diff --git a/.licenses/npm/@actions/artifact.dep.yml b/.licenses/npm/@actions/artifact.dep.yml index bc59d55..f85cc05 100644 --- a/.licenses/npm/@actions/artifact.dep.yml +++ b/.licenses/npm/@actions/artifact.dep.yml @@ -1,6 +1,6 @@ --- name: "@actions/artifact" -version: 2.1.1 +version: 2.1.5 type: npm summary: homepage: diff --git a/.licenses/npm/@actions/core.dep.yml b/.licenses/npm/@actions/core.dep.yml index 6ac109c..aecdae3 100644 --- a/.licenses/npm/@actions/core.dep.yml +++ b/.licenses/npm/@actions/core.dep.yml @@ -1,6 +1,6 @@ --- name: "@actions/core" -version: 1.10.0 +version: 1.10.1 type: npm summary: homepage: diff --git a/dist/merge/index.js b/dist/merge/index.js index 64b7b97..9e4bd2e 100644 --- a/dist/merge/index.js +++ b/dist/merge/index.js @@ -2328,6 +2328,9 @@ var __importDefault = (this && this.__importDefault) || function (mod) { Object.defineProperty(exports, "__esModule", ({ value: true })); exports.downloadArtifactInternal = exports.downloadArtifactPublic = exports.streamExtractExternal = void 0; const promises_1 = __importDefault(__nccwpck_require__(73292)); +const stream = __importStar(__nccwpck_require__(12781)); +const fs_1 = __nccwpck_require__(57147); +const path = __importStar(__nccwpck_require__(71017)); const github = __importStar(__nccwpck_require__(21260)); const core = __importStar(__nccwpck_require__(42186)); const httpClient = __importStar(__nccwpck_require__(96255)); @@ -2368,6 +2371,9 @@ function streamExtract(url, directory) { return; } catch (error) { + if (error.message.includes('Malformed extraction path')) { + throw new Error(`Artifact download failed with unretryable error: ${error.message}`); + } retryCount++; core.debug(`Failed to download artifact after ${retryCount} retries due to ${error.message}. Retrying in 5 seconds...`); // wait 5 seconds before retrying @@ -2390,6 +2396,8 @@ function streamExtractExternal(url, directory) { response.message.destroy(new Error(`Blob storage chunk did not respond in ${timeout}ms`)); }; const timer = setTimeout(timerFn, timeout); + const createdDirectories = new Set(); + createdDirectories.add(directory); response.message .on('data', () => { timer.refresh(); @@ -2399,11 +2407,47 @@ function streamExtractExternal(url, directory) { clearTimeout(timer); reject(error); }) - .pipe(unzip_stream_1.default.Extract({ path: directory })) - .on('close', () => { + .pipe(unzip_stream_1.default.Parse()) + .pipe(new stream.Transform({ + objectMode: true, + transform: (entry, _, callback) => __awaiter(this, void 0, void 0, function* () { + const fullPath = path.normalize(path.join(directory, entry.path)); + if (!directory.endsWith(path.sep)) { + directory += path.sep; + } + if (!fullPath.startsWith(directory)) { + reject(new Error(`Malformed extraction path: ${fullPath}`)); + } + if (entry.type === 'Directory') { + if (!createdDirectories.has(fullPath)) { + createdDirectories.add(fullPath); + yield resolveOrCreateDirectory(fullPath).then(() => { + entry.autodrain(); + callback(); + }); + } + else { + entry.autodrain(); + callback(); + } + } + else { + core.info(`Extracting artifact entry: ${fullPath}`); + if (!createdDirectories.has(path.dirname(fullPath))) { + createdDirectories.add(path.dirname(fullPath)); + yield resolveOrCreateDirectory(path.dirname(fullPath)); + } + const writeStream = (0, fs_1.createWriteStream)(fullPath); + writeStream.on('finish', callback); + writeStream.on('error', reject); + entry.pipe(writeStream); + } + }) + })) + .on('finish', () => __awaiter(this, void 0, void 0, function* () { clearTimeout(timer); resolve(); - }) + })) .on('error', (error) => { reject(error); }); @@ -3297,14 +3341,34 @@ const errors_1 = __nccwpck_require__(38182); function uploadZipToBlobStorage(authenticatedUploadURL, zipUploadStream) { return __awaiter(this, void 0, void 0, function* () { let uploadByteCount = 0; + let lastProgressTime = Date.now(); + let timeoutId; + const chunkTimer = (timeout) => { + // clear the previous timeout + if (timeoutId) { + clearTimeout(timeoutId); + } + timeoutId = setTimeout(() => { + const now = Date.now(); + // if there's been more than 30 seconds since the + // last progress event, then we'll consider the upload stalled + if (now - lastProgressTime > timeout) { + throw new Error('Upload progress stalled.'); + } + }, timeout); + return timeoutId; + }; const maxConcurrency = (0, config_1.getConcurrency)(); const bufferSize = (0, config_1.getUploadChunkSize)(); const blobClient = new storage_blob_1.BlobClient(authenticatedUploadURL); const blockBlobClient = blobClient.getBlockBlobClient(); + const timeoutDuration = 300000; // 30 seconds core.debug(`Uploading artifact zip to blob storage with maxConcurrency: ${maxConcurrency}, bufferSize: ${bufferSize}`); const uploadCallback = (progress) => { core.info(`Uploaded bytes ${progress.loadedBytes}`); uploadByteCount = progress.loadedBytes; + chunkTimer(timeoutDuration); + lastProgressTime = Date.now(); }; const options = { blobHTTPHeaders: { blobContentType: 'zip' }, @@ -3317,6 +3381,8 @@ function uploadZipToBlobStorage(authenticatedUploadURL, zipUploadStream) { zipUploadStream.pipe(hashStream).setEncoding('hex'); // This stream is used to compute a hash of the zip content that gets used. Integrity check core.info('Beginning upload of artifact content to blob storage'); try { + // Start the chunk timer + timeoutId = chunkTimer(timeoutDuration); yield blockBlobClient.uploadStream(uploadStream, bufferSize, maxConcurrency, options); } catch (error) { @@ -3325,6 +3391,12 @@ function uploadZipToBlobStorage(authenticatedUploadURL, zipUploadStream) { } throw error; } + finally { + // clear the timeout whether or not the upload completes + if (timeoutId) { + clearTimeout(timeoutId); + } + } core.info('Finished uploading artifact content to blob storage!'); hashStream.end(); sha256Hash = hashStream.read(); @@ -4601,7 +4673,7 @@ class OidcClient { .catch(error => { throw new Error(`Failed to get ID Token. \n Error Code : ${error.statusCode}\n - Error Message: ${error.result.message}`); + Error Message: ${error.message}`); }); const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; if (!id_token) { @@ -55371,6 +55443,141 @@ class ReflectionTypeCheck { exports.ReflectionTypeCheck = ReflectionTypeCheck; +/***/ }), + +/***/ 61659: +/***/ ((module, exports, __nccwpck_require__) => { + +"use strict"; +/** + * @author Toru Nagashima + * See LICENSE file in root directory for full license. + */ + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var eventTargetShim = __nccwpck_require__(84697); + +/** + * The signal class. + * @see https://dom.spec.whatwg.org/#abortsignal + */ +class AbortSignal extends eventTargetShim.EventTarget { + /** + * AbortSignal cannot be constructed directly. + */ + constructor() { + super(); + throw new TypeError("AbortSignal cannot be constructed directly"); + } + /** + * Returns `true` if this `AbortSignal`'s `AbortController` has signaled to abort, and `false` otherwise. + */ + get aborted() { + const aborted = abortedFlags.get(this); + if (typeof aborted !== "boolean") { + throw new TypeError(`Expected 'this' to be an 'AbortSignal' object, but got ${this === null ? "null" : typeof this}`); + } + return aborted; + } +} +eventTargetShim.defineEventAttribute(AbortSignal.prototype, "abort"); +/** + * Create an AbortSignal object. + */ +function createAbortSignal() { + const signal = Object.create(AbortSignal.prototype); + eventTargetShim.EventTarget.call(signal); + abortedFlags.set(signal, false); + return signal; +} +/** + * Abort a given signal. + */ +function abortSignal(signal) { + if (abortedFlags.get(signal) !== false) { + return; + } + abortedFlags.set(signal, true); + signal.dispatchEvent({ type: "abort" }); +} +/** + * Aborted flag for each instances. + */ +const abortedFlags = new WeakMap(); +// Properties should be enumerable. +Object.defineProperties(AbortSignal.prototype, { + aborted: { enumerable: true }, +}); +// `toString()` should return `"[object AbortSignal]"` +if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(AbortSignal.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortSignal", + }); +} + +/** + * The AbortController. + * @see https://dom.spec.whatwg.org/#abortcontroller + */ +class AbortController { + /** + * Initialize this controller. + */ + constructor() { + signals.set(this, createAbortSignal()); + } + /** + * Returns the `AbortSignal` object associated with this object. + */ + get signal() { + return getSignal(this); + } + /** + * Abort and signal to any observers that the associated activity is to be aborted. + */ + abort() { + abortSignal(getSignal(this)); + } +} +/** + * Associated signals. + */ +const signals = new WeakMap(); +/** + * Get the associated signal of a given controller. + */ +function getSignal(controller) { + const signal = signals.get(controller); + if (signal == null) { + throw new TypeError(`Expected 'this' to be an 'AbortController' object, but got ${controller === null ? "null" : typeof controller}`); + } + return signal; +} +// Properties should be enumerable. +Object.defineProperties(AbortController.prototype, { + signal: { enumerable: true }, + abort: { enumerable: true }, +}); +if (typeof Symbol === "function" && typeof Symbol.toStringTag === "symbol") { + Object.defineProperty(AbortController.prototype, Symbol.toStringTag, { + configurable: true, + value: "AbortController", + }); +} + +exports.AbortController = AbortController; +exports.AbortSignal = AbortSignal; +exports["default"] = AbortController; + +module.exports = AbortController +module.exports.AbortController = module.exports["default"] = AbortController +module.exports.AbortSignal = AbortSignal +//# sourceMappingURL=abort-controller.js.map + + /***/ }), /***/ 81231: @@ -55386,12 +55593,12 @@ exports.ReflectionTypeCheck = ReflectionTypeCheck; var fs = __nccwpck_require__(77758); var path = __nccwpck_require__(71017); -var flatten = __nccwpck_require__(48919); -var difference = __nccwpck_require__(89764); -var union = __nccwpck_require__(28651); -var isPlainObject = __nccwpck_require__(25723); +var flatten = __nccwpck_require__(42394); +var difference = __nccwpck_require__(44031); +var union = __nccwpck_require__(11620); +var isPlainObject = __nccwpck_require__(46169); -var glob = __nccwpck_require__(30095); +var glob = __nccwpck_require__(19834); var file = module.exports = {}; @@ -55601,23 +55808,17 @@ file.normalizeFilesArray = function(data) { */ var fs = __nccwpck_require__(77758); var path = __nccwpck_require__(71017); -var nutil = __nccwpck_require__(73837); +var isStream = __nccwpck_require__(41554); var lazystream = __nccwpck_require__(12084); var normalizePath = __nccwpck_require__(55388); -var defaults = __nccwpck_require__(11289); +var defaults = __nccwpck_require__(3508); var Stream = (__nccwpck_require__(12781).Stream); -var PassThrough = (__nccwpck_require__(44785).PassThrough); +var PassThrough = (__nccwpck_require__(45193).PassThrough); var utils = module.exports = {}; utils.file = __nccwpck_require__(81231); -function assertPath(path) { - if (typeof path !== 'string') { - throw new TypeError('Path must be a string. Received ' + nutils.inspect(path)); - } -} - utils.collectStream = function(source, callback) { var collection = []; var size = 0; @@ -55630,7 +55831,7 @@ utils.collectStream = function(source, callback) { }); source.on('end', function() { - var buf = new Buffer(size); + var buf = Buffer.alloc(size); var offset = 0; collection.forEach(function(data) { @@ -55665,7 +55866,7 @@ utils.defaults = function(object, source, guard) { }; utils.isStream = function(source) { - return source instanceof Stream; + return isStream(source); }; utils.lazyReadStream = function(filepath) { @@ -55676,14 +55877,14 @@ utils.lazyReadStream = function(filepath) { utils.normalizeInputSource = function(source) { if (source === null) { - return new Buffer(0); + return Buffer.alloc(0); } else if (typeof source === 'string') { - return new Buffer(source); - } else if (utils.isStream(source) && !source._readableState) { - var normalized = new PassThrough(); - source.pipe(normalized); - - return normalized; + return Buffer.from(source); + } else if (utils.isStream(source)) { + // Always pipe through a PassThrough stream to guarantee pausing the stream if it's already flowing, + // since it will only be processed in a (distant) future iteration of the event loop, and will lose + // data if already flowing now. + return source.pipe(new PassThrough()); } return source; @@ -55736,10 +55937,15 @@ utils.walkdir = function(dirpath, base, callback) { if (stats && stats.isDirectory()) { utils.walkdir(filepath, base, function(err, res) { + if(err){ + return callback(err); + } + res.forEach(function(dirEntry) { results.push(dirEntry); }); - next(); + + next(); }); } else { next(); @@ -55752,63175 +55958,62180 @@ utils.walkdir = function(dirpath, base, callback) { /***/ }), -/***/ 58311: +/***/ 43084: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var concatMap = __nccwpck_require__(86891); -var balanced = __nccwpck_require__(9417); - -module.exports = expandTop; - -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; - -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} - -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); -} - -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); -} - - -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; +/** + * Archiver Vending + * + * @ignore + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ +var Archiver = __nccwpck_require__(35010); - var parts = []; - var m = balanced('{', '}', str); +var formats = {}; - if (!m) - return str.split(','); +/** + * Dispenses a new Archiver instance. + * + * @constructor + * @param {String} format The archive format to use. + * @param {Object} options See [Archiver]{@link Archiver} + * @return {Archiver} + */ +var vending = function(format, options) { + return vending.create(format, options); +}; - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); +/** + * Creates a new Archiver instance. + * + * @param {String} format The archive format to use. + * @param {Object} options See [Archiver]{@link Archiver} + * @return {Archiver} + */ +vending.create = function(format, options) { + if (formats[format]) { + var instance = new Archiver(format, options); + instance.setFormat(format); + instance.setModule(new formats[format](options)); - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); + return instance; + } else { + throw new Error('create(' + format + '): format not registered'); } +}; - parts.push.apply(parts, p); - - return parts; -} - -function expandTop(str) { - if (!str) - return []; - - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); +/** + * Registers a format for use with archiver. + * + * @param {String} format The name of the format. + * @param {Function} module The function for archiver to interact with. + * @return void + */ +vending.registerFormat = function(format, module) { + if (formats[format]) { + throw new Error('register(' + format + '): format already registered'); } - return expand(escapeBraces(str), true).map(unescapeBraces); -} - -function identity(e) { - return e; -} - -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} - -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} + if (typeof module !== 'function') { + throw new Error('register(' + format + '): format module invalid'); + } -function expand(str, isTop) { - var expansions = []; + if (typeof module.prototype.append !== 'function' || typeof module.prototype.finalize !== 'function') { + throw new Error('register(' + format + '): format module missing methods'); + } - var m = balanced('{', '}', str); - if (!m || /\$$/.test(m.pre)) return [str]; + formats[format] = module; +}; - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); - } - return [str]; +/** + * Check if the format is already registered. + * + * @param {String} format the name of the format. + * @return boolean + */ +vending.isRegisteredFormat = function (format) { + if (formats[format]) { + return true; } + + return false; +}; - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - var post = m.post.length - ? expand(m.post, false) - : ['']; - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } - } - } +vending.registerFormat('zip', __nccwpck_require__(8987)); +vending.registerFormat('tar', __nccwpck_require__(33614)); +vending.registerFormat('json', __nccwpck_require__(99827)); - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. +module.exports = vending; - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; +/***/ }), - var N; +/***/ 35010: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; - } - var pad = n.some(isPadded); +/** + * Archiver Core + * + * @ignore + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ +var fs = __nccwpck_require__(57147); +var glob = __nccwpck_require__(44967); +var async = __nccwpck_require__(57888); +var path = __nccwpck_require__(71017); +var util = __nccwpck_require__(82072); - N = []; +var inherits = (__nccwpck_require__(73837).inherits); +var ArchiverError = __nccwpck_require__(13143); +var Transform = (__nccwpck_require__(45193).Transform); - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); - } - } else { - N = concatMap(n, function(el) { return expand(el, false) }); - } +var win32 = process.platform === 'win32'; - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); - } +/** + * @constructor + * @param {String} format The archive format to use. + * @param {(CoreOptions|TransformOptions)} options See also {@link ZipOptions} and {@link TarOptions}. + */ +var Archiver = function(format, options) { + if (!(this instanceof Archiver)) { + return new Archiver(format, options); } - return expansions; -} + if (typeof format !== 'string') { + options = format; + format = 'zip'; + } + options = this.options = util.defaults(options, { + highWaterMark: 1024 * 1024, + statConcurrency: 4 + }); + Transform.call(this, options); -/***/ }), + this._format = false; + this._module = false; + this._pending = 0; + this._pointer = 0; -/***/ 84938: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this._entriesCount = 0; + this._entriesProcessedCount = 0; + this._fsEntriesTotalBytes = 0; + this._fsEntriesProcessedBytes = 0; -exports.setopts = setopts -exports.ownProp = ownProp -exports.makeAbs = makeAbs -exports.finish = finish -exports.mark = mark -exports.isIgnored = isIgnored -exports.childrenIgnored = childrenIgnored + this._queue = async.queue(this._onQueueTask.bind(this), 1); + this._queue.drain(this._onQueueDrain.bind(this)); -function ownProp (obj, field) { - return Object.prototype.hasOwnProperty.call(obj, field) -} + this._statQueue = async.queue(this._onStatQueueTask.bind(this), options.statConcurrency); + this._statQueue.drain(this._onQueueDrain.bind(this)); -var fs = __nccwpck_require__(57147) -var path = __nccwpck_require__(71017) -var minimatch = __nccwpck_require__(8487) -var isAbsolute = __nccwpck_require__(38714) -var Minimatch = minimatch.Minimatch + this._state = { + aborted: false, + finalize: false, + finalizing: false, + finalized: false, + modulePiped: false + }; -function alphasort (a, b) { - return a.localeCompare(b, 'en') -} + this._streams = []; +}; -function setupIgnores (self, options) { - self.ignore = options.ignore || [] +inherits(Archiver, Transform); - if (!Array.isArray(self.ignore)) - self.ignore = [self.ignore] +/** + * Internal logic for `abort`. + * + * @private + * @return void + */ +Archiver.prototype._abort = function() { + this._state.aborted = true; + this._queue.kill(); + this._statQueue.kill(); - if (self.ignore.length) { - self.ignore = self.ignore.map(ignoreMap) + if (this._queue.idle()) { + this._shutdown(); } -} +}; -// ignore patterns are always in dot:true mode. -function ignoreMap (pattern) { - var gmatcher = null - if (pattern.slice(-3) === '/**') { - var gpattern = pattern.replace(/(\/\*\*)+$/, '') - gmatcher = new Minimatch(gpattern, { dot: true }) - } +/** + * Internal helper for appending files. + * + * @private + * @param {String} filepath The source filepath. + * @param {EntryData} data The entry data. + * @return void + */ +Archiver.prototype._append = function(filepath, data) { + data = data || {}; - return { - matcher: new Minimatch(pattern, { dot: true }), - gmatcher: gmatcher - } -} - -function setopts (self, pattern, options) { - if (!options) - options = {} - - // base-matching: just use globstar for that. - if (options.matchBase && -1 === pattern.indexOf("/")) { - if (options.noglobstar) { - throw new Error("base matching requires globstar") - } - pattern = "**/" + pattern - } - - self.silent = !!options.silent - self.pattern = pattern - self.strict = options.strict !== false - self.realpath = !!options.realpath - self.realpathCache = options.realpathCache || Object.create(null) - self.follow = !!options.follow - self.dot = !!options.dot - self.mark = !!options.mark - self.nodir = !!options.nodir - if (self.nodir) - self.mark = true - self.sync = !!options.sync - self.nounique = !!options.nounique - self.nonull = !!options.nonull - self.nosort = !!options.nosort - self.nocase = !!options.nocase - self.stat = !!options.stat - self.noprocess = !!options.noprocess - self.absolute = !!options.absolute - self.fs = options.fs || fs - - self.maxLength = options.maxLength || Infinity - self.cache = options.cache || Object.create(null) - self.statCache = options.statCache || Object.create(null) - self.symlinks = options.symlinks || Object.create(null) - - setupIgnores(self, options) - - self.changedCwd = false - var cwd = process.cwd() - if (!ownProp(options, "cwd")) - self.cwd = cwd - else { - self.cwd = path.resolve(options.cwd) - self.changedCwd = self.cwd !== cwd - } - - self.root = options.root || path.resolve(self.cwd, "/") - self.root = path.resolve(self.root) - if (process.platform === "win32") - self.root = self.root.replace(/\\/g, "/") - - // TODO: is an absolute `cwd` supposed to be resolved against `root`? - // e.g. { cwd: '/test', root: __dirname } === path.join(__dirname, '/test') - self.cwdAbs = isAbsolute(self.cwd) ? self.cwd : makeAbs(self, self.cwd) - if (process.platform === "win32") - self.cwdAbs = self.cwdAbs.replace(/\\/g, "/") - self.nomount = !!options.nomount - - // disable comments and negation in Minimatch. - // Note that they are not supported in Glob itself anyway. - options.nonegate = true - options.nocomment = true - // always treat \ in patterns as escapes, not path separators - options.allowWindowsEscape = false - - self.minimatch = new Minimatch(pattern, options) - self.options = self.minimatch.options -} - -function finish (self) { - var nou = self.nounique - var all = nou ? [] : Object.create(null) - - for (var i = 0, l = self.matches.length; i < l; i ++) { - var matches = self.matches[i] - if (!matches || Object.keys(matches).length === 0) { - if (self.nonull) { - // do like the shell, and spit out the literal glob - var literal = self.minimatch.globSet[i] - if (nou) - all.push(literal) - else - all[literal] = true - } - } else { - // had matches - var m = Object.keys(matches) - if (nou) - all.push.apply(all, m) - else - m.forEach(function (m) { - all[m] = true - }) - } + var task = { + source: null, + filepath: filepath + }; + + if (!data.name) { + data.name = filepath; } - if (!nou) - all = Object.keys(all) + data.sourcePath = filepath; + task.data = data; + this._entriesCount++; - if (!self.nosort) - all = all.sort(alphasort) + if (data.stats && data.stats instanceof fs.Stats) { + task = this._updateQueueTaskWithStats(task, data.stats); + if (task) { + if (data.stats.size) { + this._fsEntriesTotalBytes += data.stats.size; + } - // at *some* point we statted all of these - if (self.mark) { - for (var i = 0; i < all.length; i++) { - all[i] = self._mark(all[i]) - } - if (self.nodir) { - all = all.filter(function (e) { - var notDir = !(/\/$/.test(e)) - var c = self.cache[e] || self.cache[makeAbs(self, e)] - if (notDir && c) - notDir = c !== 'DIR' && !Array.isArray(c) - return notDir - }) + this._queue.push(task); } + } else { + this._statQueue.push(task); } +}; - if (self.ignore.length) - all = all.filter(function(m) { - return !isIgnored(self, m) - }) +/** + * Internal logic for `finalize`. + * + * @private + * @return void + */ +Archiver.prototype._finalize = function() { + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + return; + } - self.found = all -} + this._state.finalizing = true; -function mark (self, p) { - var abs = makeAbs(self, p) - var c = self.cache[abs] - var m = p - if (c) { - var isDir = c === 'DIR' || Array.isArray(c) - var slash = p.slice(-1) === '/' + this._moduleFinalize(); - if (isDir && !slash) - m += '/' - else if (!isDir && slash) - m = m.slice(0, -1) + this._state.finalizing = false; + this._state.finalized = true; +}; - if (m !== p) { - var mabs = makeAbs(self, m) - self.statCache[mabs] = self.statCache[abs] - self.cache[mabs] = self.cache[abs] - } +/** + * Checks the various state variables to determine if we can `finalize`. + * + * @private + * @return {Boolean} + */ +Archiver.prototype._maybeFinalize = function() { + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + return false; } - return m -} - -// lotta situps... -function makeAbs (self, f) { - var abs = f - if (f.charAt(0) === '/') { - abs = path.join(self.root, f) - } else if (isAbsolute(f) || f === '') { - abs = f - } else if (self.changedCwd) { - abs = path.resolve(self.cwd, f) - } else { - abs = path.resolve(f) + if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { + this._finalize(); + return true; } - if (process.platform === 'win32') - abs = abs.replace(/\\/g, '/') - - return abs -} - + return false; +}; -// Return true, if pattern ends with globstar '**', for the accompanying parent directory. -// Ex:- If node_modules/** is the pattern, add 'node_modules' to ignore list along with it's contents -function isIgnored (self, path) { - if (!self.ignore.length) - return false +/** + * Appends an entry to the module. + * + * @private + * @fires Archiver#entry + * @param {(Buffer|Stream)} source + * @param {EntryData} data + * @param {Function} callback + * @return void + */ +Archiver.prototype._moduleAppend = function(source, data, callback) { + if (this._state.aborted) { + callback(); + return; + } - return self.ignore.some(function(item) { - return item.matcher.match(path) || !!(item.gmatcher && item.gmatcher.match(path)) - }) -} + this._module.append(source, data, function(err) { + this._task = null; -function childrenIgnored (self, path) { - if (!self.ignore.length) - return false + if (this._state.aborted) { + this._shutdown(); + return; + } - return self.ignore.some(function(item) { - return !!(item.gmatcher && item.gmatcher.match(path)) - }) -} + if (err) { + this.emit('error', err); + setImmediate(callback); + return; + } + /** + * Fires when the entry's input has been processed and appended to the archive. + * + * @event Archiver#entry + * @type {EntryData} + */ + this.emit('entry', data); + this._entriesProcessedCount++; -/***/ }), + if (data.stats && data.stats.size) { + this._fsEntriesProcessedBytes += data.stats.size; + } -/***/ 30095: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * @event Archiver#progress + * @type {ProgressData} + */ + this.emit('progress', { + entries: { + total: this._entriesCount, + processed: this._entriesProcessedCount + }, + fs: { + totalBytes: this._fsEntriesTotalBytes, + processedBytes: this._fsEntriesProcessedBytes + } + }); -// Approach: -// -// 1. Get the minimatch set -// 2. For each pattern in the set, PROCESS(pattern, false) -// 3. Store matches per-set, then uniq them -// -// PROCESS(pattern, inGlobStar) -// Get the first [n] items from pattern that are all strings -// Join these together. This is PREFIX. -// If there is no more remaining, then stat(PREFIX) and -// add to matches if it succeeds. END. -// -// If inGlobStar and PREFIX is symlink and points to dir -// set ENTRIES = [] -// else readdir(PREFIX) as ENTRIES -// If fail, END -// -// with ENTRIES -// If pattern[n] is GLOBSTAR -// // handle the case where the globstar match is empty -// // by pruning it out, and testing the resulting pattern -// PROCESS(pattern[0..n] + pattern[n+1 .. $], false) -// // handle other cases. -// for ENTRY in ENTRIES (not dotfiles) -// // attach globstar + tail onto the entry -// // Mark that this entry is a globstar match -// PROCESS(pattern[0..n] + ENTRY + pattern[n .. $], true) -// -// else // not globstar -// for ENTRY in ENTRIES (not dotfiles, unless pattern[n] is dot) -// Test ENTRY against pattern[n] -// If fails, continue -// If passes, PROCESS(pattern[0..n] + item + pattern[n+1 .. $]) -// -// Caveat: -// Cache all stats and readdirs results to minimize syscall. Since all -// we ever care about is existence and directory-ness, we can just keep -// `true` for files, and [children,...] for directories, or `false` for -// things that don't exist. - -module.exports = glob - -var rp = __nccwpck_require__(46863) -var minimatch = __nccwpck_require__(8487) -var Minimatch = minimatch.Minimatch -var inherits = __nccwpck_require__(44124) -var EE = (__nccwpck_require__(82361).EventEmitter) -var path = __nccwpck_require__(71017) -var assert = __nccwpck_require__(39491) -var isAbsolute = __nccwpck_require__(38714) -var globSync = __nccwpck_require__(57388) -var common = __nccwpck_require__(84938) -var setopts = common.setopts -var ownProp = common.ownProp -var inflight = __nccwpck_require__(52492) -var util = __nccwpck_require__(73837) -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored + setImmediate(callback); + }.bind(this)); +}; -var once = __nccwpck_require__(1223) +/** + * Finalizes the module. + * + * @private + * @return void + */ +Archiver.prototype._moduleFinalize = function() { + if (typeof this._module.finalize === 'function') { + this._module.finalize(); + } else if (typeof this._module.end === 'function') { + this._module.end(); + } else { + this.emit('error', new ArchiverError('NOENDMETHOD')); + } +}; -function glob (pattern, options, cb) { - if (typeof options === 'function') cb = options, options = {} - if (!options) options = {} +/** + * Pipes the module to our internal stream with error bubbling. + * + * @private + * @return void + */ +Archiver.prototype._modulePipe = function() { + this._module.on('error', this._onModuleError.bind(this)); + this._module.pipe(this); + this._state.modulePiped = true; +}; - if (options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return globSync(pattern, options) +/** + * Determines if the current module supports a defined feature. + * + * @private + * @param {String} key + * @return {Boolean} + */ +Archiver.prototype._moduleSupports = function(key) { + if (!this._module.supports || !this._module.supports[key]) { + return false; } - return new Glob(pattern, options, cb) -} - -glob.sync = globSync -var GlobSync = glob.GlobSync = globSync.GlobSync + return this._module.supports[key]; +}; -// old api surface -glob.glob = glob +/** + * Unpipes the module from our internal stream. + * + * @private + * @return void + */ +Archiver.prototype._moduleUnpipe = function() { + this._module.unpipe(this); + this._state.modulePiped = false; +}; -function extend (origin, add) { - if (add === null || typeof add !== 'object') { - return origin - } +/** + * Normalizes entry data with fallbacks for key properties. + * + * @private + * @param {Object} data + * @param {fs.Stats} stats + * @return {Object} + */ +Archiver.prototype._normalizeEntryData = function(data, stats) { + data = util.defaults(data, { + type: 'file', + name: null, + date: null, + mode: null, + prefix: null, + sourcePath: null, + stats: false + }); - var keys = Object.keys(add) - var i = keys.length - while (i--) { - origin[keys[i]] = add[keys[i]] + if (stats && data.stats === false) { + data.stats = stats; } - return origin -} -glob.hasMagic = function (pattern, options_) { - var options = extend({}, options_) - options.noprocess = true - - var g = new Glob(pattern, options) - var set = g.minimatch.set + var isDir = data.type === 'directory'; - if (!pattern) - return false + if (data.name) { + if (typeof data.prefix === 'string' && '' !== data.prefix) { + data.name = data.prefix + '/' + data.name; + data.prefix = null; + } - if (set.length > 1) - return true + data.name = util.sanitizePath(data.name); - for (var j = 0; j < set[0].length; j++) { - if (typeof set[0][j] !== 'string') - return true + if (data.type !== 'symlink' && data.name.slice(-1) === '/') { + isDir = true; + data.type = 'directory'; + } else if (isDir) { + data.name += '/'; + } } - return false -} + // 511 === 0777; 493 === 0755; 438 === 0666; 420 === 0644 + if (typeof data.mode === 'number') { + if (win32) { + data.mode &= 511; + } else { + data.mode &= 4095 + } + } else if (data.stats && data.mode === null) { + if (win32) { + data.mode = data.stats.mode & 511; + } else { + data.mode = data.stats.mode & 4095; + } -glob.Glob = Glob -inherits(Glob, EE) -function Glob (pattern, options, cb) { - if (typeof options === 'function') { - cb = options - options = null + // stat isn't reliable on windows; force 0755 for dir + if (win32 && isDir) { + data.mode = 493; + } + } else if (data.mode === null) { + data.mode = isDir ? 493 : 420; } - if (options && options.sync) { - if (cb) - throw new TypeError('callback provided to sync glob') - return new GlobSync(pattern, options) + if (data.stats && data.date === null) { + data.date = data.stats.mtime; + } else { + data.date = util.dateify(data.date); } - if (!(this instanceof Glob)) - return new Glob(pattern, options, cb) - - setopts(this, pattern, options) - this._didRealPath = false - - // process each pattern in the minimatch set - var n = this.minimatch.set.length + return data; +}; - // The matches are stored as {: true,...} so that - // duplicates are automagically pruned. - // Later, we do an Object.keys() on these. - // Keep them as a list so we can fill in when nonull is set. - this.matches = new Array(n) +/** + * Error listener that re-emits error on to our internal stream. + * + * @private + * @param {Error} err + * @return void + */ +Archiver.prototype._onModuleError = function(err) { + /** + * @event Archiver#error + * @type {ErrorData} + */ + this.emit('error', err); +}; - if (typeof cb === 'function') { - cb = once(cb) - this.on('error', cb) - this.on('end', function (matches) { - cb(null, matches) - }) +/** + * Checks the various state variables after queue has drained to determine if + * we need to `finalize`. + * + * @private + * @return void + */ +Archiver.prototype._onQueueDrain = function() { + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + return; } - var self = this - this._processing = 0 - - this._emitQueue = [] - this._processQueue = [] - this.paused = false - - if (this.noprocess) - return this - - if (n === 0) - return done() - - var sync = true - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false, done) + if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { + this._finalize(); } - sync = false +}; - function done () { - --self._processing - if (self._processing <= 0) { - if (sync) { - process.nextTick(function () { - self._finish() - }) - } else { - self._finish() - } +/** + * Appends each queue task to the module. + * + * @private + * @param {Object} task + * @param {Function} callback + * @return void + */ +Archiver.prototype._onQueueTask = function(task, callback) { + var fullCallback = () => { + if(task.data.callback) { + task.data.callback(); } + callback(); } -} - -Glob.prototype._finish = function () { - assert(this instanceof Glob) - if (this.aborted) - return - if (this.realpath && !this._didRealpath) - return this._realpath() - - common.finish(this) - this.emit('end', this.found) -} - -Glob.prototype._realpath = function () { - if (this._didRealpath) - return - - this._didRealpath = true - - var n = this.matches.length - if (n === 0) - return this._finish() + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + fullCallback(); + return; + } - var self = this - for (var i = 0; i < this.matches.length; i++) - this._realpathSet(i, next) + this._task = task; + this._moduleAppend(task.source, task.data, fullCallback); +}; - function next () { - if (--n === 0) - self._finish() +/** + * Performs a file stat and reinjects the task back into the queue. + * + * @private + * @param {Object} task + * @param {Function} callback + * @return void + */ +Archiver.prototype._onStatQueueTask = function(task, callback) { + if (this._state.finalizing || this._state.finalized || this._state.aborted) { + callback(); + return; } -} -Glob.prototype._realpathSet = function (index, cb) { - var matchset = this.matches[index] - if (!matchset) - return cb() + fs.lstat(task.filepath, function(err, stats) { + if (this._state.aborted) { + setImmediate(callback); + return; + } - var found = Object.keys(matchset) - var self = this - var n = found.length + if (err) { + this._entriesCount--; - if (n === 0) - return cb() + /** + * @event Archiver#warning + * @type {ErrorData} + */ + this.emit('warning', err); + setImmediate(callback); + return; + } - var set = this.matches[index] = Object.create(null) - found.forEach(function (p, i) { - // If there's a problem with the stat, then it means that - // one or more of the links in the realpath couldn't be - // resolved. just return the abs value in that case. - p = self._makeAbs(p) - rp.realpath(p, self.realpathCache, function (er, real) { - if (!er) - set[real] = true - else if (er.syscall === 'stat') - set[p] = true - else - self.emit('error', er) // srsly wtf right here + task = this._updateQueueTaskWithStats(task, stats); - if (--n === 0) { - self.matches[index] = set - cb() + if (task) { + if (stats.size) { + this._fsEntriesTotalBytes += stats.size; } - }) - }) -} - -Glob.prototype._mark = function (p) { - return common.mark(this, p) -} -Glob.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} + this._queue.push(task); + } -Glob.prototype.abort = function () { - this.aborted = true - this.emit('abort') -} + setImmediate(callback); + }.bind(this)); +}; -Glob.prototype.pause = function () { - if (!this.paused) { - this.paused = true - this.emit('pause') - } -} +/** + * Unpipes the module and ends our internal stream. + * + * @private + * @return void + */ +Archiver.prototype._shutdown = function() { + this._moduleUnpipe(); + this.end(); +}; -Glob.prototype.resume = function () { - if (this.paused) { - this.emit('resume') - this.paused = false - if (this._emitQueue.length) { - var eq = this._emitQueue.slice(0) - this._emitQueue.length = 0 - for (var i = 0; i < eq.length; i ++) { - var e = eq[i] - this._emitMatch(e[0], e[1]) - } - } - if (this._processQueue.length) { - var pq = this._processQueue.slice(0) - this._processQueue.length = 0 - for (var i = 0; i < pq.length; i ++) { - var p = pq[i] - this._processing-- - this._process(p[0], p[1], p[2], p[3]) - } - } +/** + * Tracks the bytes emitted by our internal stream. + * + * @private + * @param {Buffer} chunk + * @param {String} encoding + * @param {Function} callback + * @return void + */ +Archiver.prototype._transform = function(chunk, encoding, callback) { + if (chunk) { + this._pointer += chunk.length; } -} -Glob.prototype._process = function (pattern, index, inGlobStar, cb) { - assert(this instanceof Glob) - assert(typeof cb === 'function') + callback(null, chunk); +}; - if (this.aborted) - return +/** + * Updates and normalizes a queue task using stats data. + * + * @private + * @param {Object} task + * @param {fs.Stats} stats + * @return {Object} + */ +Archiver.prototype._updateQueueTaskWithStats = function(task, stats) { + if (stats.isFile()) { + task.data.type = 'file'; + task.data.sourceType = 'stream'; + task.source = util.lazyReadStream(task.filepath); + } else if (stats.isDirectory() && this._moduleSupports('directory')) { + task.data.name = util.trailingSlashIt(task.data.name); + task.data.type = 'directory'; + task.data.sourcePath = util.trailingSlashIt(task.filepath); + task.data.sourceType = 'buffer'; + task.source = Buffer.concat([]); + } else if (stats.isSymbolicLink() && this._moduleSupports('symlink')) { + var linkPath = fs.readlinkSync(task.filepath); + var dirName = path.dirname(task.filepath); + task.data.type = 'symlink'; + task.data.linkname = path.relative(dirName, path.resolve(dirName, linkPath)); + task.data.sourceType = 'buffer'; + task.source = Buffer.concat([]); + } else { + if (stats.isDirectory()) { + this.emit('warning', new ArchiverError('DIRECTORYNOTSUPPORTED', task.data)); + } else if (stats.isSymbolicLink()) { + this.emit('warning', new ArchiverError('SYMLINKNOTSUPPORTED', task.data)); + } else { + this.emit('warning', new ArchiverError('ENTRYNOTSUPPORTED', task.data)); + } - this._processing++ - if (this.paused) { - this._processQueue.push([pattern, index, inGlobStar, cb]) - return + return null; } - //console.error('PROCESS %d', this._processing, pattern) + task.data = this._normalizeEntryData(task.data, stats); + + return task; +}; - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ +/** + * Aborts the archiving process, taking a best-effort approach, by: + * + * - removing any pending queue tasks + * - allowing any active queue workers to finish + * - detaching internal module pipes + * - ending both sides of the Transform stream + * + * It will NOT drain any remaining sources. + * + * @return {this} + */ +Archiver.prototype.abort = function() { + if (this._state.aborted || this._state.finalized) { + return this; } - // now n is the index of the first one that is *not* a string. - // see if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index, cb) - return + this._abort(); - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break + return this; +}; - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break +/** + * Appends an input source (text string, buffer, or stream) to the instance. + * + * When the instance has received, processed, and emitted the input, the `entry` + * event is fired. + * + * @fires Archiver#entry + * @param {(Buffer|Stream|String)} source The input source. + * @param {EntryData} data See also {@link ZipEntryData} and {@link TarEntryData}. + * @return {this} + */ +Archiver.prototype.append = function(source, data) { + if (this._state.finalize || this._state.aborted) { + this.emit('error', new ArchiverError('QUEUECLOSED')); + return this; } - var remain = pattern.slice(n) - - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || - isAbsolute(pattern.map(function (p) { - return typeof p === 'string' ? p : '[*]' - }).join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix + data = this._normalizeEntryData(data); - var abs = this._makeAbs(read) + if (typeof data.name !== 'string' || data.name.length === 0) { + this.emit('error', new ArchiverError('ENTRYNAMEREQUIRED')); + return this; + } - //if ignored, skip _processing - if (childrenIgnored(this, read)) - return cb() + if (data.type === 'directory' && !this._moduleSupports('directory')) { + this.emit('error', new ArchiverError('DIRECTORYNOTSUPPORTED', { name: data.name })); + return this; + } - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar, cb) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar, cb) -} + source = util.normalizeInputSource(source); -Glob.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - return self._processReaddir2(prefix, read, abs, remain, index, inGlobStar, entries, cb) - }) -} + if (Buffer.isBuffer(source)) { + data.sourceType = 'buffer'; + } else if (util.isStream(source)) { + data.sourceType = 'stream'; + } else { + this.emit('error', new ArchiverError('INPUTSTEAMBUFFERREQUIRED', { name: data.name })); + return this; + } -Glob.prototype._processReaddir2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { + this._entriesCount++; + this._queue.push({ + data: data, + source: source + }); - // if the abs isn't a dir, then nothing can match! - if (!entries) - return cb() + return this; +}; - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' - - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) - } +/** + * Appends a directory and its files, recursively, given its dirpath. + * + * @param {String} dirpath The source directory path. + * @param {String} destpath The destination path within the archive. + * @param {(EntryData|Function)} data See also [ZipEntryData]{@link ZipEntryData} and + * [TarEntryData]{@link TarEntryData}. + * @return {this} + */ +Archiver.prototype.directory = function(dirpath, destpath, data) { + if (this._state.finalize || this._state.aborted) { + this.emit('error', new ArchiverError('QUEUECLOSED')); + return this; } - //console.error('prd2', prefix, entries, remain[0]._glob, matchedEntries) + if (typeof dirpath !== 'string' || dirpath.length === 0) { + this.emit('error', new ArchiverError('DIRECTORYDIRPATHREQUIRED')); + return this; + } - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return cb() + this._pending++; - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. + if (destpath === false) { + destpath = ''; + } else if (typeof destpath !== 'string'){ + destpath = dirpath; + } - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) + var dataFunction = false; + if (typeof data === 'function') { + dataFunction = data; + data = {}; + } else if (typeof data !== 'object') { + data = {}; + } - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e - } + var globOptions = { + stat: true, + dot: true + }; - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this._emitMatch(index, e) - } - // This was the last one, and no stats were needed - return cb() + function onGlobEnd() { + this._pending--; + this._maybeFinalize(); } - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) { - if (prefix !== '/') - e = prefix + '/' + e - else - e = prefix + e - } - this._process([e].concat(remain), index, inGlobStar, cb) + function onGlobError(err) { + this.emit('error', err); } - cb() -} -Glob.prototype._emitMatch = function (index, e) { - if (this.aborted) - return + function onGlobMatch(match){ + globber.pause(); - if (isIgnored(this, e)) - return - - if (this.paused) { - this._emitQueue.push([index, e]) - return - } - - var abs = isAbsolute(e) ? e : this._makeAbs(e) + var ignoreMatch = false; + var entryData = Object.assign({}, data); + entryData.name = match.relative; + entryData.prefix = destpath; + entryData.stats = match.stat; + entryData.callback = globber.resume.bind(globber); - if (this.mark) - e = this._mark(e) + try { + if (dataFunction) { + entryData = dataFunction(entryData); - if (this.absolute) - e = abs + if (entryData === false) { + ignoreMatch = true; + } else if (typeof entryData !== 'object') { + throw new ArchiverError('DIRECTORYFUNCTIONINVALIDDATA', { dirpath: dirpath }); + } + } + } catch(e) { + this.emit('error', e); + return; + } - if (this.matches[index][e]) - return + if (ignoreMatch) { + globber.resume(); + return; + } - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return + this._append(match.absolute, entryData); } - this.matches[index][e] = true + var globber = glob(dirpath, globOptions); + globber.on('error', onGlobError.bind(this)); + globber.on('match', onGlobMatch.bind(this)); + globber.on('end', onGlobEnd.bind(this)); - var st = this.statCache[abs] - if (st) - this.emit('stat', e, st) + return this; +}; - this.emit('match', e) -} +/** + * Appends a file given its filepath using a + * [lazystream]{@link https://github.com/jpommerening/node-lazystream} wrapper to + * prevent issues with open file limits. + * + * When the instance has received, processed, and emitted the file, the `entry` + * event is fired. + * + * @param {String} filepath The source filepath. + * @param {EntryData} data See also [ZipEntryData]{@link ZipEntryData} and + * [TarEntryData]{@link TarEntryData}. + * @return {this} + */ +Archiver.prototype.file = function(filepath, data) { + if (this._state.finalize || this._state.aborted) { + this.emit('error', new ArchiverError('QUEUECLOSED')); + return this; + } -Glob.prototype._readdirInGlobStar = function (abs, cb) { - if (this.aborted) - return + if (typeof filepath !== 'string' || filepath.length === 0) { + this.emit('error', new ArchiverError('FILEFILEPATHREQUIRED')); + return this; + } - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false, cb) + this._append(filepath, data); - var lstatkey = 'lstat\0' + abs - var self = this - var lstatcb = inflight(lstatkey, lstatcb_) + return this; +}; - if (lstatcb) - self.fs.lstat(abs, lstatcb) +/** + * Appends multiple files that match a glob pattern. + * + * @param {String} pattern The [glob pattern]{@link https://github.com/isaacs/minimatch} to match. + * @param {Object} options See [node-readdir-glob]{@link https://github.com/yqnn/node-readdir-glob#options}. + * @param {EntryData} data See also [ZipEntryData]{@link ZipEntryData} and + * [TarEntryData]{@link TarEntryData}. + * @return {this} + */ +Archiver.prototype.glob = function(pattern, options, data) { + this._pending++; - function lstatcb_ (er, lstat) { - if (er && er.code === 'ENOENT') - return cb() + options = util.defaults(options, { + stat: true, + pattern: pattern + }); - var isSym = lstat && lstat.isSymbolicLink() - self.symlinks[abs] = isSym + function onGlobEnd() { + this._pending--; + this._maybeFinalize(); + } - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) { - self.cache[abs] = 'FILE' - cb() - } else - self._readdir(abs, false, cb) + function onGlobError(err) { + this.emit('error', err); } -} -Glob.prototype._readdir = function (abs, inGlobStar, cb) { - if (this.aborted) - return + function onGlobMatch(match){ + globber.pause(); + var entryData = Object.assign({}, data); + entryData.callback = globber.resume.bind(globber); + entryData.stats = match.stat; + entryData.name = match.relative; - cb = inflight('readdir\0'+abs+'\0'+inGlobStar, cb) - if (!cb) - return + this._append(match.absolute, entryData); + } - //console.error('RD %j %j', +inGlobStar, abs) - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs, cb) + var globber = glob(options.cwd || '.', options); + globber.on('error', onGlobError.bind(this)); + globber.on('match', onGlobMatch.bind(this)); + globber.on('end', onGlobEnd.bind(this)); - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return cb() + return this; +}; - if (Array.isArray(c)) - return cb(null, c) +/** + * Finalizes the instance and prevents further appending to the archive + * structure (queue will continue til drained). + * + * The `end`, `close` or `finish` events on the destination stream may fire + * right after calling this method so you should set listeners beforehand to + * properly detect stream completion. + * + * @return {Promise} + */ +Archiver.prototype.finalize = function() { + if (this._state.aborted) { + var abortedError = new ArchiverError('ABORTED'); + this.emit('error', abortedError); + return Promise.reject(abortedError); } - var self = this - self.fs.readdir(abs, readdirCb(this, abs, cb)) -} - -function readdirCb (self, abs, cb) { - return function (er, entries) { - if (er) - self._readdirError(abs, er, cb) - else - self._readdirEntries(abs, entries, cb) + if (this._state.finalize) { + var finalizingError = new ArchiverError('FINALIZING'); + this.emit('error', finalizingError); + return Promise.reject(finalizingError); } -} -Glob.prototype._readdirEntries = function (abs, entries, cb) { - if (this.aborted) - return + this._state.finalize = true; - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } + if (this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { + this._finalize(); } - this.cache[abs] = entries - return cb(null, entries) -} - -Glob.prototype._readdirError = function (f, er, cb) { - if (this.aborted) - return - - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - this.emit('error', error) - this.abort() - } - break + var self = this; - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break + return new Promise(function(resolve, reject) { + var errored; - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) { - this.emit('error', er) - // If the error is handled, then we abort - // if not, we threw out of here - this.abort() + self._module.on('end', function() { + if (!errored) { + resolve(); } - if (!this.silent) - console.error('glob error', er) - break - } - - return cb() -} + }) -Glob.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar, cb) { - var self = this - this._readdir(abs, inGlobStar, function (er, entries) { - self._processGlobStar2(prefix, read, abs, remain, index, inGlobStar, entries, cb) + self._module.on('error', function(err) { + errored = true; + reject(err); + }) }) -} - - -Glob.prototype._processGlobStar2 = function (prefix, read, abs, remain, index, inGlobStar, entries, cb) { - //console.error('pgs2', prefix, remain[0], entries) +}; - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return cb() +/** + * Sets the module format name used for archiving. + * + * @param {String} format The name of the format. + * @return {this} + */ +Archiver.prototype.setFormat = function(format) { + if (this._format) { + this.emit('error', new ArchiverError('FORMATSET')); + return this; + } - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) + this._format = format; - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false, cb) + return this; +}; - var isSym = this.symlinks[abs] - var len = entries.length +/** + * Sets the module used for archiving. + * + * @param {Function} module The function for archiver to interact with. + * @return {this} + */ +Archiver.prototype.setModule = function(module) { + if (this._state.aborted) { + this.emit('error', new ArchiverError('ABORTED')); + return this; + } - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return cb() + if (this._state.module) { + this.emit('error', new ArchiverError('MODULESET')); + return this; + } - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue + this._module = module; + this._modulePipe(); - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true, cb) + return this; +}; - var below = gspref.concat(entries[i], remain) - this._process(below, index, true, cb) +/** + * Appends a symlink to the instance. + * + * This does NOT interact with filesystem and is used for programmatically creating symlinks. + * + * @param {String} filepath The symlink path (within archive). + * @param {String} target The target path (within archive). + * @param {Number} mode Sets the entry permissions. + * @return {this} + */ +Archiver.prototype.symlink = function(filepath, target, mode) { + if (this._state.finalize || this._state.aborted) { + this.emit('error', new ArchiverError('QUEUECLOSED')); + return this; } - cb() -} - -Glob.prototype._processSimple = function (prefix, index, cb) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var self = this - this._stat(prefix, function (er, exists) { - self._processSimple2(prefix, index, er, exists, cb) - }) -} -Glob.prototype._processSimple2 = function (prefix, index, er, exists, cb) { + if (typeof filepath !== 'string' || filepath.length === 0) { + this.emit('error', new ArchiverError('SYMLINKFILEPATHREQUIRED')); + return this; + } - //console.error('ps2', prefix, exists) + if (typeof target !== 'string' || target.length === 0) { + this.emit('error', new ArchiverError('SYMLINKTARGETREQUIRED', { filepath: filepath })); + return this; + } - if (!this.matches[index]) - this.matches[index] = Object.create(null) + if (!this._moduleSupports('symlink')) { + this.emit('error', new ArchiverError('SYMLINKNOTSUPPORTED', { filepath: filepath })); + return this; + } - // If it doesn't exist, then just mark the lack of results - if (!exists) - return cb() + var data = {}; + data.type = 'symlink'; + data.name = filepath.replace(/\\/g, '/'); + data.linkname = target.replace(/\\/g, '/'); + data.sourceType = 'buffer'; - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' - } + if (typeof mode === "number") { + data.mode = mode; } - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') + this._entriesCount++; + this._queue.push({ + data: data, + source: Buffer.concat([]) + }); - // Mark this as a match - this._emitMatch(index, prefix) - cb() -} + return this; +}; -// Returns either 'DIR', 'FILE', or false -Glob.prototype._stat = function (f, cb) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' +/** + * Returns the current length (in bytes) that has been emitted. + * + * @return {Number} + */ +Archiver.prototype.pointer = function() { + return this._pointer; +}; - if (f.length > this.maxLength) - return cb() +/** + * Middleware-like helper that has yet to be fully implemented. + * + * @private + * @param {Function} plugin + * @return {this} + */ +Archiver.prototype.use = function(plugin) { + this._streams.push(plugin); + return this; +}; - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] +module.exports = Archiver; - if (Array.isArray(c)) - c = 'DIR' +/** + * @typedef {Object} CoreOptions + * @global + * @property {Number} [statConcurrency=4] Sets the number of workers used to + * process the internal fs stat queue. + */ - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return cb(null, c) +/** + * @typedef {Object} TransformOptions + * @property {Boolean} [allowHalfOpen=true] If set to false, then the stream + * will automatically end the readable side when the writable side ends and vice + * versa. + * @property {Boolean} [readableObjectMode=false] Sets objectMode for readable + * side of the stream. Has no effect if objectMode is true. + * @property {Boolean} [writableObjectMode=false] Sets objectMode for writable + * side of the stream. Has no effect if objectMode is true. + * @property {Boolean} [decodeStrings=true] Whether or not to decode strings + * into Buffers before passing them to _write(). `Writable` + * @property {String} [encoding=NULL] If specified, then buffers will be decoded + * to strings using the specified encoding. `Readable` + * @property {Number} [highWaterMark=16kb] The maximum number of bytes to store + * in the internal buffer before ceasing to read from the underlying resource. + * `Readable` `Writable` + * @property {Boolean} [objectMode=false] Whether this stream should behave as a + * stream of objects. Meaning that stream.read(n) returns a single value instead + * of a Buffer of size n. `Readable` `Writable` + */ - if (needDir && c === 'FILE') - return cb() +/** + * @typedef {Object} EntryData + * @property {String} name Sets the entry name including internal path. + * @property {(String|Date)} [date=NOW()] Sets the entry date. + * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions. + * @property {String} [prefix] Sets a path prefix for the entry name. Useful + * when working with methods like `directory` or `glob`. + * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing + * for reduction of fs stat calls when stat data is already known. + */ - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } +/** + * @typedef {Object} ErrorData + * @property {String} message The message of the error. + * @property {String} code The error code assigned to this error. + * @property {String} data Additional data provided for reporting or debugging (where available). + */ - var exists - var stat = this.statCache[abs] - if (stat !== undefined) { - if (stat === false) - return cb(null, stat) - else { - var type = stat.isDirectory() ? 'DIR' : 'FILE' - if (needDir && type === 'FILE') - return cb() - else - return cb(null, type, stat) - } - } +/** + * @typedef {Object} ProgressData + * @property {Object} entries + * @property {Number} entries.total Number of entries that have been appended. + * @property {Number} entries.processed Number of entries that have been processed. + * @property {Object} fs + * @property {Number} fs.totalBytes Number of bytes that have been appended. Calculated asynchronously and might not be accurate: it growth while entries are added. (based on fs.Stats) + * @property {Number} fs.processedBytes Number of bytes that have been processed. (based on fs.Stats) + */ - var self = this - var statcb = inflight('stat\0' + abs, lstatcb_) - if (statcb) - self.fs.lstat(abs, statcb) - - function lstatcb_ (er, lstat) { - if (lstat && lstat.isSymbolicLink()) { - // If it's a symlink, then treat it as the target, unless - // the target does not exist, then treat it as a file. - return self.fs.stat(abs, function (er, stat) { - if (er) - self._stat2(f, abs, null, lstat, cb) - else - self._stat2(f, abs, er, stat, cb) - }) - } else { - self._stat2(f, abs, er, lstat, cb) - } - } -} -Glob.prototype._stat2 = function (f, abs, er, stat, cb) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return cb() - } +/***/ }), - var needDir = f.slice(-1) === '/' - this.statCache[abs] = stat +/***/ 13143: +/***/ ((module, exports, __nccwpck_require__) => { - if (abs.slice(-1) === '/' && stat && !stat.isDirectory()) - return cb(null, false, stat) +/** + * Archiver Core + * + * @ignore + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' - this.cache[abs] = this.cache[abs] || c +var util = __nccwpck_require__(73837); - if (needDir && c === 'FILE') - return cb() +const ERROR_CODES = { + 'ABORTED': 'archive was aborted', + 'DIRECTORYDIRPATHREQUIRED': 'diretory dirpath argument must be a non-empty string value', + 'DIRECTORYFUNCTIONINVALIDDATA': 'invalid data returned by directory custom data function', + 'ENTRYNAMEREQUIRED': 'entry name must be a non-empty string value', + 'FILEFILEPATHREQUIRED': 'file filepath argument must be a non-empty string value', + 'FINALIZING': 'archive already finalizing', + 'QUEUECLOSED': 'queue closed', + 'NOENDMETHOD': 'no suitable finalize/end method defined by module', + 'DIRECTORYNOTSUPPORTED': 'support for directory entries not defined by module', + 'FORMATSET': 'archive format already set', + 'INPUTSTEAMBUFFERREQUIRED': 'input source must be valid Stream or Buffer instance', + 'MODULESET': 'module already set', + 'SYMLINKNOTSUPPORTED': 'support for symlink entries not defined by module', + 'SYMLINKFILEPATHREQUIRED': 'symlink filepath argument must be a non-empty string value', + 'SYMLINKTARGETREQUIRED': 'symlink target argument must be a non-empty string value', + 'ENTRYNOTSUPPORTED': 'entry not supported' +}; - return cb(null, c, stat) +function ArchiverError(code, data) { + Error.captureStackTrace(this, this.constructor); + //this.name = this.constructor.name; + this.message = ERROR_CODES[code] || code; + this.code = code; + this.data = data; } +util.inherits(ArchiverError, Error); + +exports = module.exports = ArchiverError; /***/ }), -/***/ 57388: +/***/ 99827: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = globSync -globSync.GlobSync = GlobSync +/** + * JSON Format Plugin + * + * @module plugins/json + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ +var inherits = (__nccwpck_require__(73837).inherits); +var Transform = (__nccwpck_require__(45193).Transform); -var rp = __nccwpck_require__(46863) -var minimatch = __nccwpck_require__(8487) -var Minimatch = minimatch.Minimatch -var Glob = (__nccwpck_require__(30095).Glob) -var util = __nccwpck_require__(73837) -var path = __nccwpck_require__(71017) -var assert = __nccwpck_require__(39491) -var isAbsolute = __nccwpck_require__(38714) -var common = __nccwpck_require__(84938) -var setopts = common.setopts -var ownProp = common.ownProp -var childrenIgnored = common.childrenIgnored -var isIgnored = common.isIgnored +var crc32 = __nccwpck_require__(54119); +var util = __nccwpck_require__(82072); -function globSync (pattern, options) { - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') +/** + * @constructor + * @param {(JsonOptions|TransformOptions)} options + */ +var Json = function(options) { + if (!(this instanceof Json)) { + return new Json(options); + } - return new GlobSync(pattern, options).found -} + options = this.options = util.defaults(options, {}); -function GlobSync (pattern, options) { - if (!pattern) - throw new Error('must provide pattern') + Transform.call(this, options); - if (typeof options === 'function' || arguments.length === 3) - throw new TypeError('callback provided to sync glob\n'+ - 'See: https://github.com/isaacs/node-glob/issues/167') + this.supports = { + directory: true, + symlink: true + }; - if (!(this instanceof GlobSync)) - return new GlobSync(pattern, options) + this.files = []; +}; - setopts(this, pattern, options) +inherits(Json, Transform); - if (this.noprocess) - return this +/** + * [_transform description] + * + * @private + * @param {Buffer} chunk + * @param {String} encoding + * @param {Function} callback + * @return void + */ +Json.prototype._transform = function(chunk, encoding, callback) { + callback(null, chunk); +}; - var n = this.minimatch.set.length - this.matches = new Array(n) - for (var i = 0; i < n; i ++) { - this._process(this.minimatch.set[i], i, false) - } - this._finish() -} +/** + * [_writeStringified description] + * + * @private + * @return void + */ +Json.prototype._writeStringified = function() { + var fileString = JSON.stringify(this.files); + this.write(fileString); +}; -GlobSync.prototype._finish = function () { - assert.ok(this instanceof GlobSync) - if (this.realpath) { - var self = this - this.matches.forEach(function (matchset, index) { - var set = self.matches[index] = Object.create(null) - for (var p in matchset) { - try { - p = self._makeAbs(p) - var real = rp.realpathSync(p, self.realpathCache) - set[real] = true - } catch (er) { - if (er.syscall === 'stat') - set[self._makeAbs(p)] = true - else - throw er - } - } - }) - } - common.finish(this) -} +/** + * [append description] + * + * @param {(Buffer|Stream)} source + * @param {EntryData} data + * @param {Function} callback + * @return void + */ +Json.prototype.append = function(source, data, callback) { + var self = this; + data.crc32 = 0; -GlobSync.prototype._process = function (pattern, index, inGlobStar) { - assert.ok(this instanceof GlobSync) + function onend(err, sourceBuffer) { + if (err) { + callback(err); + return; + } - // Get the first [n] parts of pattern that are all strings. - var n = 0 - while (typeof pattern[n] === 'string') { - n ++ - } - // now n is the index of the first one that is *not* a string. + data.size = sourceBuffer.length || 0; + data.crc32 = crc32.unsigned(sourceBuffer); - // See if there's anything else - var prefix - switch (n) { - // if not, then this is rather simple - case pattern.length: - this._processSimple(pattern.join('/'), index) - return + self.files.push(data); - case 0: - // pattern *starts* with some non-trivial item. - // going to readdir(cwd), but not include the prefix in matches. - prefix = null - break + callback(null, data); + } - default: - // pattern has some string bits in the front. - // whatever it starts with, whether that's 'absolute' like /foo/bar, - // or 'relative' like '../baz' - prefix = pattern.slice(0, n).join('/') - break + if (data.sourceType === 'buffer') { + onend(null, source); + } else if (data.sourceType === 'stream') { + util.collectStream(source, onend); } +}; - var remain = pattern.slice(n) +/** + * [finalize description] + * + * @return void + */ +Json.prototype.finalize = function() { + this._writeStringified(); + this.end(); +}; - // get the list of entries. - var read - if (prefix === null) - read = '.' - else if (isAbsolute(prefix) || - isAbsolute(pattern.map(function (p) { - return typeof p === 'string' ? p : '[*]' - }).join('/'))) { - if (!prefix || !isAbsolute(prefix)) - prefix = '/' + prefix - read = prefix - } else - read = prefix +module.exports = Json; - var abs = this._makeAbs(read) +/** + * @typedef {Object} JsonOptions + * @global + */ - //if ignored, skip processing - if (childrenIgnored(this, read)) - return - var isGlobStar = remain[0] === minimatch.GLOBSTAR - if (isGlobStar) - this._processGlobStar(prefix, read, abs, remain, index, inGlobStar) - else - this._processReaddir(prefix, read, abs, remain, index, inGlobStar) -} +/***/ }), +/***/ 33614: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -GlobSync.prototype._processReaddir = function (prefix, read, abs, remain, index, inGlobStar) { - var entries = this._readdir(abs, inGlobStar) +/** + * TAR Format Plugin + * + * @module plugins/tar + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ +var zlib = __nccwpck_require__(59796); - // if the abs isn't a dir, then nothing can match! - if (!entries) - return +var engine = __nccwpck_require__(2283); +var util = __nccwpck_require__(82072); - // It will only match dot entries if it starts with a dot, or if - // dot is set. Stuff like @(.foo|.bar) isn't allowed. - var pn = remain[0] - var negate = !!this.minimatch.negate - var rawGlob = pn._glob - var dotOk = this.dot || rawGlob.charAt(0) === '.' - - var matchedEntries = [] - for (var i = 0; i < entries.length; i++) { - var e = entries[i] - if (e.charAt(0) !== '.' || dotOk) { - var m - if (negate && !prefix) { - m = !e.match(pn) - } else { - m = e.match(pn) - } - if (m) - matchedEntries.push(e) - } +/** + * @constructor + * @param {TarOptions} options + */ +var Tar = function(options) { + if (!(this instanceof Tar)) { + return new Tar(options); } - var len = matchedEntries.length - // If there are no matched entries, then nothing matches. - if (len === 0) - return - - // if this is the last remaining pattern bit, then no need for - // an additional stat *unless* the user has specified mark or - // stat explicitly. We know they exist, since readdir returned - // them. + options = this.options = util.defaults(options, { + gzip: false + }); - if (remain.length === 1 && !this.mark && !this.stat) { - if (!this.matches[index]) - this.matches[index] = Object.create(null) + if (typeof options.gzipOptions !== 'object') { + options.gzipOptions = {}; + } - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - if (prefix) { - if (prefix.slice(-1) !== '/') - e = prefix + '/' + e - else - e = prefix + e - } + this.supports = { + directory: true, + symlink: true + }; - if (e.charAt(0) === '/' && !this.nomount) { - e = path.join(this.root, e) - } - this._emitMatch(index, e) - } - // This was the last one, and no stats were needed - return - } + this.engine = engine.pack(options); + this.compressor = false; - // now test all matched entries as stand-ins for that part - // of the pattern. - remain.shift() - for (var i = 0; i < len; i ++) { - var e = matchedEntries[i] - var newPattern - if (prefix) - newPattern = [prefix, e] - else - newPattern = [e] - this._process(newPattern.concat(remain), index, inGlobStar) + if (options.gzip) { + this.compressor = zlib.createGzip(options.gzipOptions); + this.compressor.on('error', this._onCompressorError.bind(this)); } -} +}; +/** + * [_onCompressorError description] + * + * @private + * @param {Error} err + * @return void + */ +Tar.prototype._onCompressorError = function(err) { + this.engine.emit('error', err); +}; -GlobSync.prototype._emitMatch = function (index, e) { - if (isIgnored(this, e)) - return +/** + * [append description] + * + * @param {(Buffer|Stream)} source + * @param {TarEntryData} data + * @param {Function} callback + * @return void + */ +Tar.prototype.append = function(source, data, callback) { + var self = this; - var abs = this._makeAbs(e) + data.mtime = data.date; - if (this.mark) - e = this._mark(e) + function append(err, sourceBuffer) { + if (err) { + callback(err); + return; + } - if (this.absolute) { - e = abs + self.engine.entry(data, sourceBuffer, function(err) { + callback(err, data); + }); } - if (this.matches[index][e]) - return + if (data.sourceType === 'buffer') { + append(null, source); + } else if (data.sourceType === 'stream' && data.stats) { + data.size = data.stats.size; - if (this.nodir) { - var c = this.cache[abs] - if (c === 'DIR' || Array.isArray(c)) - return - } + var entry = self.engine.entry(data, function(err) { + callback(err, data); + }); - this.matches[index][e] = true + source.pipe(entry); + } else if (data.sourceType === 'stream') { + util.collectStream(source, append); + } +}; - if (this.stat) - this._stat(e) -} +/** + * [finalize description] + * + * @return void + */ +Tar.prototype.finalize = function() { + this.engine.finalize(); +}; +/** + * [on description] + * + * @return this.engine + */ +Tar.prototype.on = function() { + return this.engine.on.apply(this.engine, arguments); +}; -GlobSync.prototype._readdirInGlobStar = function (abs) { - // follow all symlinked directories forever - // just proceed as if this is a non-globstar situation - if (this.follow) - return this._readdir(abs, false) +/** + * [pipe description] + * + * @param {String} destination + * @param {Object} options + * @return this.engine + */ +Tar.prototype.pipe = function(destination, options) { + if (this.compressor) { + return this.engine.pipe.apply(this.engine, [this.compressor]).pipe(destination, options); + } else { + return this.engine.pipe.apply(this.engine, arguments); + } +}; - var entries - var lstat - var stat - try { - lstat = this.fs.lstatSync(abs) - } catch (er) { - if (er.code === 'ENOENT') { - // lstat failed, doesn't exist - return null - } +/** + * [unpipe description] + * + * @return this.engine + */ +Tar.prototype.unpipe = function() { + if (this.compressor) { + return this.compressor.unpipe.apply(this.compressor, arguments); + } else { + return this.engine.unpipe.apply(this.engine, arguments); } +}; - var isSym = lstat && lstat.isSymbolicLink() - this.symlinks[abs] = isSym +module.exports = Tar; - // If it's not a symlink or a dir, then it's definitely a regular file. - // don't bother doing a readdir in that case. - if (!isSym && lstat && !lstat.isDirectory()) - this.cache[abs] = 'FILE' - else - entries = this._readdir(abs, false) +/** + * @typedef {Object} TarOptions + * @global + * @property {Boolean} [gzip=false] Compress the tar archive using gzip. + * @property {Object} [gzipOptions] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} + * to control compression. + * @property {*} [*] See [tar-stream]{@link https://github.com/mafintosh/tar-stream} documentation for additional properties. + */ - return entries -} +/** + * @typedef {Object} TarEntryData + * @global + * @property {String} name Sets the entry name including internal path. + * @property {(String|Date)} [date=NOW()] Sets the entry date. + * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions. + * @property {String} [prefix] Sets a path prefix for the entry name. Useful + * when working with methods like `directory` or `glob`. + * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing + * for reduction of fs stat calls when stat data is already known. + */ -GlobSync.prototype._readdir = function (abs, inGlobStar) { - var entries +/** + * TarStream Module + * @external TarStream + * @see {@link https://github.com/mafintosh/tar-stream} + */ - if (inGlobStar && !ownProp(this.symlinks, abs)) - return this._readdirInGlobStar(abs) - if (ownProp(this.cache, abs)) { - var c = this.cache[abs] - if (!c || c === 'FILE') - return null +/***/ }), - if (Array.isArray(c)) - return c - } +/***/ 8987: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - try { - return this._readdirEntries(abs, this.fs.readdirSync(abs)) - } catch (er) { - this._readdirError(abs, er) - return null - } -} +/** + * ZIP Format Plugin + * + * @module plugins/zip + * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} + * @copyright (c) 2012-2014 Chris Talkington, contributors. + */ +var engine = __nccwpck_require__(86454); +var util = __nccwpck_require__(82072); -GlobSync.prototype._readdirEntries = function (abs, entries) { - // if we haven't asked to stat everything, then just - // assume that everything in there exists, so we can avoid - // having to stat it a second time. - if (!this.mark && !this.stat) { - for (var i = 0; i < entries.length; i ++) { - var e = entries[i] - if (abs === '/') - e = abs + e - else - e = abs + '/' + e - this.cache[e] = true - } +/** + * @constructor + * @param {ZipOptions} [options] + * @param {String} [options.comment] Sets the zip archive comment. + * @param {Boolean} [options.forceLocalTime=false] Forces the archive to contain local file times instead of UTC. + * @param {Boolean} [options.forceZip64=false] Forces the archive to contain ZIP64 headers. + * @param {Boolean} [options.namePrependSlash=false] Prepends a forward slash to archive file paths. + * @param {Boolean} [options.store=false] Sets the compression method to STORE. + * @param {Object} [options.zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} + */ +var Zip = function(options) { + if (!(this instanceof Zip)) { + return new Zip(options); } - this.cache[abs] = entries - - // mark and cache dir-ness - return entries -} - -GlobSync.prototype._readdirError = function (f, er) { - // handle errors, and cache the information - switch (er.code) { - case 'ENOTSUP': // https://github.com/isaacs/node-glob/issues/205 - case 'ENOTDIR': // totally normal. means it *does* exist. - var abs = this._makeAbs(f) - this.cache[abs] = 'FILE' - if (abs === this.cwdAbs) { - var error = new Error(er.code + ' invalid cwd ' + this.cwd) - error.path = this.cwd - error.code = er.code - throw error - } - break + options = this.options = util.defaults(options, { + comment: '', + forceUTC: false, + namePrependSlash: false, + store: false + }); - case 'ENOENT': // not terribly unusual - case 'ELOOP': - case 'ENAMETOOLONG': - case 'UNKNOWN': - this.cache[this._makeAbs(f)] = false - break + this.supports = { + directory: true, + symlink: true + }; - default: // some unusual error. Treat as failure. - this.cache[this._makeAbs(f)] = false - if (this.strict) - throw er - if (!this.silent) - console.error('glob error', er) - break - } -} + this.engine = new engine(options); +}; -GlobSync.prototype._processGlobStar = function (prefix, read, abs, remain, index, inGlobStar) { +/** + * @param {(Buffer|Stream)} source + * @param {ZipEntryData} data + * @param {String} data.name Sets the entry name including internal path. + * @param {(String|Date)} [data.date=NOW()] Sets the entry date. + * @param {Number} [data.mode=D:0755/F:0644] Sets the entry permissions. + * @param {String} [data.prefix] Sets a path prefix for the entry name. Useful + * when working with methods like `directory` or `glob`. + * @param {fs.Stats} [data.stats] Sets the fs stat data for this entry allowing + * for reduction of fs stat calls when stat data is already known. + * @param {Boolean} [data.store=ZipOptions.store] Sets the compression method to STORE. + * @param {Function} callback + * @return void + */ +Zip.prototype.append = function(source, data, callback) { + this.engine.entry(source, data, callback); +}; - var entries = this._readdir(abs, inGlobStar) +/** + * @return void + */ +Zip.prototype.finalize = function() { + this.engine.finalize(); +}; - // no entries means not a dir, so it can never have matches - // foo.txt/** doesn't match foo.txt - if (!entries) - return +/** + * @return this.engine + */ +Zip.prototype.on = function() { + return this.engine.on.apply(this.engine, arguments); +}; - // test without the globstar, and with every child both below - // and replacing the globstar. - var remainWithoutGlobStar = remain.slice(1) - var gspref = prefix ? [ prefix ] : [] - var noGlobStar = gspref.concat(remainWithoutGlobStar) +/** + * @return this.engine + */ +Zip.prototype.pipe = function() { + return this.engine.pipe.apply(this.engine, arguments); +}; - // the noGlobStar pattern exits the inGlobStar state - this._process(noGlobStar, index, false) +/** + * @return this.engine + */ +Zip.prototype.unpipe = function() { + return this.engine.unpipe.apply(this.engine, arguments); +}; - var len = entries.length - var isSym = this.symlinks[abs] +module.exports = Zip; - // If it's a symlink, and we're in a globstar, then stop - if (isSym && inGlobStar) - return +/** + * @typedef {Object} ZipOptions + * @global + * @property {String} [comment] Sets the zip archive comment. + * @property {Boolean} [forceLocalTime=false] Forces the archive to contain local file times instead of UTC. + * @property {Boolean} [forceZip64=false] Forces the archive to contain ZIP64 headers. + * @prpperty {Boolean} [namePrependSlash=false] Prepends a forward slash to archive file paths. + * @property {Boolean} [store=false] Sets the compression method to STORE. + * @property {Object} [zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} + * to control compression. + * @property {*} [*] See [zip-stream]{@link https://archiverjs.com/zip-stream/ZipStream.html} documentation for current list of properties. + */ - for (var i = 0; i < len; i++) { - var e = entries[i] - if (e.charAt(0) === '.' && !this.dot) - continue +/** + * @typedef {Object} ZipEntryData + * @global + * @property {String} name Sets the entry name including internal path. + * @property {(String|Date)} [date=NOW()] Sets the entry date. + * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions. + * @property {Boolean} [namePrependSlash=ZipOptions.namePrependSlash] Prepends a forward slash to archive file paths. + * @property {String} [prefix] Sets a path prefix for the entry name. Useful + * when working with methods like `directory` or `glob`. + * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing + * for reduction of fs stat calls when stat data is already known. + * @property {Boolean} [store=ZipOptions.store] Sets the compression method to STORE. + */ - // these two cases enter the inGlobStar state - var instead = gspref.concat(entries[i], remainWithoutGlobStar) - this._process(instead, index, true) +/** + * ZipStream Module + * @external ZipStream + * @see {@link https://www.archiverjs.com/zip-stream/ZipStream.html} + */ - var below = gspref.concat(entries[i], remain) - this._process(below, index, true) - } -} -GlobSync.prototype._processSimple = function (prefix, index) { - // XXX review this. Shouldn't it be doing the mounting etc - // before doing stat? kinda weird? - var exists = this._stat(prefix) +/***/ }), - if (!this.matches[index]) - this.matches[index] = Object.create(null) +/***/ 57888: +/***/ (function(__unused_webpack_module, exports) { - // If it doesn't exist, then just mark the lack of results - if (!exists) - return +(function (global, factory) { + true ? factory(exports) : + 0; +})(this, (function (exports) { 'use strict'; - if (prefix && isAbsolute(prefix) && !this.nomount) { - var trail = /[\/\\]$/.test(prefix) - if (prefix.charAt(0) === '/') { - prefix = path.join(this.root, prefix) - } else { - prefix = path.resolve(this.root, prefix) - if (trail) - prefix += '/' + /** + * Creates a continuation function with some arguments already applied. + * + * Useful as a shorthand when combined with other control flow functions. Any + * arguments passed to the returned function are added to the arguments + * originally passed to apply. + * + * @name apply + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {Function} fn - The function you want to eventually apply all + * arguments to. Invokes with (arguments...). + * @param {...*} arguments... - Any number of arguments to automatically apply + * when the continuation is called. + * @returns {Function} the partially-applied function + * @example + * + * // using apply + * async.parallel([ + * async.apply(fs.writeFile, 'testfile1', 'test1'), + * async.apply(fs.writeFile, 'testfile2', 'test2') + * ]); + * + * + * // the same process without using apply + * async.parallel([ + * function(callback) { + * fs.writeFile('testfile1', 'test1', callback); + * }, + * function(callback) { + * fs.writeFile('testfile2', 'test2', callback); + * } + * ]); + * + * // It's possible to pass any number of additional arguments when calling the + * // continuation: + * + * node> var fn = async.apply(sys.puts, 'one'); + * node> fn('two', 'three'); + * one + * two + * three + */ + function apply(fn, ...args) { + return (...callArgs) => fn(...args,...callArgs); } - } - if (process.platform === 'win32') - prefix = prefix.replace(/\\/g, '/') + function initialParams (fn) { + return function (...args/*, callback*/) { + var callback = args.pop(); + return fn.call(this, args, callback); + }; + } - // Mark this as a match - this._emitMatch(index, prefix) -} + /* istanbul ignore file */ -// Returns either 'DIR', 'FILE', or false -GlobSync.prototype._stat = function (f) { - var abs = this._makeAbs(f) - var needDir = f.slice(-1) === '/' + var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask; + var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; + var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; - if (f.length > this.maxLength) - return false + function fallback(fn) { + setTimeout(fn, 0); + } - if (!this.stat && ownProp(this.cache, abs)) { - var c = this.cache[abs] + function wrap(defer) { + return (fn, ...args) => defer(() => fn(...args)); + } - if (Array.isArray(c)) - c = 'DIR' + var _defer$1; - // It exists, but maybe not how we need it - if (!needDir || c === 'DIR') - return c + if (hasQueueMicrotask) { + _defer$1 = queueMicrotask; + } else if (hasSetImmediate) { + _defer$1 = setImmediate; + } else if (hasNextTick) { + _defer$1 = process.nextTick; + } else { + _defer$1 = fallback; + } - if (needDir && c === 'FILE') - return false + var setImmediate$1 = wrap(_defer$1); - // otherwise we have to stat, because maybe c=true - // if we know it exists, but not what it is. - } + /** + * Take a sync function and make it async, passing its return value to a + * callback. This is useful for plugging sync functions into a waterfall, + * series, or other async functions. Any arguments passed to the generated + * function will be passed to the wrapped function (except for the final + * callback argument). Errors thrown will be passed to the callback. + * + * If the function passed to `asyncify` returns a Promise, that promises's + * resolved/rejected state will be used to call the callback, rather than simply + * the synchronous return value. + * + * This also means you can asyncify ES2017 `async` functions. + * + * @name asyncify + * @static + * @memberOf module:Utils + * @method + * @alias wrapSync + * @category Util + * @param {Function} func - The synchronous function, or Promise-returning + * function to convert to an {@link AsyncFunction}. + * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be + * invoked with `(args..., callback)`. + * @example + * + * // passing a regular synchronous function + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(JSON.parse), + * function (data, next) { + * // data is the result of parsing the text. + * // If there was a parsing error, it would have been caught. + * } + * ], callback); + * + * // passing a function returning a promise + * async.waterfall([ + * async.apply(fs.readFile, filename, "utf8"), + * async.asyncify(function (contents) { + * return db.model.create(contents); + * }), + * function (model, next) { + * // `model` is the instantiated model object. + * // If there was an error, this function would be skipped. + * } + * ], callback); + * + * // es2017 example, though `asyncify` is not needed if your JS environment + * // supports async functions out of the box + * var q = async.queue(async.asyncify(async function(file) { + * var intermediateStep = await processFile(file); + * return await somePromise(intermediateStep) + * })); + * + * q.push(files); + */ + function asyncify(func) { + if (isAsync(func)) { + return function (...args/*, callback*/) { + const callback = args.pop(); + const promise = func.apply(this, args); + return handlePromise(promise, callback) + } + } - var exists - var stat = this.statCache[abs] - if (!stat) { - var lstat - try { - lstat = this.fs.lstatSync(abs) - } catch (er) { - if (er && (er.code === 'ENOENT' || er.code === 'ENOTDIR')) { - this.statCache[abs] = false - return false - } + return initialParams(function (args, callback) { + var result; + try { + result = func.apply(this, args); + } catch (e) { + return callback(e); + } + // if result is Promise object + if (result && typeof result.then === 'function') { + return handlePromise(result, callback) + } else { + callback(null, result); + } + }); } - if (lstat && lstat.isSymbolicLink()) { - try { - stat = this.fs.statSync(abs) - } catch (er) { - stat = lstat - } - } else { - stat = lstat + function handlePromise(promise, callback) { + return promise.then(value => { + invokeCallback(callback, null, value); + }, err => { + invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); + }); } - } - this.statCache[abs] = stat + function invokeCallback(callback, error, value) { + try { + callback(error, value); + } catch (err) { + setImmediate$1(e => { throw e }, err); + } + } - var c = true - if (stat) - c = stat.isDirectory() ? 'DIR' : 'FILE' + function isAsync(fn) { + return fn[Symbol.toStringTag] === 'AsyncFunction'; + } - this.cache[abs] = this.cache[abs] || c + function isAsyncGenerator(fn) { + return fn[Symbol.toStringTag] === 'AsyncGenerator'; + } - if (needDir && c === 'FILE') - return false + function isAsyncIterable(obj) { + return typeof obj[Symbol.asyncIterator] === 'function'; + } - return c -} + function wrapAsync(asyncFn) { + if (typeof asyncFn !== 'function') throw new Error('expected a function') + return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; + } -GlobSync.prototype._mark = function (p) { - return common.mark(this, p) -} + // conditionally promisify a function. + // only return a promise if a callback is omitted + function awaitify (asyncFn, arity) { + if (!arity) arity = asyncFn.length; + if (!arity) throw new Error('arity is undefined') + function awaitable (...args) { + if (typeof args[arity - 1] === 'function') { + return asyncFn.apply(this, args) + } -GlobSync.prototype._makeAbs = function (f) { - return common.makeAbs(this, f) -} + return new Promise((resolve, reject) => { + args[arity - 1] = (err, ...cbArgs) => { + if (err) return reject(err) + resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); + }; + asyncFn.apply(this, args); + }) + } + return awaitable + } -/***/ }), + function applyEach$1 (eachfn) { + return function applyEach(fns, ...callArgs) { + const go = awaitify(function (callback) { + var that = this; + return eachfn(fns, (fn, cb) => { + wrapAsync(fn).apply(that, callArgs.concat(cb)); + }, callback); + }); + return go; + }; + } -/***/ 8487: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = minimatch -minimatch.Minimatch = Minimatch - -var path = (function () { try { return __nccwpck_require__(71017) } catch (e) {}}()) || { - sep: '/' -} -minimatch.sep = path.sep - -var GLOBSTAR = minimatch.GLOBSTAR = Minimatch.GLOBSTAR = {} -var expand = __nccwpck_require__(58311) - -var plTypes = { - '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, - '?': { open: '(?:', close: ')?' }, - '+': { open: '(?:', close: ')+' }, - '*': { open: '(?:', close: ')*' }, - '@': { open: '(?:', close: ')' } -} - -// any single thing other than / -// don't need to escape / when using new RegExp() -var qmark = '[^/]' - -// * => any number of characters -var star = qmark + '*?' - -// ** when dots are allowed. Anything goes, except .. and . -// not (^ or / followed by one or two dots followed by $ or /), -// followed by anything, any number of times. -var twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' - -// not a ^ or / followed by a dot, -// followed by anything, any number of times. -var twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' - -// characters that need to be escaped in RegExp. -var reSpecials = charSet('().*{}+?[]^$\\!') - -// "abc" -> { a:true, b:true, c:true } -function charSet (s) { - return s.split('').reduce(function (set, c) { - set[c] = true - return set - }, {}) -} + function _asyncMap(eachfn, arr, iteratee, callback) { + arr = arr || []; + var results = []; + var counter = 0; + var _iteratee = wrapAsync(iteratee); -// normalizes slashes. -var slashSplit = /\/+/ + return eachfn(arr, (value, _, iterCb) => { + var index = counter++; + _iteratee(value, (err, v) => { + results[index] = v; + iterCb(err); + }); + }, err => { + callback(err, results); + }); + } -minimatch.filter = filter -function filter (pattern, options) { - options = options || {} - return function (p, i, list) { - return minimatch(p, pattern, options) - } -} + function isArrayLike(value) { + return value && + typeof value.length === 'number' && + value.length >= 0 && + value.length % 1 === 0; + } -function ext (a, b) { - b = b || {} - var t = {} - Object.keys(a).forEach(function (k) { - t[k] = a[k] - }) - Object.keys(b).forEach(function (k) { - t[k] = b[k] - }) - return t -} + // A temporary value used to identify if the loop should be broken. + // See #1064, #1293 + const breakLoop = {}; + var breakLoop$1 = breakLoop; -minimatch.defaults = function (def) { - if (!def || typeof def !== 'object' || !Object.keys(def).length) { - return minimatch - } + function once(fn) { + function wrapper (...args) { + if (fn === null) return; + var callFn = fn; + fn = null; + callFn.apply(this, args); + } + Object.assign(wrapper, fn); + return wrapper + } - var orig = minimatch + function getIterator (coll) { + return coll[Symbol.iterator] && coll[Symbol.iterator](); + } - var m = function minimatch (p, pattern, options) { - return orig(p, pattern, ext(def, options)) - } + function createArrayIterator(coll) { + var i = -1; + var len = coll.length; + return function next() { + return ++i < len ? {value: coll[i], key: i} : null; + } + } - m.Minimatch = function Minimatch (pattern, options) { - return new orig.Minimatch(pattern, ext(def, options)) - } - m.Minimatch.defaults = function defaults (options) { - return orig.defaults(ext(def, options)).Minimatch - } + function createES2015Iterator(iterator) { + var i = -1; + return function next() { + var item = iterator.next(); + if (item.done) + return null; + i++; + return {value: item.value, key: i}; + } + } - m.filter = function filter (pattern, options) { - return orig.filter(pattern, ext(def, options)) - } + function createObjectIterator(obj) { + var okeys = obj ? Object.keys(obj) : []; + var i = -1; + var len = okeys.length; + return function next() { + var key = okeys[++i]; + if (key === '__proto__') { + return next(); + } + return i < len ? {value: obj[key], key} : null; + }; + } - m.defaults = function defaults (options) { - return orig.defaults(ext(def, options)) - } + function createIterator(coll) { + if (isArrayLike(coll)) { + return createArrayIterator(coll); + } - m.makeRe = function makeRe (pattern, options) { - return orig.makeRe(pattern, ext(def, options)) - } + var iterator = getIterator(coll); + return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); + } - m.braceExpand = function braceExpand (pattern, options) { - return orig.braceExpand(pattern, ext(def, options)) - } + function onlyOnce(fn) { + return function (...args) { + if (fn === null) throw new Error("Callback was already called."); + var callFn = fn; + fn = null; + callFn.apply(this, args); + }; + } - m.match = function (list, pattern, options) { - return orig.match(list, pattern, ext(def, options)) - } + // for async generators + function asyncEachOfLimit(generator, limit, iteratee, callback) { + let done = false; + let canceled = false; + let awaiting = false; + let running = 0; + let idx = 0; - return m -} + function replenish() { + //console.log('replenish') + if (running >= limit || awaiting || done) return + //console.log('replenish awaiting') + awaiting = true; + generator.next().then(({value, done: iterDone}) => { + //console.log('got value', value) + if (canceled || done) return + awaiting = false; + if (iterDone) { + done = true; + if (running <= 0) { + //console.log('done nextCb') + callback(null); + } + return; + } + running++; + iteratee(value, idx, iterateeCallback); + idx++; + replenish(); + }).catch(handleError); + } -Minimatch.defaults = function (def) { - return minimatch.defaults(def).Minimatch -} + function iterateeCallback(err, result) { + //console.log('iterateeCallback') + running -= 1; + if (canceled) return + if (err) return handleError(err) -function minimatch (p, pattern, options) { - assertValidPattern(pattern) + if (err === false) { + done = true; + canceled = true; + return + } - if (!options) options = {} + if (result === breakLoop$1 || (done && running <= 0)) { + done = true; + //console.log('done iterCb') + return callback(null); + } + replenish(); + } - // shortcut: comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - return false - } + function handleError(err) { + if (canceled) return + awaiting = false; + done = true; + callback(err); + } - return new Minimatch(pattern, options).match(p) -} + replenish(); + } -function Minimatch (pattern, options) { - if (!(this instanceof Minimatch)) { - return new Minimatch(pattern, options) - } + var eachOfLimit$2 = (limit) => { + return (obj, iteratee, callback) => { + callback = once(callback); + if (limit <= 0) { + throw new RangeError('concurrency limit cannot be less than 1') + } + if (!obj) { + return callback(null); + } + if (isAsyncGenerator(obj)) { + return asyncEachOfLimit(obj, limit, iteratee, callback) + } + if (isAsyncIterable(obj)) { + return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) + } + var nextElem = createIterator(obj); + var done = false; + var canceled = false; + var running = 0; + var looping = false; - assertValidPattern(pattern) + function iterateeCallback(err, value) { + if (canceled) return + running -= 1; + if (err) { + done = true; + callback(err); + } + else if (err === false) { + done = true; + canceled = true; + } + else if (value === breakLoop$1 || (done && running <= 0)) { + done = true; + return callback(null); + } + else if (!looping) { + replenish(); + } + } - if (!options) options = {} + function replenish () { + looping = true; + while (running < limit && !done) { + var elem = nextElem(); + if (elem === null) { + done = true; + if (running <= 0) { + callback(null); + } + return; + } + running += 1; + iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); + } + looping = false; + } - pattern = pattern.trim() + replenish(); + }; + }; - // windows support: need to use /, not \ - if (!options.allowWindowsEscape && path.sep !== '/') { - pattern = pattern.split(path.sep).join('/') - } + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a + * time. + * + * @name eachOfLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. The `key` is the item's key, or index in the case of an + * array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback); + } - this.options = options - this.set = [] - this.pattern = pattern - this.regexp = null - this.negate = false - this.comment = false - this.empty = false - this.partial = !!options.partial + var eachOfLimit$1 = awaitify(eachOfLimit, 4); - // make the set of regexps etc. - this.make() -} + // eachOf implementation optimized for array-likes + function eachOfArrayLike(coll, iteratee, callback) { + callback = once(callback); + var index = 0, + completed = 0, + {length} = coll, + canceled = false; + if (length === 0) { + callback(null); + } -Minimatch.prototype.debug = function () {} + function iteratorCallback(err, value) { + if (err === false) { + canceled = true; + } + if (canceled === true) return + if (err) { + callback(err); + } else if ((++completed === length) || value === breakLoop$1) { + callback(null); + } + } -Minimatch.prototype.make = make -function make () { - var pattern = this.pattern - var options = this.options + for (; index < length; index++) { + iteratee(coll[index], index, onlyOnce(iteratorCallback)); + } + } - // empty patterns and comments match nothing. - if (!options.nocomment && pattern.charAt(0) === '#') { - this.comment = true - return - } - if (!pattern) { - this.empty = true - return - } + // a generic version of eachOf which can handle array, object, and iterator cases. + function eachOfGeneric (coll, iteratee, callback) { + return eachOfLimit$1(coll, Infinity, iteratee, callback); + } - // step 1: figure out negation, etc. - this.parseNegate() + /** + * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument + * to the iteratee. + * + * @name eachOf + * @static + * @memberOf module:Collections + * @method + * @alias forEachOf + * @category Collection + * @see [async.each]{@link module:Collections.each} + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each + * item in `coll`. + * The `key` is the item's key, or index in the case of an array. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dev.json is a file containing a valid json object config for dev environment + * // dev.json is a file containing a valid json object config for test environment + * // prod.json is a file containing a valid json object config for prod environment + * // invalid.json is a file with a malformed json object + * + * let configs = {}; //global variable + * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; + * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; + * + * // asynchronous function that reads a json file and parses the contents as json object + * function parseFile(file, key, callback) { + * fs.readFile(file, "utf8", function(err, data) { + * if (err) return calback(err); + * try { + * configs[key] = JSON.parse(data); + * } catch (e) { + * return callback(e); + * } + * callback(); + * }); + * } + * + * // Using callbacks + * async.forEachOf(validConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * } else { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { + * if (err) { + * console.error(err); + * // JSON parse error exception + * } else { + * console.log(configs); + * } + * }); + * + * // Using Promises + * async.forEachOf(validConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * }).catch( err => { + * console.error(err); + * }); + * + * //Error handing + * async.forEachOf(invalidConfigFileMap, parseFile) + * .then( () => { + * console.log(configs); + * }).catch( err => { + * console.error(err); + * // JSON parse error exception + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.forEachOf(validConfigFileMap, parseFile); + * console.log(configs); + * // configs is now a map of JSON data, e.g. + * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} + * } + * catch (err) { + * console.log(err); + * } + * } + * + * //Error handing + * async () => { + * try { + * let result = await async.forEachOf(invalidConfigFileMap, parseFile); + * console.log(configs); + * } + * catch (err) { + * console.log(err); + * // JSON parse error exception + * } + * } + * + */ + function eachOf(coll, iteratee, callback) { + var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; + return eachOfImplementation(coll, wrapAsync(iteratee), callback); + } - // step 2: expand braces - var set = this.globSet = this.braceExpand() + var eachOf$1 = awaitify(eachOf, 3); - if (options.debug) this.debug = function debug() { console.error.apply(console, arguments) } - - this.debug(this.pattern, set) + /** + * Produces a new collection of values by mapping each value in `coll` through + * the `iteratee` function. The `iteratee` is called with an item from `coll` + * and a callback for when it has finished processing. Each of these callbacks + * takes 2 arguments: an `error`, and the transformed item from `coll`. If + * `iteratee` passes an error to its callback, the main `callback` (for the + * `map` function) is immediately called with the error. + * + * Note, that since this function applies the `iteratee` to each item in + * parallel, there is no guarantee that the `iteratee` functions will complete + * in order. However, the results array will be in the same order as the + * original `coll`. + * + * If `map` is passed an Object, the results will be an Array. The results + * will roughly be in the order of the original Objects' keys (but this can + * vary across JavaScript engines). + * + * @name map + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an Array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.map(fileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.map(fileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.map(withMissingFileList, getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.map(fileList, getFileSizeInBytes); + * console.log(results); + * // results is now an array of the file size in bytes for each file, e.g. + * // [ 1000, 2000, 3000] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.map(withMissingFileList, getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function map (coll, iteratee, callback) { + return _asyncMap(eachOf$1, coll, iteratee, callback) + } + var map$1 = awaitify(map, 3); - // step 3: now we have a set, so turn each one into a series of path-portion - // matching patterns. - // These will be regexps, except in the case of "**", which is - // set to the GLOBSTAR object for globstar behavior, - // and will not contain any / characters - set = this.globParts = set.map(function (s) { - return s.split(slashSplit) - }) + /** + * Applies the provided arguments to each function in the array, calling + * `callback` after all functions have completed. If you only provide the first + * argument, `fns`, then it will return a function which lets you pass in the + * arguments as if it were a single function call. If more arguments are + * provided, `callback` is required while `args` is still optional. The results + * for each of the applied async functions are passed to the final callback + * as an array. + * + * @name applyEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s + * to all call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - Returns a function that takes no args other than + * an optional callback, that is the result of applying the `args` to each + * of the functions. + * @example + * + * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') + * + * appliedFn((err, results) => { + * // results[0] is the results for `enableSearch` + * // results[1] is the results for `updateSchema` + * }); + * + * // partial application example: + * async.each( + * buckets, + * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), + * callback + * ); + */ + var applyEach = applyEach$1(map$1); - this.debug(this.pattern, set) + /** + * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. + * + * @name eachOfSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.eachOf]{@link module:Collections.eachOf} + * @alias forEachOfSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * Invoked with (item, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachOfSeries(coll, iteratee, callback) { + return eachOfLimit$1(coll, 1, iteratee, callback) + } + var eachOfSeries$1 = awaitify(eachOfSeries, 3); - // glob --> regexps - set = set.map(function (s, si, set) { - return s.map(this.parse, this) - }, this) + /** + * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. + * + * @name mapSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapSeries (coll, iteratee, callback) { + return _asyncMap(eachOfSeries$1, coll, iteratee, callback) + } + var mapSeries$1 = awaitify(mapSeries, 3); - this.debug(this.pattern, set) + /** + * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. + * + * @name applyEachSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.applyEach]{@link module:ControlFlow.applyEach} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all + * call with the same arguments + * @param {...*} [args] - any number of separate arguments to pass to the + * function. + * @param {Function} [callback] - the final argument should be the callback, + * called when all functions have completed processing. + * @returns {AsyncFunction} - A function, that when called, is the result of + * appling the `args` to the list of functions. It takes no args, other than + * a callback. + */ + var applyEachSeries = applyEach$1(mapSeries$1); - // filter out everything that didn't compile properly. - set = set.filter(function (s) { - return s.indexOf(false) === -1 - }) + const PROMISE_SYMBOL = Symbol('promiseCallback'); - this.debug(this.pattern, set) + function promiseCallback () { + let resolve, reject; + function callback (err, ...args) { + if (err) return reject(err) + resolve(args.length > 1 ? args : args[0]); + } - this.set = set -} + callback[PROMISE_SYMBOL] = new Promise((res, rej) => { + resolve = res, + reject = rej; + }); -Minimatch.prototype.parseNegate = parseNegate -function parseNegate () { - var pattern = this.pattern - var negate = false - var options = this.options - var negateOffset = 0 + return callback + } - if (options.nonegate) return + /** + * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on + * their requirements. Each function can optionally depend on other functions + * being completed first, and each function is run as soon as its requirements + * are satisfied. + * + * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence + * will stop. Further tasks will not execute (so any other functions depending + * on it will not run), and the main `callback` is immediately called with the + * error. + * + * {@link AsyncFunction}s also receive an object containing the results of functions which + * have completed so far as the first argument, if they have dependencies. If a + * task function has no dependencies, it will only be passed a callback. + * + * @name auto + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Object} tasks - An object. Each of its properties is either a + * function or an array of requirements, with the {@link AsyncFunction} itself the last item + * in the array. The object's key of a property serves as the name of the task + * defined by that property, i.e. can be used when specifying requirements for + * other tasks. The function receives one or two arguments: + * * a `results` object, containing the results of the previously executed + * functions, only passed if the task has any dependencies, + * * a `callback(err, result)` function, which must be called when finished, + * passing an `error` (which can be `null`) and the result of the function's + * execution. + * @param {number} [concurrency=Infinity] - An optional `integer` for + * determining the maximum number of tasks that can be run in parallel. By + * default, as many as possible. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback. Results are always returned; however, if an + * error occurs, no further `tasks` will be performed, and the results object + * will only contain partial results. Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * @example + * + * //Using Callbacks + * async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }, function(err, results) { + * if (err) { + * console.log('err = ', err); + * } + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }); + * + * //Using Promises + * async.auto({ + * get_data: function(callback) { + * console.log('in get_data'); + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * console.log('in make_folder'); + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }).then(results => { + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * }).catch(err => { + * console.log('err = ', err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.auto({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: ['get_data', 'make_folder', function(results, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(results, callback) { + * // once the file is written let's email a link to it... + * callback(null, {'file':results.write_file, 'email':'user@example.com'}); + * }] + * }); + * console.log('results = ', results); + * // results = { + * // get_data: ['data', 'converted to array'] + * // make_folder; 'folder', + * // write_file: 'filename' + * // email_link: { file: 'filename', email: 'user@example.com' } + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function auto(tasks, concurrency, callback) { + if (typeof concurrency !== 'number') { + // concurrency is optional, shift the args. + callback = concurrency; + concurrency = null; + } + callback = once(callback || promiseCallback()); + var numTasks = Object.keys(tasks).length; + if (!numTasks) { + return callback(null); + } + if (!concurrency) { + concurrency = numTasks; + } - for (var i = 0, l = pattern.length - ; i < l && pattern.charAt(i) === '!' - ; i++) { - negate = !negate - negateOffset++ - } + var results = {}; + var runningTasks = 0; + var canceled = false; + var hasError = false; - if (negateOffset) this.pattern = pattern.substr(negateOffset) - this.negate = negate -} + var listeners = Object.create(null); -// Brace expansion: -// a{b,c}d -> abd acd -// a{b,}c -> abc ac -// a{0..3}d -> a0d a1d a2d a3d -// a{b,c{d,e}f}g -> abg acdfg acefg -// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg -// -// Invalid sets are not expanded. -// a{2..}b -> a{2..}b -// a{b}c -> a{b}c -minimatch.braceExpand = function (pattern, options) { - return braceExpand(pattern, options) -} + var readyTasks = []; -Minimatch.prototype.braceExpand = braceExpand + // for cycle detection: + var readyToCheck = []; // tasks that have been identified as reachable + // without the possibility of returning to an ancestor task + var uncheckedDependencies = {}; -function braceExpand (pattern, options) { - if (!options) { - if (this instanceof Minimatch) { - options = this.options - } else { - options = {} - } - } + Object.keys(tasks).forEach(key => { + var task = tasks[key]; + if (!Array.isArray(task)) { + // no dependencies + enqueueTask(key, [task]); + readyToCheck.push(key); + return; + } - pattern = typeof pattern === 'undefined' - ? this.pattern : pattern + var dependencies = task.slice(0, task.length - 1); + var remainingDependencies = dependencies.length; + if (remainingDependencies === 0) { + enqueueTask(key, task); + readyToCheck.push(key); + return; + } + uncheckedDependencies[key] = remainingDependencies; - assertValidPattern(pattern) + dependencies.forEach(dependencyName => { + if (!tasks[dependencyName]) { + throw new Error('async.auto task `' + key + + '` has a non-existent dependency `' + + dependencyName + '` in ' + + dependencies.join(', ')); + } + addListener(dependencyName, () => { + remainingDependencies--; + if (remainingDependencies === 0) { + enqueueTask(key, task); + } + }); + }); + }); - // Thanks to Yeting Li for - // improving this regexp to avoid a ReDOS vulnerability. - if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { - // shortcut. no need to expand. - return [pattern] - } + checkForDeadlocks(); + processQueue(); - return expand(pattern) -} - -var MAX_PATTERN_LENGTH = 1024 * 64 -var assertValidPattern = function (pattern) { - if (typeof pattern !== 'string') { - throw new TypeError('invalid pattern') - } + function enqueueTask(key, task) { + readyTasks.push(() => runTask(key, task)); + } - if (pattern.length > MAX_PATTERN_LENGTH) { - throw new TypeError('pattern is too long') - } -} + function processQueue() { + if (canceled) return + if (readyTasks.length === 0 && runningTasks === 0) { + return callback(null, results); + } + while(readyTasks.length && runningTasks < concurrency) { + var run = readyTasks.shift(); + run(); + } -// parse a component of the expanded set. -// At this point, no pattern may contain "/" in it -// so we're going to return a 2d array, where each entry is the full -// pattern, split on '/', and then turned into a regular expression. -// A regexp is made at the end which joins each array with an -// escaped /, and another full one which joins each regexp with |. -// -// Following the lead of Bash 4.1, note that "**" only has special meaning -// when it is the *only* thing in a path portion. Otherwise, any series -// of * is equivalent to a single *. Globstar behavior is enabled by -// default, and can be disabled by setting options.noglobstar. -Minimatch.prototype.parse = parse -var SUBPARSE = {} -function parse (pattern, isSub) { - assertValidPattern(pattern) + } - var options = this.options + function addListener(taskName, fn) { + var taskListeners = listeners[taskName]; + if (!taskListeners) { + taskListeners = listeners[taskName] = []; + } - // shortcuts - if (pattern === '**') { - if (!options.noglobstar) - return GLOBSTAR - else - pattern = '*' - } - if (pattern === '') return '' + taskListeners.push(fn); + } - var re = '' - var hasMagic = !!options.nocase - var escaping = false - // ? => one single character - var patternListStack = [] - var negativeLists = [] - var stateChar - var inClass = false - var reClassStart = -1 - var classStart = -1 - // . and .. never match anything that doesn't start with ., - // even when options.dot is set. - var patternStart = pattern.charAt(0) === '.' ? '' // anything - // not (start or / followed by . or .. followed by / or end) - : options.dot ? '(?!(?:^|\\\/)\\.{1,2}(?:$|\\\/))' - : '(?!\\.)' - var self = this + function taskComplete(taskName) { + var taskListeners = listeners[taskName] || []; + taskListeners.forEach(fn => fn()); + processQueue(); + } - function clearStateChar () { - if (stateChar) { - // we had some state-tracking character - // that wasn't consumed by this pass. - switch (stateChar) { - case '*': - re += star - hasMagic = true - break - case '?': - re += qmark - hasMagic = true - break - default: - re += '\\' + stateChar - break - } - self.debug('clearStateChar %j %j', stateChar, re) - stateChar = false - } - } - for (var i = 0, len = pattern.length, c - ; (i < len) && (c = pattern.charAt(i)) - ; i++) { - this.debug('%s\t%s %s %j', pattern, i, re, c) + function runTask(key, task) { + if (hasError) return; - // skip over any that are escaped. - if (escaping && reSpecials[c]) { - re += '\\' + c - escaping = false - continue - } + var taskCallback = onlyOnce((err, ...result) => { + runningTasks--; + if (err === false) { + canceled = true; + return + } + if (result.length < 2) { + [result] = result; + } + if (err) { + var safeResults = {}; + Object.keys(results).forEach(rkey => { + safeResults[rkey] = results[rkey]; + }); + safeResults[key] = result; + hasError = true; + listeners = Object.create(null); + if (canceled) return + callback(err, safeResults); + } else { + results[key] = result; + taskComplete(key); + } + }); - switch (c) { - /* istanbul ignore next */ - case '/': { - // completely not allowed, even escaped. - // Should already be path-split by now. - return false - } + runningTasks++; + var taskFn = wrapAsync(task[task.length - 1]); + if (task.length > 1) { + taskFn(results, taskCallback); + } else { + taskFn(taskCallback); + } + } - case '\\': - clearStateChar() - escaping = true - continue + function checkForDeadlocks() { + // Kahn's algorithm + // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm + // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html + var currentTask; + var counter = 0; + while (readyToCheck.length) { + currentTask = readyToCheck.pop(); + counter++; + getDependents(currentTask).forEach(dependent => { + if (--uncheckedDependencies[dependent] === 0) { + readyToCheck.push(dependent); + } + }); + } - // the various stateChar values - // for the "extglob" stuff. - case '?': - case '*': - case '+': - case '@': - case '!': - this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) + if (counter !== numTasks) { + throw new Error( + 'async.auto cannot execute tasks due to a recursive dependency' + ); + } + } - // all of those are literals inside a class, except that - // the glob [!a] means [^a] in regexp - if (inClass) { - this.debug(' in class') - if (c === '!' && i === classStart + 1) c = '^' - re += c - continue + function getDependents(taskName) { + var result = []; + Object.keys(tasks).forEach(key => { + const task = tasks[key]; + if (Array.isArray(task) && task.indexOf(taskName) >= 0) { + result.push(key); + } + }); + return result; } - // if we already have a stateChar, then it means - // that there was something like ** or +? in there. - // Handle the stateChar, then proceed with this one. - self.debug('call clearStateChar %j', stateChar) - clearStateChar() - stateChar = c - // if extglob is disabled, then +(asdf|foo) isn't a thing. - // just clear the statechar *now*, rather than even diving into - // the patternList stuff. - if (options.noext) clearStateChar() - continue + return callback[PROMISE_SYMBOL] + } - case '(': - if (inClass) { - re += '(' - continue + var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/; + var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/; + var FN_ARG_SPLIT = /,/; + var FN_ARG = /(=.+)?(\s*)$/; + + function stripComments(string) { + let stripped = ''; + let index = 0; + let endBlockComment = string.indexOf('*/'); + while (index < string.length) { + if (string[index] === '/' && string[index+1] === '/') { + // inline comment + let endIndex = string.indexOf('\n', index); + index = (endIndex === -1) ? string.length : endIndex; + } else if ((endBlockComment !== -1) && (string[index] === '/') && (string[index+1] === '*')) { + // block comment + let endIndex = string.indexOf('*/', index); + if (endIndex !== -1) { + index = endIndex + 2; + endBlockComment = string.indexOf('*/', index); + } else { + stripped += string[index]; + index++; + } + } else { + stripped += string[index]; + index++; + } } + return stripped; + } - if (!stateChar) { - re += '\\(' - continue + function parseParams(func) { + const src = stripComments(func.toString()); + let match = src.match(FN_ARGS); + if (!match) { + match = src.match(ARROW_FN_ARGS); } + if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) + let [, args] = match; + return args + .replace(/\s/g, '') + .split(FN_ARG_SPLIT) + .map((arg) => arg.replace(FN_ARG, '').trim()); + } - patternListStack.push({ - type: stateChar, - start: i - 1, - reStart: re.length, - open: plTypes[stateChar].open, - close: plTypes[stateChar].close - }) - // negation is (?:(?!js)[^/]*) - re += stateChar === '!' ? '(?:(?!(?:' : '(?:' - this.debug('plType %j %j', stateChar, re) - stateChar = false - continue + /** + * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent + * tasks are specified as parameters to the function, after the usual callback + * parameter, with the parameter names matching the names of the tasks it + * depends on. This can provide even more readable task graphs which can be + * easier to maintain. + * + * If a final callback is specified, the task results are similarly injected, + * specified as named parameters after the initial error parameter. + * + * The autoInject function is purely syntactic sugar and its semantics are + * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. + * + * @name autoInject + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.auto]{@link module:ControlFlow.auto} + * @category Control Flow + * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of + * the form 'func([dependencies...], callback). The object's key of a property + * serves as the name of the task defined by that property, i.e. can be used + * when specifying requirements for other tasks. + * * The `callback` parameter is a `callback(err, result)` which must be called + * when finished, passing an `error` (which can be `null`) and the result of + * the function's execution. The remaining parameters name other tasks on + * which the task is dependent, and the results from those tasks are the + * arguments of those parameters. + * @param {Function} [callback] - An optional callback which is called when all + * the tasks have been completed. It receives the `err` argument if any `tasks` + * pass an error to their callback, and a `results` object with any completed + * task results, similar to `auto`. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // The example from `auto` can be rewritten as follows: + * async.autoInject({ + * get_data: function(callback) { + * // async code to get some data + * callback(null, 'data', 'converted to array'); + * }, + * make_folder: function(callback) { + * // async code to create a directory to store a file in + * // this is run at the same time as getting the data + * callback(null, 'folder'); + * }, + * write_file: function(get_data, make_folder, callback) { + * // once there is some data and the directory exists, + * // write the data to a file in the directory + * callback(null, 'filename'); + * }, + * email_link: function(write_file, callback) { + * // once the file is written let's email a link to it... + * // write_file contains the filename returned by write_file. + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * } + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + * + * // If you are using a JS minifier that mangles parameter names, `autoInject` + * // will not work with plain functions, since the parameter names will be + * // collapsed to a single letter identifier. To work around this, you can + * // explicitly specify the names of the parameters your task function needs + * // in an array, similar to Angular.js dependency injection. + * + * // This still has an advantage over plain `auto`, since the results a task + * // depends on are still spread into arguments. + * async.autoInject({ + * //... + * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { + * callback(null, 'filename'); + * }], + * email_link: ['write_file', function(write_file, callback) { + * callback(null, {'file':write_file, 'email':'user@example.com'}); + * }] + * //... + * }, function(err, results) { + * console.log('err = ', err); + * console.log('email_link = ', results.email_link); + * }); + */ + function autoInject(tasks, callback) { + var newTasks = {}; - case ')': - if (inClass || !patternListStack.length) { - re += '\\)' - continue - } + Object.keys(tasks).forEach(key => { + var taskFn = tasks[key]; + var params; + var fnIsAsync = isAsync(taskFn); + var hasNoDeps = + (!fnIsAsync && taskFn.length === 1) || + (fnIsAsync && taskFn.length === 0); - clearStateChar() - hasMagic = true - var pl = patternListStack.pop() - // negation is (?:(?!js)[^/]*) - // The others are (?:) - re += pl.close - if (pl.type === '!') { - negativeLists.push(pl) - } - pl.reEnd = re.length - continue + if (Array.isArray(taskFn)) { + params = [...taskFn]; + taskFn = params.pop(); - case '|': - if (inClass || !patternListStack.length || escaping) { - re += '\\|' - escaping = false - continue - } + newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); + } else if (hasNoDeps) { + // no dependencies, use the function as-is + newTasks[key] = taskFn; + } else { + params = parseParams(taskFn); + if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { + throw new Error("autoInject task functions require explicit parameters."); + } - clearStateChar() - re += '|' - continue + // remove callback param + if (!fnIsAsync) params.pop(); - // these are mostly the same in regexp and glob - case '[': - // swallow any state-tracking char before the [ - clearStateChar() + newTasks[key] = params.concat(newTask); + } - if (inClass) { - re += '\\' + c - continue + function newTask(results, taskCb) { + var newArgs = params.map(name => results[name]); + newArgs.push(taskCb); + wrapAsync(taskFn)(...newArgs); + } + }); + + return auto(newTasks, callback); + } + + // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation + // used for queues. This implementation assumes that the node provided by the user can be modified + // to adjust the next and last properties. We implement only the minimal functionality + // for queue support. + class DLL { + constructor() { + this.head = this.tail = null; + this.length = 0; } - inClass = true - classStart = i - reClassStart = re.length - re += c - continue + removeLink(node) { + if (node.prev) node.prev.next = node.next; + else this.head = node.next; + if (node.next) node.next.prev = node.prev; + else this.tail = node.prev; - case ']': - // a right bracket shall lose its special - // meaning and represent itself in - // a bracket expression if it occurs - // first in the list. -- POSIX.2 2.8.3.2 - if (i === classStart + 1 || !inClass) { - re += '\\' + c - escaping = false - continue + node.prev = node.next = null; + this.length -= 1; + return node; } - // handle the case where we left a class open. - // "[z-a]" is valid, equivalent to "\[z-a\]" - // split where the last [ was, make sure we don't have - // an invalid re. if so, re-walk the contents of the - // would-be class to re-translate any characters that - // were passed through as-is - // TODO: It would probably be faster to determine this - // without a try/catch and a new RegExp, but it's tricky - // to do safely. For now, this is safe and works. - var cs = pattern.substring(classStart + 1, i) - try { - RegExp('[' + cs + ']') - } catch (er) { - // not a valid class! - var sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] + '\\]' - hasMagic = hasMagic || sp[1] - inClass = false - continue + empty () { + while(this.head) this.shift(); + return this; } - // finish up the class. - hasMagic = true - inClass = false - re += c - continue + insertAfter(node, newNode) { + newNode.prev = node; + newNode.next = node.next; + if (node.next) node.next.prev = newNode; + else this.tail = newNode; + node.next = newNode; + this.length += 1; + } - default: - // swallow any state char that wasn't consumed - clearStateChar() + insertBefore(node, newNode) { + newNode.prev = node.prev; + newNode.next = node; + if (node.prev) node.prev.next = newNode; + else this.head = newNode; + node.prev = newNode; + this.length += 1; + } - if (escaping) { - // no need - escaping = false - } else if (reSpecials[c] - && !(c === '^' && inClass)) { - re += '\\' + unshift(node) { + if (this.head) this.insertBefore(this.head, node); + else setInitial(this, node); } - re += c + push(node) { + if (this.tail) this.insertAfter(this.tail, node); + else setInitial(this, node); + } - } // switch - } // for - - // handle the case where we left a class open. - // "[abc" is valid, equivalent to "\[abc" - if (inClass) { - // split where the last [ was, and escape it - // this is a huge pita. We now have to re-walk - // the contents of the would-be class to re-translate - // any characters that were passed through as-is - cs = pattern.substr(classStart + 1) - sp = this.parse(cs, SUBPARSE) - re = re.substr(0, reClassStart) + '\\[' + sp[0] - hasMagic = hasMagic || sp[1] - } - - // handle the case where we had a +( thing at the *end* - // of the pattern. - // each pattern list stack adds 3 chars, and we need to go through - // and escape any | chars that were passed through as-is for the regexp. - // Go through and escape them, taking care not to double-escape any - // | chars that were already escaped. - for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { - var tail = re.slice(pl.reStart + pl.open.length) - this.debug('setting tail', re, pl) - // maybe some even number of \, then maybe 1 \, followed by a | - tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, function (_, $1, $2) { - if (!$2) { - // the | isn't already escaped, so escape it. - $2 = '\\' - } - - // need to escape all those slashes *again*, without escaping the - // one that we need for escaping the | character. As it works out, - // escaping an even number of slashes can be done by simply repeating - // it exactly after itself. That's why this trick works. - // - // I am sorry that you have to see this. - return $1 + $1 + $2 + '|' - }) - - this.debug('tail=%j\n %s', tail, tail, pl, re) - var t = pl.type === '*' ? star - : pl.type === '?' ? qmark - : '\\' + pl.type - - hasMagic = true - re = re.slice(0, pl.reStart) + t + '\\(' + tail - } - - // handle trailing things that only matter at the very end. - clearStateChar() - if (escaping) { - // trailing \\ - re += '\\\\' - } - - // only need to apply the nodot start if the re starts with - // something that could conceivably capture a dot - var addPatternStart = false - switch (re.charAt(0)) { - case '[': case '.': case '(': addPatternStart = true - } + shift() { + return this.head && this.removeLink(this.head); + } - // Hack to work around lack of negative lookbehind in JS - // A pattern like: *.!(x).!(y|z) needs to ensure that a name - // like 'a.xyz.yz' doesn't match. So, the first negative - // lookahead, has to look ALL the way ahead, to the end of - // the pattern. - for (var n = negativeLists.length - 1; n > -1; n--) { - var nl = negativeLists[n] + pop() { + return this.tail && this.removeLink(this.tail); + } - var nlBefore = re.slice(0, nl.reStart) - var nlFirst = re.slice(nl.reStart, nl.reEnd - 8) - var nlLast = re.slice(nl.reEnd - 8, nl.reEnd) - var nlAfter = re.slice(nl.reEnd) + toArray() { + return [...this] + } - nlLast += nlAfter + *[Symbol.iterator] () { + var cur = this.head; + while (cur) { + yield cur.data; + cur = cur.next; + } + } - // Handle nested stuff like *(*.js|!(*.json)), where open parens - // mean that we should *not* include the ) in the bit that is considered - // "after" the negated section. - var openParensBefore = nlBefore.split('(').length - 1 - var cleanAfter = nlAfter - for (i = 0; i < openParensBefore; i++) { - cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + remove (testFn) { + var curr = this.head; + while(curr) { + var {next} = curr; + if (testFn(curr)) { + this.removeLink(curr); + } + curr = next; + } + return this; + } } - nlAfter = cleanAfter - var dollar = '' - if (nlAfter === '' && isSub !== SUBPARSE) { - dollar = '$' + function setInitial(dll, node) { + dll.length = 1; + dll.head = dll.tail = node; } - var newRe = nlBefore + nlFirst + nlAfter + dollar + nlLast - re = newRe - } - - // if the re is not "" at this point, then we need to make sure - // it doesn't match against an empty path part. - // Otherwise a/* will match a/, which it should not. - if (re !== '' && hasMagic) { - re = '(?=.)' + re - } - - if (addPatternStart) { - re = patternStart + re - } - - // parsing just a piece of a larger pattern. - if (isSub === SUBPARSE) { - return [re, hasMagic] - } - // skip the regexp for non-magical patterns - // unescape anything in it, though, so that it'll be - // an exact match against a file etc. - if (!hasMagic) { - return globUnescape(pattern) - } + function queue$1(worker, concurrency, payload) { + if (concurrency == null) { + concurrency = 1; + } + else if(concurrency === 0) { + throw new RangeError('Concurrency must not be zero'); + } - var flags = options.nocase ? 'i' : '' - try { - var regExp = new RegExp('^' + re + '$', flags) - } catch (er) /* istanbul ignore next - should be impossible */ { - // If it was an invalid regular expression, then it can't match - // anything. This trick looks for a character after the end of - // the string, which is of course impossible, except in multi-line - // mode, but it's not a /m regex. - return new RegExp('$.') - } + var _worker = wrapAsync(worker); + var numRunning = 0; + var workersList = []; + const events = { + error: [], + drain: [], + saturated: [], + unsaturated: [], + empty: [] + }; - regExp._glob = pattern - regExp._src = re + function on (event, handler) { + events[event].push(handler); + } - return regExp -} + function once (event, handler) { + const handleAndRemove = (...args) => { + off(event, handleAndRemove); + handler(...args); + }; + events[event].push(handleAndRemove); + } -minimatch.makeRe = function (pattern, options) { - return new Minimatch(pattern, options || {}).makeRe() -} + function off (event, handler) { + if (!event) return Object.keys(events).forEach(ev => events[ev] = []) + if (!handler) return events[event] = [] + events[event] = events[event].filter(ev => ev !== handler); + } -Minimatch.prototype.makeRe = makeRe -function makeRe () { - if (this.regexp || this.regexp === false) return this.regexp + function trigger (event, ...args) { + events[event].forEach(handler => handler(...args)); + } - // at this point, this.set is a 2d array of partial - // pattern strings, or "**". - // - // It's better to use .match(). This function shouldn't - // be used, really, but it's pretty convenient sometimes, - // when you just want to work with a regex. - var set = this.set + var processingScheduled = false; + function _insert(data, insertAtFront, rejectOnError, callback) { + if (callback != null && typeof callback !== 'function') { + throw new Error('task callback must be a function'); + } + q.started = true; - if (!set.length) { - this.regexp = false - return this.regexp - } - var options = this.options + var res, rej; + function promiseCallback (err, ...args) { + // we don't care about the error, let the global error handler + // deal with it + if (err) return rejectOnError ? rej(err) : res() + if (args.length <= 1) return res(args[0]) + res(args); + } - var twoStar = options.noglobstar ? star - : options.dot ? twoStarDot - : twoStarNoDot - var flags = options.nocase ? 'i' : '' + var item = q._createTaskItem( + data, + rejectOnError ? promiseCallback : + (callback || promiseCallback) + ); - var re = set.map(function (pattern) { - return pattern.map(function (p) { - return (p === GLOBSTAR) ? twoStar - : (typeof p === 'string') ? regExpEscape(p) - : p._src - }).join('\\\/') - }).join('|') + if (insertAtFront) { + q._tasks.unshift(item); + } else { + q._tasks.push(item); + } - // must match entire pattern - // ending in a * or ** will make it less strict. - re = '^(?:' + re + ')$' + if (!processingScheduled) { + processingScheduled = true; + setImmediate$1(() => { + processingScheduled = false; + q.process(); + }); + } - // can match anything, as long as it's not this. - if (this.negate) re = '^(?!' + re + ').*$' + if (rejectOnError || !callback) { + return new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }) + } + } - try { - this.regexp = new RegExp(re, flags) - } catch (ex) /* istanbul ignore next - should be impossible */ { - this.regexp = false - } - return this.regexp -} + function _createCB(tasks) { + return function (err, ...args) { + numRunning -= 1; -minimatch.match = function (list, pattern, options) { - options = options || {} - var mm = new Minimatch(pattern, options) - list = list.filter(function (f) { - return mm.match(f) - }) - if (mm.options.nonull && !list.length) { - list.push(pattern) - } - return list -} + for (var i = 0, l = tasks.length; i < l; i++) { + var task = tasks[i]; -Minimatch.prototype.match = function match (f, partial) { - if (typeof partial === 'undefined') partial = this.partial - this.debug('match', f, this.pattern) - // short-circuit in the case of busted things. - // comments, etc. - if (this.comment) return false - if (this.empty) return f === '' + var index = workersList.indexOf(task); + if (index === 0) { + workersList.shift(); + } else if (index > 0) { + workersList.splice(index, 1); + } - if (f === '/' && partial) return true + task.callback(err, ...args); - var options = this.options + if (err != null) { + trigger('error', err, task.data); + } + } - // windows: need to use /, not \ - if (path.sep !== '/') { - f = f.split(path.sep).join('/') - } + if (numRunning <= (q.concurrency - q.buffer) ) { + trigger('unsaturated'); + } - // treat the test path as a set of pathparts. - f = f.split(slashSplit) - this.debug(this.pattern, 'split', f) + if (q.idle()) { + trigger('drain'); + } + q.process(); + }; + } - // just ONE of the pattern sets in this.set needs to match - // in order for it to be valid. If negating, then just one - // match means that we have failed. - // Either way, return on the first hit. + function _maybeDrain(data) { + if (data.length === 0 && q.idle()) { + // call drain immediately if there are no tasks + setImmediate$1(() => trigger('drain')); + return true + } + return false + } - var set = this.set - this.debug(this.pattern, 'set', set) + const eventMethod = (name) => (handler) => { + if (!handler) { + return new Promise((resolve, reject) => { + once(name, (err, data) => { + if (err) return reject(err) + resolve(data); + }); + }) + } + off(name); + on(name, handler); - // Find the basename of the path by looking for the last non-empty segment - var filename - var i - for (i = f.length - 1; i >= 0; i--) { - filename = f[i] - if (filename) break - } + }; - for (i = 0; i < set.length; i++) { - var pattern = set[i] - var file = f - if (options.matchBase && pattern.length === 1) { - file = [filename] - } - var hit = this.matchOne(file, pattern, partial) - if (hit) { - if (options.flipNegate) return true - return !this.negate - } - } + var isProcessing = false; + var q = { + _tasks: new DLL(), + _createTaskItem (data, callback) { + return { + data, + callback + }; + }, + *[Symbol.iterator] () { + yield* q._tasks[Symbol.iterator](); + }, + concurrency, + payload, + buffer: concurrency / 4, + started: false, + paused: false, + push (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, false, callback)) + } + return _insert(data, false, false, callback); + }, + pushAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, false, true, callback)) + } + return _insert(data, false, true, callback); + }, + kill () { + off(); + q._tasks.empty(); + }, + unshift (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, false, callback)) + } + return _insert(data, true, false, callback); + }, + unshiftAsync (data, callback) { + if (Array.isArray(data)) { + if (_maybeDrain(data)) return + return data.map(datum => _insert(datum, true, true, callback)) + } + return _insert(data, true, true, callback); + }, + remove (testFn) { + q._tasks.remove(testFn); + }, + process () { + // Avoid trying to start too many processing operations. This can occur + // when callbacks resolve synchronously (#1267). + if (isProcessing) { + return; + } + isProcessing = true; + while(!q.paused && numRunning < q.concurrency && q._tasks.length){ + var tasks = [], data = []; + var l = q._tasks.length; + if (q.payload) l = Math.min(l, q.payload); + for (var i = 0; i < l; i++) { + var node = q._tasks.shift(); + tasks.push(node); + workersList.push(node); + data.push(node.data); + } - // didn't get any hits. this is success if it's a negative - // pattern, failure otherwise. - if (options.flipNegate) return false - return this.negate -} + numRunning += 1; -// set partial to true to test if, for example, -// "/a/b" matches the start of "/*/b/*/d" -// Partial means, if you run out of file before you run -// out of pattern, then that's fine, as long as all -// the parts match. -Minimatch.prototype.matchOne = function (file, pattern, partial) { - var options = this.options + if (q._tasks.length === 0) { + trigger('empty'); + } - this.debug('matchOne', - { 'this': this, file: file, pattern: pattern }) + if (numRunning === q.concurrency) { + trigger('saturated'); + } - this.debug('matchOne', file.length, pattern.length) + var cb = onlyOnce(_createCB(tasks)); + _worker(data, cb); + } + isProcessing = false; + }, + length () { + return q._tasks.length; + }, + running () { + return numRunning; + }, + workersList () { + return workersList; + }, + idle() { + return q._tasks.length + numRunning === 0; + }, + pause () { + q.paused = true; + }, + resume () { + if (q.paused === false) { return; } + q.paused = false; + setImmediate$1(q.process); + } + }; + // define these as fixed properties, so people get useful errors when updating + Object.defineProperties(q, { + saturated: { + writable: false, + value: eventMethod('saturated') + }, + unsaturated: { + writable: false, + value: eventMethod('unsaturated') + }, + empty: { + writable: false, + value: eventMethod('empty') + }, + drain: { + writable: false, + value: eventMethod('drain') + }, + error: { + writable: false, + value: eventMethod('error') + }, + }); + return q; + } - for (var fi = 0, - pi = 0, - fl = file.length, - pl = pattern.length - ; (fi < fl) && (pi < pl) - ; fi++, pi++) { - this.debug('matchOne loop') - var p = pattern[pi] - var f = file[fi] - - this.debug(pattern, p, f) - - // should be impossible. - // some invalid regexp stuff in the set. - /* istanbul ignore if */ - if (p === false) return false + /** + * Creates a `cargo` object with the specified payload. Tasks added to the + * cargo will be processed altogether (up to the `payload` limit). If the + * `worker` is in progress, the task is queued until it becomes available. Once + * the `worker` has completed some tasks, each callback of those tasks is + * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) + * for how `cargo` and `queue` work. + * + * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers + * at a time, cargo passes an array of tasks to a single worker, repeating + * when the worker is finished. + * + * @name cargo + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An asynchronous function for processing an array + * of queued tasks. Invoked with `(tasks, callback)`. + * @param {number} [payload=Infinity] - An optional `integer` for determining + * how many tasks should be processed per round; if omitted, the default is + * unlimited. + * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can + * attached as certain properties to listen for specific events during the + * lifecycle of the cargo and inner queue. + * @example + * + * // create a cargo object with payload 2 + * var cargo = async.cargo(function(tasks, callback) { + * for (var i=0; i no - // - matchOne(y/z/c, c) -> no - // - matchOne(z/c, c) -> no - // - matchOne(c, c) yes, hit - var fr = fi - var pr = pi + 1 - if (pr === pl) { - this.debug('** at the end') - // a ** at the end will just swallow the rest. - // We have found a match. - // however, it will not swallow /.x, unless - // options.dot is set. - // . and .. are *never* matched by **, for explosively - // exponential reasons. - for (; fi < fl; fi++) { - if (file[fi] === '.' || file[fi] === '..' || - (!options.dot && file[fi].charAt(0) === '.')) return false - } - return true - } + /** + * Reduces `coll` into a single value using an async `iteratee` to return each + * successive step. `memo` is the initial state of the reduction. This function + * only operates in series. + * + * For performance reasons, it may make sense to split a call to this function + * into a parallel map, and then use the normal `Array.prototype.reduce` on the + * results. This function is for situations where each step in the reduction + * needs to be async; if you can get the data before reducing it, then it's + * probably a good idea to do so. + * + * @name reduce + * @static + * @memberOf module:Collections + * @method + * @alias inject + * @alias foldl + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file3.txt', 'file4.txt']; + * + * // asynchronous function that computes the file size in bytes + * // file size is added to the memoized value, then returned + * function getFileSizeInBytes(memo, file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, memo + stat.size); + * }); + * } + * + * // Using callbacks + * async.reduce(fileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.reduce(fileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.reduce(withMissingFileList, 0, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.reduce(fileList, 0, getFileSizeInBytes); + * console.log(result); + * // 6000 + * // which is the sum of the file sizes of the three files + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function reduce(coll, memo, iteratee, callback) { + callback = once(callback); + var _iteratee = wrapAsync(iteratee); + return eachOfSeries$1(coll, (x, i, iterCb) => { + _iteratee(memo, x, (err, v) => { + memo = v; + iterCb(err); + }); + }, err => callback(err, memo)); + } + var reduce$1 = awaitify(reduce, 4); - // ok, let's see if we can swallow whatever we can. - while (fr < fl) { - var swallowee = file[fr] + /** + * Version of the compose function that is more natural to read. Each function + * consumes the return value of the previous function. It is the equivalent of + * [compose]{@link module:ControlFlow.compose} with the arguments reversed. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name seq + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.compose]{@link module:ControlFlow.compose} + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} a function that composes the `functions` in order + * @example + * + * // Requires lodash (or underscore), express3 and dresende's orm2. + * // Part of an app, that fetches cats of the logged user. + * // This example uses `seq` function to avoid overnesting and error + * // handling clutter. + * app.get('/cats', function(request, response) { + * var User = request.models.User; + * async.seq( + * User.get.bind(User), // 'User.get' has signature (id, callback(err, data)) + * function(user, fn) { + * user.getCats(fn); // 'getCats' has signature (callback(err, data)) + * } + * )(req.session.user_id, function (err, cats) { + * if (err) { + * console.error(err); + * response.json({ status: 'error', message: err.message }); + * } else { + * response.json({ status: 'ok', message: 'Cats found', data: cats }); + * } + * }); + * }); + */ + function seq(...functions) { + var _functions = functions.map(wrapAsync); + return function (...args) { + var that = this; - this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) + var cb = args[args.length - 1]; + if (typeof cb == 'function') { + args.pop(); + } else { + cb = promiseCallback(); + } - // XXX remove this slice. Just pass the start index. - if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { - this.debug('globstar found match!', fr, fl, swallowee) - // found a match. - return true - } else { - // can't swallow "." or ".." ever. - // can only swallow ".foo" when explicitly asked. - if (swallowee === '.' || swallowee === '..' || - (!options.dot && swallowee.charAt(0) === '.')) { - this.debug('dot detected!', file, fr, pattern, pr) - break - } + reduce$1(_functions, args, (newargs, fn, iterCb) => { + fn.apply(that, newargs.concat((err, ...nextargs) => { + iterCb(err, nextargs); + })); + }, + (err, results) => cb(err, ...results)); - // ** swallows a segment, and continue. - this.debug('globstar swallow a segment, and continue') - fr++ - } - } + return cb[PROMISE_SYMBOL] + }; + } - // no match was found. - // However, in partial mode, we can't say this is necessarily over. - // If there's more *pattern* left, then - /* istanbul ignore if */ - if (partial) { - // ran out of file - this.debug('\n>>> no match, partial?', file, fr, pattern, pr) - if (fr === fl) return true - } - return false + /** + * Creates a function which is a composition of the passed asynchronous + * functions. Each function consumes the return value of the function that + * follows. Composing functions `f()`, `g()`, and `h()` would produce the result + * of `f(g(h()))`, only this version uses callbacks to obtain the return values. + * + * If the last argument to the composed function is not a function, a promise + * is returned when you call it. + * + * Each function is executed with the `this` binding of the composed function. + * + * @name compose + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {...AsyncFunction} functions - the asynchronous functions to compose + * @returns {Function} an asynchronous function that is the composed + * asynchronous `functions` + * @example + * + * function add1(n, callback) { + * setTimeout(function () { + * callback(null, n + 1); + * }, 10); + * } + * + * function mul3(n, callback) { + * setTimeout(function () { + * callback(null, n * 3); + * }, 10); + * } + * + * var add1mul3 = async.compose(mul3, add1); + * add1mul3(4, function (err, result) { + * // result now equals 15 + * }); + */ + function compose(...args) { + return seq(...args.reverse()); } - // something other than ** - // non-magic patterns just have to match exactly - // patterns with magic have been turned into regexps. - var hit - if (typeof p === 'string') { - hit = f === p - this.debug('string match', p, f, hit) - } else { - hit = f.match(p) - this.debug('pattern match', p, f, hit) + /** + * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. + * + * @name mapLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.map]{@link module:Collections.map} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with the transformed item. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Results is an array of the + * transformed items from the `coll`. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function mapLimit (coll, limit, iteratee, callback) { + return _asyncMap(eachOfLimit$2(limit), coll, iteratee, callback) } + var mapLimit$1 = awaitify(mapLimit, 4); - if (!hit) return false - } + /** + * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. + * + * @name concatLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapLimit + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, ...args) => { + if (err) return iterCb(err); + return iterCb(err, args); + }); + }, (err, mapResults) => { + var result = []; + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + result = result.concat(...mapResults[i]); + } + } - // Note: ending in / means that we'll get a final "" - // at the end of the pattern. This can only match a - // corresponding "" at the end of the file. - // If the file ends in /, then it can only match a - // a pattern that ends in /, unless the pattern just - // doesn't have any more for it. But, a/b/ should *not* - // match "a/b/*", even though "" matches against the - // [^/]*? pattern, except in partial mode, where it might - // simply not be reached yet. - // However, a/b/ should still satisfy a/* + return callback(err, result); + }); + } + var concatLimit$1 = awaitify(concatLimit, 4); - // now either we fell off the end of the pattern, or we're done. - if (fi === fl && pi === pl) { - // ran out of pattern and filename at the same time. - // an exact hit! - return true - } else if (fi === fl) { - // ran out of file, but still had pattern left. - // this is ok if we're doing the match as part of - // a glob fs traversal. - return partial - } else /* istanbul ignore else */ if (pi === pl) { - // ran out of pattern, still have file left. - // this is only acceptable if we're on the very last - // empty segment of a file with a trailing slash. - // a/* should match a/b/ - return (fi === fl - 1) && (file[fi] === '') - } - - // should be unreachable. - /* istanbul ignore next */ - throw new Error('wtf?') -} - -// replace stuff like \* with * -function globUnescape (s) { - return s.replace(/\\(.)/g, '$1') -} - -function regExpEscape (s) { - return s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') -} + /** + * Applies `iteratee` to each item in `coll`, concatenating the results. Returns + * the concatenated list. The `iteratee`s are called in parallel, and the + * results are concatenated as they return. The results array will be returned in + * the original order of `coll` passed to the `iteratee` function. + * + * @name concat + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @alias flatMap + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, + * which should use an array as its result. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * let directoryList = ['dir1','dir2','dir3']; + * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; + * + * // Using callbacks + * async.concat(directoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } else { + * console.log(results); + * } + * }); + * + * // Using Promises + * async.concat(directoryList, fs.readdir) + * .then(results => { + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Error Handling + * async.concat(withMissingDirectoryList, fs.readdir) + * .then(results => { + * console.log(results); + * }).catch(err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.concat(directoryList, fs.readdir); + * console.log(results); + * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] + * } catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let results = await async.concat(withMissingDirectoryList, fs.readdir); + * console.log(results); + * } catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4 does not exist + * } + * } + * + */ + function concat(coll, iteratee, callback) { + return concatLimit$1(coll, Infinity, iteratee, callback) + } + var concat$1 = awaitify(concat, 3); + /** + * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. + * + * @name concatSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.concat]{@link module:Collections.concat} + * @category Collection + * @alias flatMapSeries + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. + * The iteratee should complete with an array an array of results. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is an array + * containing the concatenated results of the `iteratee` function. Invoked with + * (err, results). + * @returns A Promise, if no callback is passed + */ + function concatSeries(coll, iteratee, callback) { + return concatLimit$1(coll, 1, iteratee, callback) + } + var concatSeries$1 = awaitify(concatSeries, 3); -/***/ }), + /** + * Returns a function that when called, calls-back with the values provided. + * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to + * [`auto`]{@link module:ControlFlow.auto}. + * + * @name constant + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {...*} arguments... - Any number of arguments to automatically invoke + * callback with. + * @returns {AsyncFunction} Returns a function that when invoked, automatically + * invokes the callback with the previous given arguments. + * @example + * + * async.waterfall([ + * async.constant(42), + * function (value, next) { + * // value === 42 + * }, + * //... + * ], callback); + * + * async.waterfall([ + * async.constant(filename, "utf8"), + * fs.readFile, + * function (fileData, next) { + * //... + * } + * //... + * ], callback); + * + * async.auto({ + * hostname: async.constant("https://server.net/"), + * port: findFreePort, + * launchServer: ["hostname", "port", function (options, cb) { + * startServer(options, cb); + * }], + * //... + * }, callback); + */ + function constant$1(...args) { + return function (...ignoredArgs/*, callback*/) { + var callback = ignoredArgs.pop(); + return callback(null, ...args); + }; + } -/***/ 5364: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + function _createTester(check, getResult) { + return (eachfn, arr, _iteratee, cb) => { + var testPassed = false; + var testResult; + const iteratee = wrapAsync(_iteratee); + eachfn(arr, (value, _, callback) => { + iteratee(value, (err, result) => { + if (err || err === false) return callback(err); -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + if (check(result) && !testResult) { + testPassed = true; + testResult = getResult(true, value); + return callback(null, breakLoop$1); + } + callback(); + }); + }, err => { + if (err) return cb(err); + cb(null, testPassed ? testResult : getResult(false)); + }); + }; + } -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. + /** + * Returns the first value in `coll` that passes an async truth test. The + * `iteratee` is applied in parallel, meaning the first iteratee to return + * `true` will fire the detect `callback` with that result. That means the + * result might not be the first item in the original `coll` (in terms of order) + * that passes the test. + * If order within the original `coll` is important, then look at + * [`detectSeries`]{@link module:Collections.detectSeries}. + * + * @name detect + * @static + * @memberOf module:Collections + * @method + * @alias find + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * } + *); + * + * // Using Promises + * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) + * .then(result => { + * console.log(result); + * // dir1/file1.txt + * // result now equals the first file in the list that exists + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); + * console.log(result); + * // dir1/file1.txt + * // result now equals the file in the list that exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function detect(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) + } + var detect$1 = awaitify(detect, 3); + /** + * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a + * time. + * + * @name detectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findLimit + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ + function detectLimit(coll, limit, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(limit), coll, iteratee, callback) + } + var detectLimit$1 = awaitify(detectLimit, 4); -/**/ + /** + * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. + * + * @name detectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.detect]{@link module:Collections.detect} + * @alias findSeries + * @category Collections + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. + * The iteratee must complete with a boolean value as its result. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the `iteratee` functions have finished. + * Result will be the first item in the array that passes the truth test + * (iteratee) or the value `undefined` if none passed. Invoked with + * (err, result). + * @returns {Promise} a promise, if a callback is omitted + */ + function detectSeries(coll, iteratee, callback) { + return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(1), coll, iteratee, callback) + } -var pna = __nccwpck_require__(47810); -/**/ + var detectSeries$1 = awaitify(detectSeries, 3); -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; -/**/ + function consoleFunc(name) { + return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { + /* istanbul ignore else */ + if (typeof console === 'object') { + /* istanbul ignore else */ + if (err) { + /* istanbul ignore else */ + if (console.error) { + console.error(err); + } + } else if (console[name]) { /* istanbul ignore else */ + resultArgs.forEach(x => console[name](x)); + } + } + }) + } -module.exports = Duplex; + /** + * Logs the result of an [`async` function]{@link AsyncFunction} to the + * `console` using `console.dir` to display the properties of the resulting object. + * Only works in Node.js or in browsers that support `console.dir` and + * `console.error` (such as FF and Chrome). + * If multiple arguments are returned from the async function, + * `console.dir` is called on each argument in order. + * + * @name dir + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, {hello: name}); + * }, 1000); + * }; + * + * // in the node repl + * node> async.dir(hello, 'world'); + * {hello: 'world'} + */ + var dir = consoleFunc('dir'); -/**/ -var util = Object.create(__nccwpck_require__(95898)); -util.inherits = __nccwpck_require__(44124); -/**/ + /** + * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in + * the order of operations, the arguments `test` and `iteratee` are switched. + * + * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. + * + * @name doWhilst + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - A function which is called each time `test` + * passes. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee`. + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. + * `callback` will be passed an error and any arguments passed to the final + * `iteratee`'s callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doWhilst(iteratee, test, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results; -var Readable = __nccwpck_require__(19647); -var Writable = __nccwpck_require__(33369); + function next(err, ...args) { + if (err) return callback(err); + if (err === false) return; + results = args; + _test(...args, check); + } -util.inherits(Duplex, Readable); + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } -{ - // avoid scope creep, the keys array can then be collected - var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} + return check(null, true); + } -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); + var doWhilst$1 = awaitify(doWhilst, 3); - Readable.call(this, options); - Writable.call(this, options); + /** + * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the + * argument ordering differs from `until`. + * + * @name doUntil + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} + * @category Control Flow + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {AsyncFunction} test - asynchronous truth test to perform after each + * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the + * non-error args from the previous callback of `iteratee` + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + */ + function doUntil(iteratee, test, callback) { + const _test = wrapAsync(test); + return doWhilst$1(iteratee, (...args) => { + const cb = args.pop(); + _test(...args, (err, truth) => cb (err, !truth)); + }, callback); + } - if (options && options.readable === false) this.readable = false; + function _withoutIndex(iteratee) { + return (value, index, callback) => iteratee(value, callback); + } - if (options && options.writable === false) this.writable = false; - - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + /** + * Applies the function `iteratee` to each item in `coll`, in parallel. + * The `iteratee` is called with an item from the list, and a callback for when + * it has finished. If the `iteratee` passes an error to its `callback`, the + * main `callback` (for the `each` function) is immediately called with the + * error. + * + * Note, that since this function applies `iteratee` to each item in parallel, + * there is no guarantee that the iteratee functions will complete in order. + * + * @name each + * @static + * @memberOf module:Collections + * @method + * @alias forEach + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to + * each item in `coll`. Invoked with (item, callback). + * The array index is not passed to the iteratee. + * If you need the index, use `eachOf`. + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; + * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; + * + * // asynchronous function that deletes a file + * const deleteFile = function(file, callback) { + * fs.unlink(file, callback); + * }; + * + * // Using callbacks + * async.each(fileList, deleteFile, function(err) { + * if( err ) { + * console.log(err); + * } else { + * console.log('All files have been deleted successfully'); + * } + * }); + * + * // Error Handling + * async.each(withMissingFileList, deleteFile, function(err){ + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using Promises + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * }); + * + * // Error Handling + * async.each(fileList, deleteFile) + * .then( () => { + * console.log('All files have been deleted successfully'); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * }); + * + * // Using async/await + * async () => { + * try { + * await async.each(files, deleteFile); + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * await async.each(withMissingFileList, deleteFile); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * // since dir4/file2.txt does not exist + * // dir1/file1.txt could have been deleted + * } + * } + * + */ + function eachLimit$2(coll, iteratee, callback) { + return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } - this.once('end', onend); -} + var each = awaitify(eachLimit$2, 3); -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._writableState.highWaterMark; - } -}); + /** + * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. + * + * @name eachLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfLimit`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachLimit(coll, limit, iteratee, callback) { + return eachOfLimit$2(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); + } + var eachLimit$1 = awaitify(eachLimit, 4); -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; + /** + * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. + * + * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item + * in series and therefore the iteratee functions will complete in order. - // no more data can be written. - // But allow more writes to happen in this tick. - pna.nextTick(onEndNT, this); -} + * @name eachSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.each]{@link module:Collections.each} + * @alias forEachSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each + * item in `coll`. + * The array index is not passed to the iteratee. + * If you need the index, use `eachOfSeries`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called when all + * `iteratee` functions have finished, or an error occurs. Invoked with (err). + * @returns {Promise} a promise, if a callback is omitted + */ + function eachSeries(coll, iteratee, callback) { + return eachLimit$1(coll, 1, iteratee, callback) + } + var eachSeries$1 = awaitify(eachSeries, 3); -function onEndNT(self) { - self.end(); -} + /** + * Wrap an async function and ensure it calls its callback on a later tick of + * the event loop. If the function already calls its callback on a next tick, + * no extra deferral is added. This is useful for preventing stack overflows + * (`RangeError: Maximum call stack size exceeded`) and generally keeping + * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) + * contained. ES2017 `async` functions are returned as-is -- they are immune + * to Zalgo's corrupting influences, as they always resolve on a later tick. + * + * @name ensureAsync + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - an async function, one that expects a node-style + * callback as its last argument. + * @returns {AsyncFunction} Returns a wrapped function with the exact same call + * signature as the function passed in. + * @example + * + * function sometimesAsync(arg, callback) { + * if (cache[arg]) { + * return callback(null, cache[arg]); // this would be synchronous!! + * } else { + * doSomeIO(arg, callback); // this IO would be asynchronous + * } + * } + * + * // this has a risk of stack overflows if many results are cached in a row + * async.mapSeries(args, sometimesAsync, done); + * + * // this will defer sometimesAsync's callback if necessary, + * // preventing stack overflows + * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); + */ + function ensureAsync(fn) { + if (isAsync(fn)) return fn; + return function (...args/*, callback*/) { + var callback = args.pop(); + var sync = true; + args.push((...innerArgs) => { + if (sync) { + setImmediate$1(() => callback(...innerArgs)); + } else { + callback(...innerArgs); + } + }); + fn.apply(this, args); + sync = false; + }; + } -Object.defineProperty(Duplex.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined || this._writableState === undefined) { - return false; + /** + * Returns `true` if every element in `coll` satisfies an async test. If any + * iteratee call returns `false`, the main `callback` is immediately called. + * + * @name every + * @static + * @memberOf module:Collections + * @method + * @alias all + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; + * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.every(fileList, fileExists, function(err, result) { + * console.log(result); + * // true + * // result is true since every file exists + * }); + * + * async.every(withMissingFileList, fileExists, function(err, result) { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }); + * + * // Using Promises + * async.every(fileList, fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.every(withMissingFileList, fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since NOT every file exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.every(fileList, fileExists); + * console.log(result); + * // true + * // result is true since every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.every(withMissingFileList, fileExists); + * console.log(result); + * // false + * // result is false since NOT every file exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function every(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; + var every$1 = awaitify(every, 3); + + /** + * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. + * + * @name everyLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in parallel. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everyLimit(coll, limit, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfLimit$2(limit), coll, iteratee, callback) } + var everyLimit$1 = awaitify(everyLimit, 4); - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); + /** + * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. + * + * @name everySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.every]{@link module:Collections.every} + * @alias allSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collection in series. + * The iteratee must complete with a boolean result value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result will be either `true` or `false` + * depending on the values of the async tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function everySeries(coll, iteratee, callback) { + return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) + } + var everySeries$1 = awaitify(everySeries, 3); -Duplex.prototype._destroy = function (err, cb) { - this.push(null); - this.end(); + function filterArray(eachfn, arr, iteratee, callback) { + var truthValues = new Array(arr.length); + eachfn(arr, (x, index, iterCb) => { + iteratee(x, (err, v) => { + truthValues[index] = !!v; + iterCb(err); + }); + }, err => { + if (err) return callback(err); + var results = []; + for (var i = 0; i < arr.length; i++) { + if (truthValues[i]) results.push(arr[i]); + } + callback(null, results); + }); + } - pna.nextTick(cb, err); -}; + function filterGeneric(eachfn, coll, iteratee, callback) { + var results = []; + eachfn(coll, (x, index, iterCb) => { + iteratee(x, (err, v) => { + if (err) return iterCb(err); + if (v) { + results.push({index, value: x}); + } + iterCb(err); + }); + }, err => { + if (err) return callback(err); + callback(null, results + .sort((a, b) => a.index - b.index) + .map(v => v.value)); + }); + } -/***/ }), + function _filter(eachfn, coll, iteratee, callback) { + var filter = isArrayLike(coll) ? filterArray : filterGeneric; + return filter(eachfn, coll, wrapAsync(iteratee), callback); + } -/***/ 47905: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * Returns a new array of all the values in `coll` which pass an async truth + * test. This operation is performed in parallel, but the results array will be + * in the same order as the original. + * + * @name filter + * @static + * @memberOf module:Collections + * @method + * @alias select + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.filter(files, fileExists, function(err, results) { + * if(err) { + * console.log(err); + * } else { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * }); + * + * // Using Promises + * async.filter(files, fileExists) + * .then(results => { + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.filter(files, fileExists); + * console.log(results); + * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] + * // results is now an array of the existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function filter (coll, iteratee, callback) { + return _filter(eachOf$1, coll, iteratee, callback) + } + var filter$1 = awaitify(filter, 3); -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. + /** + * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a + * time. + * + * @name filterLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback provided + */ + function filterLimit (coll, limit, iteratee, callback) { + return _filter(eachOfLimit$2(limit), coll, iteratee, callback) + } + var filterLimit$1 = awaitify(filterLimit, 4); + /** + * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. + * + * @name filterSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @alias selectSeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - A truth test to apply to each item in `coll`. + * The `iteratee` is passed a `callback(err, truthValue)`, which must be called + * with a boolean argument once it has completed. Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results) + * @returns {Promise} a promise, if no callback provided + */ + function filterSeries (coll, iteratee, callback) { + return _filter(eachOfSeries$1, coll, iteratee, callback) + } + var filterSeries$1 = awaitify(filterSeries, 3); + /** + * Calls the asynchronous function `fn` with a callback parameter that allows it + * to call itself again, in series, indefinitely. -module.exports = PassThrough; + * If an error is passed to the callback then `errback` is called with the + * error, and execution stops, otherwise it will never be called. + * + * @name forever + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} fn - an async function to call repeatedly. + * Invoked with (next). + * @param {Function} [errback] - when `fn` passes an error to it's callback, + * this function will be called, and execution stops. Invoked with (err). + * @returns {Promise} a promise that rejects if an error occurs and an errback + * is not passed + * @example + * + * async.forever( + * function(next) { + * // next is suitable for passing to things that need a callback(err [, whatever]); + * // it will result in this function being called again. + * }, + * function(err) { + * // if next is called with a value in its first parameter, it will appear + * // in here as 'err', and execution will stop. + * } + * ); + */ + function forever(fn, errback) { + var done = onlyOnce(errback); + var task = wrapAsync(ensureAsync(fn)); -var Transform = __nccwpck_require__(95401); + function next(err) { + if (err) return done(err); + if (err === false) return; + task(next); + } + return next(); + } + var forever$1 = awaitify(forever, 2); -/**/ -var util = Object.create(__nccwpck_require__(95898)); -util.inherits = __nccwpck_require__(44124); -/**/ + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. + * + * @name groupByLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupByLimit(coll, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(coll, limit, (val, iterCb) => { + _iteratee(val, (err, key) => { + if (err) return iterCb(err); + return iterCb(err, {key, val}); + }); + }, (err, mapResults) => { + var result = {}; + // from MDN, handle object having an `hasOwnProperty` prop + var {hasOwnProperty} = Object.prototype; -util.inherits(PassThrough, Transform); + for (var i = 0; i < mapResults.length; i++) { + if (mapResults[i]) { + var {key} = mapResults[i]; + var {val} = mapResults[i]; -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); + if (hasOwnProperty.call(result, key)) { + result[key].push(val); + } else { + result[key] = [val]; + } + } + } - Transform.call(this, options); -} + return callback(err, result); + }); + } -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; + var groupByLimit$1 = awaitify(groupByLimit, 4); -/***/ }), + /** + * Returns a new object, where each value corresponds to an array of items, from + * `coll`, that returned the corresponding key. That is, the keys of the object + * correspond to the values passed to the `iteratee` callback. + * + * Note: Since this function applies the `iteratee` to each item in parallel, + * there is no guarantee that the `iteratee` functions will complete in order. + * However, the values for each key in the `result` will be in the same order as + * the original `coll`. For Objects, the values will roughly be in the order of + * the original Objects' keys (but this can vary across JavaScript engines). + * + * @name groupBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whoses + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * const files = ['dir1/file1.txt','dir2','dir4'] + * + * // asynchronous function that detects file type as none, file, or directory + * function detectFile(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(null, 'none'); + * } + * callback(null, stat.isDirectory() ? 'directory' : 'file'); + * }); + * } + * + * //Using callbacks + * async.groupBy(files, detectFile, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * }); + * + * // Using Promises + * async.groupBy(files, detectFile) + * .then( result => { + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.groupBy(files, detectFile); + * console.log(result); + * // { + * // file: [ 'dir1/file1.txt' ], + * // none: [ 'dir4' ], + * // directory: [ 'dir2'] + * // } + * // result is object containing the files grouped by type + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function groupBy (coll, iteratee, callback) { + return groupByLimit$1(coll, Infinity, iteratee, callback) + } -/***/ 19647: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. + * + * @name groupBySeries + * @static + * @memberOf module:Collections + * @method + * @see [async.groupBy]{@link module:Collections.groupBy} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a `key` to group the value under. + * Invoked with (value, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. Result is an `Object` whose + * properties are arrays of values which returned the corresponding key. + * @returns {Promise} a promise, if no callback is passed + */ + function groupBySeries (coll, iteratee, callback) { + return groupByLimit$1(coll, 1, iteratee, callback) + } -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + /** + * Logs the result of an `async` function to the `console`. Only works in + * Node.js or in browsers that support `console.log` and `console.error` (such + * as FF and Chrome). If multiple arguments are returned from the async + * function, `console.log` is called on each argument in order. + * + * @name log + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} function - The function you want to eventually apply + * all arguments to. + * @param {...*} arguments... - Any number of arguments to apply to the function. + * @example + * + * // in a module + * var hello = function(name, callback) { + * setTimeout(function() { + * callback(null, 'hello ' + name); + * }, 1000); + * }; + * + * // in the node repl + * node> async.log(hello, 'world'); + * 'hello world' + */ + var log = consoleFunc('log'); + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a + * time. + * + * @name mapValuesLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesLimit(obj, limit, iteratee, callback) { + callback = once(callback); + var newObj = {}; + var _iteratee = wrapAsync(iteratee); + return eachOfLimit$2(limit)(obj, (val, key, next) => { + _iteratee(val, key, (err, result) => { + if (err) return next(err); + newObj[key] = result; + next(err); + }); + }, err => callback(err, newObj)); + } + var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); -/**/ + /** + * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. + * + * Produces a new Object by mapping each value of `obj` through the `iteratee` + * function. The `iteratee` is called each `value` and `key` from `obj` and a + * callback for when it has finished processing. Each of these callbacks takes + * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` + * passes an error to its callback, the main `callback` (for the `mapValues` + * function) is immediately called with the error. + * + * Note, the order of the keys in the result is not guaranteed. The keys will + * be roughly in the order they complete, (but this is very engine-specific) + * + * @name mapValues + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * // file4.txt does not exist + * + * const fileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file3.txt' + * }; + * + * const withMissingFileMap = { + * f1: 'file1.txt', + * f2: 'file2.txt', + * f3: 'file4.txt' + * }; + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, key, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * } else { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * }); + * + * // Error handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(result); + * } + * }); + * + * // Using Promises + * async.mapValues(fileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * }).catch (err => { + * console.log(err); + * }); + * + * // Error Handling + * async.mapValues(withMissingFileMap, getFileSizeInBytes) + * .then( result => { + * console.log(result); + * }).catch (err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.mapValues(fileMap, getFileSizeInBytes); + * console.log(result); + * // result is now a map of file size in bytes for each file, e.g. + * // { + * // f1: 1000, + * // f2: 2000, + * // f3: 3000 + * // } + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // Error Handling + * async () => { + * try { + * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); + * console.log(result); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function mapValues(obj, iteratee, callback) { + return mapValuesLimit$1(obj, Infinity, iteratee, callback) + } -var pna = __nccwpck_require__(47810); -/**/ + /** + * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. + * + * @name mapValuesSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.mapValues]{@link module:Collections.mapValues} + * @category Collection + * @param {Object} obj - A collection to iterate over. + * @param {AsyncFunction} iteratee - A function to apply to each value and key + * in `coll`. + * The iteratee should complete with the transformed value as its result. + * Invoked with (value, key, callback). + * @param {Function} [callback] - A callback which is called when all `iteratee` + * functions have finished, or an error occurs. `result` is a new object consisting + * of each key from `obj`, with each transformed value on the right-hand side. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function mapValuesSeries(obj, iteratee, callback) { + return mapValuesLimit$1(obj, 1, iteratee, callback) + } -module.exports = Readable; + /** + * Caches the results of an async function. When creating a hash to store + * function results against, the callback is omitted from the hash and an + * optional hash function can be used. + * + * **Note: if the async function errs, the result will not be cached and + * subsequent calls will call the wrapped function.** + * + * If no hash function is specified, the first argument is used as a hash key, + * which may work reasonably if it is a string or a data type that converts to a + * distinct string. Note that objects and arrays will not behave reasonably. + * Neither will cases where the other arguments are significant. In such cases, + * specify your own hash function. + * + * The cache of results is exposed as the `memo` property of the function + * returned by `memoize`. + * + * @name memoize + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function to proxy and cache results from. + * @param {Function} hasher - An optional function for generating a custom hash + * for storing results. It has all the arguments applied to it apart from the + * callback, and must be synchronous. + * @returns {AsyncFunction} a memoized version of `fn` + * @example + * + * var slow_fn = function(name, callback) { + * // do something + * callback(null, result); + * }; + * var fn = async.memoize(slow_fn); + * + * // fn can now be used as if it were slow_fn + * fn('some name', function() { + * // callback + * }); + */ + function memoize(fn, hasher = v => v) { + var memo = Object.create(null); + var queues = Object.create(null); + var _fn = wrapAsync(fn); + var memoized = initialParams((args, callback) => { + var key = hasher(...args); + if (key in memo) { + setImmediate$1(() => callback(null, ...memo[key])); + } else if (key in queues) { + queues[key].push(callback); + } else { + queues[key] = [callback]; + _fn(...args, (err, ...resultArgs) => { + // #1465 don't memoize if an error occurred + if (!err) { + memo[key] = resultArgs; + } + var q = queues[key]; + delete queues[key]; + for (var i = 0, l = q.length; i < l; i++) { + q[i](err, ...resultArgs); + } + }); + } + }); + memoized.memo = memo; + memoized.unmemoized = fn; + return memoized; + } -/**/ -var isArray = __nccwpck_require__(20893); -/**/ + /* istanbul ignore file */ -/**/ -var Duplex; -/**/ + /** + * Calls `callback` on a later loop around the event loop. In Node.js this just + * calls `process.nextTick`. In the browser it will use `setImmediate` if + * available, otherwise `setTimeout(callback, 0)`, which means other higher + * priority events may precede the execution of `callback`. + * + * This is used internally for browser-compatibility purposes. + * + * @name nextTick + * @static + * @memberOf module:Utils + * @method + * @see [async.setImmediate]{@link module:Utils.setImmediate} + * @category Util + * @param {Function} callback - The function to call on a later loop around + * the event loop. Invoked with (args...). + * @param {...*} args... - any number of additional arguments to pass to the + * callback on the next tick. + * @example + * + * var call_order = []; + * async.nextTick(function() { + * call_order.push('two'); + * // call_order now equals ['one','two'] + * }); + * call_order.push('one'); + * + * async.setImmediate(function (a, b, c) { + * // a, b, and c equal 1, 2, and 3 + * }, 1, 2, 3); + */ + var _defer; -Readable.ReadableState = ReadableState; + if (hasNextTick) { + _defer = process.nextTick; + } else if (hasSetImmediate) { + _defer = setImmediate; + } else { + _defer = fallback; + } -/**/ -var EE = (__nccwpck_require__(82361).EventEmitter); + var nextTick = wrap(_defer); -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ + var _parallel = awaitify((eachfn, tasks, callback) => { + var results = isArrayLike(tasks) ? [] : {}; -/**/ -var Stream = __nccwpck_require__(41715); -/**/ + eachfn(tasks, (task, key, taskCb) => { + wrapAsync(task)((err, ...result) => { + if (result.length < 2) { + [result] = result; + } + results[key] = result; + taskCb(err); + }); + }, err => callback(err, results)); + }, 3); -/**/ + /** + * Run the `tasks` collection of functions in parallel, without waiting until + * the previous function has completed. If any of the functions pass an error to + * its callback, the main `callback` is immediately called with the value of the + * error. Once the `tasks` have completed, the results are passed to the final + * `callback` as an array. + * + * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about + * parallel execution of code. If your tasks do not use any timers or perform + * any I/O, they will actually be executed in series. Any synchronous setup + * sections for each task will happen one after the other. JavaScript remains + * single-threaded. + * + * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the + * execution of other tasks when a task fails. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.parallel}. + * + * @name parallel + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * + * //Using Callbacks + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.parallel([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] even though + * // the second function had a shorter timeout. + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function parallel(tasks, callback) { + return _parallel(eachOf$1, tasks, callback); + } -var Buffer = (__nccwpck_require__(36476).Buffer); -var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} + /** + * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a + * time. + * + * @name parallelLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.parallel]{@link module:ControlFlow.parallel} + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of + * [async functions]{@link AsyncFunction} to run. + * Each async function can complete with any number of optional `result` values. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed successfully. This function gets a results array + * (or object) containing all the result arguments passed to the task callbacks. + * Invoked with (err, results). + * @returns {Promise} a promise, if a callback is not passed + */ + function parallelLimit(tasks, limit, callback) { + return _parallel(eachOfLimit$2(limit), tasks, callback); + } -/**/ + /** + * A queue of tasks for the worker function to complete. + * @typedef {Iterable} QueueObject + * @memberOf module:ControlFlow + * @property {Function} length - a function returning the number of items + * waiting to be processed. Invoke with `queue.length()`. + * @property {boolean} started - a boolean indicating whether or not any + * items have been pushed and processed by the queue. + * @property {Function} running - a function returning the number of items + * currently being processed. Invoke with `queue.running()`. + * @property {Function} workersList - a function returning the array of items + * currently being processed. Invoke with `queue.workersList()`. + * @property {Function} idle - a function returning false if there are items + * waiting or being processed, or true if not. Invoke with `queue.idle()`. + * @property {number} concurrency - an integer for determining how many `worker` + * functions should be run in parallel. This property can be changed after a + * `queue` is created to alter the concurrency on-the-fly. + * @property {number} payload - an integer that specifies how many items are + * passed to the worker function at a time. only applies if this is a + * [cargo]{@link module:ControlFlow.cargo} object + * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` + * once the `worker` has finished processing the task. Instead of a single task, + * a `tasks` array can be submitted. The respective callback is used for every + * task in the list. Invoke with `queue.push(task, [callback])`, + * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. + * Invoke with `queue.unshift(task, [callback])`. + * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns + * a promise that rejects if an error occurs. + * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns + * a promise that rejects if an error occurs. + * @property {Function} remove - remove items from the queue that match a test + * function. The test function will be passed an object with a `data` property, + * and a `priority` property, if this is a + * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. + * Invoked with `queue.remove(testFn)`, where `testFn` is of the form + * `function ({data, priority}) {}` and returns a Boolean. + * @property {Function} saturated - a function that sets a callback that is + * called when the number of running workers hits the `concurrency` limit, and + * further tasks will be queued. If the callback is omitted, `q.saturated()` + * returns a promise for the next occurrence. + * @property {Function} unsaturated - a function that sets a callback that is + * called when the number of running workers is less than the `concurrency` & + * `buffer` limits, and further tasks will not be queued. If the callback is + * omitted, `q.unsaturated()` returns a promise for the next occurrence. + * @property {number} buffer - A minimum threshold buffer in order to say that + * the `queue` is `unsaturated`. + * @property {Function} empty - a function that sets a callback that is called + * when the last item from the `queue` is given to a `worker`. If the callback + * is omitted, `q.empty()` returns a promise for the next occurrence. + * @property {Function} drain - a function that sets a callback that is called + * when the last item from the `queue` has returned from the `worker`. If the + * callback is omitted, `q.drain()` returns a promise for the next occurrence. + * @property {Function} error - a function that sets a callback that is called + * when a task errors. Has the signature `function(error, task)`. If the + * callback is omitted, `error()` returns a promise that rejects on the next + * error. + * @property {boolean} paused - a boolean for determining whether the queue is + * in a paused state. + * @property {Function} pause - a function that pauses the processing of tasks + * until `resume()` is called. Invoke with `queue.pause()`. + * @property {Function} resume - a function that resumes the processing of + * queued tasks when the queue is paused. Invoke with `queue.resume()`. + * @property {Function} kill - a function that removes the `drain` callback and + * empties remaining tasks from the queue forcing it to go idle. No more tasks + * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. + * + * @example + * const q = async.queue(worker, 2) + * q.push(item1) + * q.push(item2) + * q.push(item3) + * // queues are iterable, spread into an array to inspect + * const items = [...q] // [item1, item2, item3] + * // or use for of + * for (let item of q) { + * console.log(item) + * } + * + * q.drain(() => { + * console.log('all done') + * }) + * // or + * await q.drain() + */ -/**/ -var util = Object.create(__nccwpck_require__(95898)); -util.inherits = __nccwpck_require__(44124); -/**/ + /** + * Creates a `queue` object with the specified `concurrency`. Tasks added to the + * `queue` are processed in parallel (up to the `concurrency` limit). If all + * `worker`s are in progress, the task is queued until one becomes available. + * Once a `worker` completes a `task`, that `task`'s callback is called. + * + * @name queue + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. Invoked with (task, callback). + * @param {number} [concurrency=1] - An `integer` for determining how many + * `worker` functions should be run in parallel. If omitted, the concurrency + * defaults to `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be + * attached as certain properties to listen for specific events during the + * lifecycle of the queue. + * @example + * + * // create a queue object with concurrency 2 + * var q = async.queue(function(task, callback) { + * console.log('hello ' + task.name); + * callback(); + * }, 2); + * + * // assign a callback + * q.drain(function() { + * console.log('all items have been processed'); + * }); + * // or await the end + * await q.drain() + * + * // assign an error callback + * q.error(function(err, task) { + * console.error('task experienced an error'); + * }); + * + * // add some items to the queue + * q.push({name: 'foo'}, function(err) { + * console.log('finished processing foo'); + * }); + * // callback is optional + * q.push({name: 'bar'}); + * + * // add some items to the queue (batch-wise) + * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { + * console.log('finished processing item'); + * }); + * + * // add some items to the front of the queue + * q.unshift({name: 'bar'}, function (err) { + * console.log('finished processing bar'); + * }); + */ + function queue (worker, concurrency) { + var _worker = wrapAsync(worker); + return queue$1((items, cb) => { + _worker(items[0], cb); + }, concurrency, 1); + } -/**/ -var debugUtil = __nccwpck_require__(73837); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; -} -/**/ - -var BufferList = __nccwpck_require__(37898); -var destroyImpl = __nccwpck_require__(71890); -var StringDecoder; + // Binary min-heap implementation used for priority queue. + // Implementation is stable, i.e. push time is considered for equal priorities + class Heap { + constructor() { + this.heap = []; + this.pushCount = Number.MIN_SAFE_INTEGER; + } -util.inherits(Readable, Stream); + get length() { + return this.heap.length; + } -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; + empty () { + this.heap = []; + return this; + } -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + percUp(index) { + let p; - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} + while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { + let t = this.heap[index]; + this.heap[index] = this.heap[p]; + this.heap[p] = t; -function ReadableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(5364); + index = p; + } + } - options = options || {}; + percDown(index) { + let l; - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; + while ((l=leftChi(index)) < this.heap.length) { + if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { + l = l+1; + } - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; + if (smaller(this.heap[index], this.heap[l])) { + break; + } - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + let t = this.heap[index]; + this.heap[index] = this.heap[l]; + this.heap[l] = t; - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var readableHwm = options.readableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; + index = l; + } + } - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; + push(node) { + node.pushCount = ++this.pushCount; + this.heap.push(node); + this.percUp(this.heap.length-1); + } - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); + unshift(node) { + return this.heap.push(node); + } - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; + shift() { + let [top] = this.heap; - // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - this.sync = true; + this.heap[0] = this.heap[this.heap.length-1]; + this.heap.pop(); + this.percDown(0); - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; + return top; + } - // has it been destroyed - this.destroyed = false; + toArray() { + return [...this]; + } - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + *[Symbol.iterator] () { + for (let i = 0; i < this.heap.length; i++) { + yield this.heap[i].data; + } + } - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; + remove (testFn) { + let j = 0; + for (let i = 0; i < this.heap.length; i++) { + if (!testFn(this.heap[i])) { + this.heap[j] = this.heap[i]; + j++; + } + } - // if true, a maybeReadMore has been scheduled - this.readingMore = false; + this.heap.splice(j); - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(99708)/* .StringDecoder */ .s); - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} + for (let i = parent(this.heap.length-1); i >= 0; i--) { + this.percDown(i); + } -function Readable(options) { - Duplex = Duplex || __nccwpck_require__(5364); + return this; + } + } - if (!(this instanceof Readable)) return new Readable(options); + function leftChi(i) { + return (i<<1)+1; + } - this._readableState = new ReadableState(options, this); + function parent(i) { + return ((i+1)>>1)-1; + } - // legacy - this.readable = true; + function smaller(x, y) { + if (x.priority !== y.priority) { + return x.priority < y.priority; + } + else { + return x.pushCount < y.pushCount; + } + } - if (options) { - if (typeof options.read === 'function') this._read = options.read; + /** + * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and + * completed in ascending priority order. + * + * @name priorityQueue + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.queue]{@link module:ControlFlow.queue} + * @category Control Flow + * @param {AsyncFunction} worker - An async function for processing a queued task. + * If you want to handle errors from an individual task, pass a callback to + * `q.push()`. + * Invoked with (task, callback). + * @param {number} concurrency - An `integer` for determining how many `worker` + * functions should be run in parallel. If omitted, the concurrency defaults to + * `1`. If the concurrency is `0`, an error is thrown. + * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three + * differences between `queue` and `priorityQueue` objects: + * * `push(task, priority, [callback])` - `priority` should be a number. If an + * array of `tasks` is given, all tasks will be assigned the same priority. + * * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`, + * except this returns a promise that rejects if an error occurs. + * * The `unshift` and `unshiftAsync` methods were removed. + */ + function priorityQueue(worker, concurrency) { + // Start with a normal queue + var q = queue(worker, concurrency); - if (typeof options.destroy === 'function') this._destroy = options.destroy; - } + var { + push, + pushAsync + } = q; - Stream.call(this); -} + q._tasks = new Heap(); + q._createTaskItem = ({data, priority}, callback) => { + return { + data, + priority, + callback + }; + }; -Object.defineProperty(Readable.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined) { - return false; - } - return this._readableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } + function createDataItems(tasks, priority) { + if (!Array.isArray(tasks)) { + return {data: tasks, priority}; + } + return tasks.map(data => { return {data, priority}; }); + } - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - } -}); + // Override push to accept second parameter representing priority + q.push = function(data, priority = 0, callback) { + return push(createDataItems(data, priority), callback); + }; -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { - this.push(null); - cb(err); -}; + q.pushAsync = function(data, priority = 0, callback) { + return pushAsync(createDataItems(data, priority), callback); + }; -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; + // Remove unshift functions + delete q.unshift; + delete q.unshiftAsync; - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - skipChunkCheck = true; + return q; } - } else { - skipChunkCheck = true; - } - - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; - -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; - -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } - if (addToFront) { - if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); - } else if (state.ended) { - stream.emit('error', new Error('stream.push() after EOF')); - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); + /** + * Runs the `tasks` array of functions in parallel, without waiting until the + * previous function has completed. Once any of the `tasks` complete or pass an + * error to its callback, the main `callback` is immediately called. It's + * equivalent to `Promise.race()`. + * + * @name race + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} + * to run. Each function can complete with an optional `result` value. + * @param {Function} callback - A callback to run once any of the functions have + * completed. This function gets an error or result from the first function that + * completed. Invoked with (err, result). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.race([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ], + * // main callback + * function(err, result) { + * // the result will be equal to 'two' as it finishes earlier + * }); + */ + function race(tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); + if (!tasks.length) return callback(); + for (var i = 0, l = tasks.length; i < l; i++) { + wrapAsync(tasks[i])(callback); } - } - } else if (!addToFront) { - state.reading = false; } - } - - return needMoreData(state); -} - -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - if (state.needReadable) emitReadable(stream); - } - maybeReadMore(stream, state); -} - -function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} - -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); -} + var race$1 = awaitify(race, 2); -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; + /** + * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. + * + * @name reduceRight + * @static + * @memberOf module:Collections + * @method + * @see [async.reduce]{@link module:Collections.reduce} + * @alias foldr + * @category Collection + * @param {Array} array - A collection to iterate over. + * @param {*} memo - The initial state of the reduction. + * @param {AsyncFunction} iteratee - A function applied to each item in the + * array to produce the next step in the reduction. + * The `iteratee` should complete with the next state of the reduction. + * If the iteratee completes with an error, the reduction is stopped and the + * main `callback` is immediately called with the error. + * Invoked with (memo, item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the reduced value. Invoked with + * (err, result). + * @returns {Promise} a promise, if no callback is passed + */ + function reduceRight (array, memo, iteratee, callback) { + var reversed = [...array].reverse(); + return reduce$1(reversed, memo, iteratee, callback); + } -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(99708)/* .StringDecoder */ .s); - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; + /** + * Wraps the async function in another function that always completes with a + * result object, even when it errors. + * + * The result object has either the property `error` or `value`. + * + * @name reflect + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} fn - The async function you want to wrap + * @returns {Function} - A function that always passes null to it's callback as + * the error. The second argument to the callback will be an `object` with + * either an `error` or a `value` property. + * @example + * + * async.parallel([ + * async.reflect(function(callback) { + * // do some stuff ... + * callback(null, 'one'); + * }), + * async.reflect(function(callback) { + * // do some more stuff but error ... + * callback('bad stuff happened'); + * }), + * async.reflect(function(callback) { + * // do some more stuff ... + * callback(null, 'two'); + * }) + * ], + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = 'bad stuff happened' + * // results[2].value = 'two' + * }); + */ + function reflect(fn) { + var _fn = wrapAsync(fn); + return initialParams(function reflectOn(args, reflectCallback) { + args.push((error, ...cbArgs) => { + let retVal = {}; + if (error) { + retVal.error = error; + } + if (cbArgs.length > 0){ + var value = cbArgs; + if (cbArgs.length <= 1) { + [value] = cbArgs; + } + retVal.value = value; + } + reflectCallback(null, retVal); + }); -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; -} + return _fn.apply(this, args); + }); + } -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; -} - -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; + /** + * A helper function that wraps an array or an object of functions with `reflect`. + * + * @name reflectAll + * @static + * @memberOf module:Utils + * @method + * @see [async.reflect]{@link module:Utils.reflect} + * @category Util + * @param {Array|Object|Iterable} tasks - The collection of + * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. + * @returns {Array} Returns an array of async functions, each wrapped in + * `async.reflect` + * @example + * + * let tasks = [ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * // do some more stuff but error ... + * callback(new Error('bad stuff happened')); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results[0].value = 'one' + * // results[1].error = Error('bad stuff happened') + * // results[2].value = 'two' + * }); + * + * // an example using an object instead of an array + * let tasks = { + * one: function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * two: function(callback) { + * callback('two'); + * }, + * three: function(callback) { + * setTimeout(function() { + * callback(null, 'three'); + * }, 100); + * } + * }; + * + * async.parallel(async.reflectAll(tasks), + * // optional callback + * function(err, results) { + * // values + * // results.one.value = 'one' + * // results.two.error = 'two' + * // results.three.value = 'three' + * }); + */ + function reflectAll(tasks) { + var results; + if (Array.isArray(tasks)) { + results = tasks.map(reflect); + } else { + results = {}; + Object.keys(tasks).forEach(key => { + results[key] = reflect.call(this, tasks[key]); + }); + } + return results; + } - if (n !== 0) state.emittedReadable = false; + function reject$2(eachfn, arr, _iteratee, callback) { + const iteratee = wrapAsync(_iteratee); + return _filter(eachfn, arr, (value, cb) => { + iteratee(value, (err, v) => { + cb(err, !v); + }); + }, callback); + } - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } + /** + * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. + * + * @name reject + * @static + * @memberOf module:Collections + * @method + * @see [async.filter]{@link module:Collections.filter} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * + * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.reject(fileList, fileExists, function(err, results) { + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }); + * + * // Using Promises + * async.reject(fileList, fileExists) + * .then( results => { + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let results = await async.reject(fileList, fileExists); + * console.log(results); + * // [ 'dir3/file6.txt' ] + * // results now equals an array of the non-existing files + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function reject (coll, iteratee, callback) { + return reject$2(eachOf$1, coll, iteratee, callback) + } + var reject$1 = awaitify(reject, 3); - n = howMuchToRead(n, state); + /** + * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a + * time. + * + * @name rejectLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectLimit (coll, limit, iteratee, callback) { + return reject$2(eachOfLimit$2(limit), coll, iteratee, callback) + } + var rejectLimit$1 = awaitify(rejectLimit, 4); - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } + /** + * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. + * + * @name rejectSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.reject]{@link module:Collections.reject} + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {Function} iteratee - An async truth test to apply to each item in + * `coll`. + * The should complete with a boolean value as its `result`. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Invoked with (err, results). + * @returns {Promise} a promise, if no callback is passed + */ + function rejectSeries (coll, iteratee, callback) { + return reject$2(eachOfSeries$1, coll, iteratee, callback) + } + var rejectSeries$1 = awaitify(rejectSeries, 3); - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. + function constant(value) { + return function () { + return value; + } + } - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); + /** + * Attempts to get a successful response from `task` no more than `times` times + * before returning an error. If the task is successful, the `callback` will be + * passed the result of the successful task. If all attempts fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name retry + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @see [async.retryable]{@link module:ControlFlow.retryable} + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an + * object with `times` and `interval` or a number. + * * `times` - The number of attempts to make before giving up. The default + * is `5`. + * * `interval` - The time to wait between retries, in milliseconds. The + * default is `0`. The interval may also be specified as a function of the + * retry count (see example). + * * `errorFilter` - An optional synchronous function that is invoked on + * erroneous result. If it returns `true` the retry attempts will continue; + * if the function returns `false` the retry flow is aborted with the current + * attempt's error and result being returned to the final callback. + * Invoked with (err). + * * If `opts` is a number, the number specifies the number of times to retry, + * with the default interval of `0`. + * @param {AsyncFunction} task - An async function to retry. + * Invoked with (callback). + * @param {Function} [callback] - An optional callback which is called when the + * task has succeeded, or after the final failed attempt. It receives the `err` + * and `result` arguments of the last attempt at completing the `task`. Invoked + * with (err, results). + * @returns {Promise} a promise if no callback provided + * + * @example + * + * // The `retry` function can be used as a stand-alone control flow by passing + * // a callback, as shown below: + * + * // try calling apiMethod 3 times + * async.retry(3, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 3 times, waiting 200 ms between each retry + * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod 10 times with exponential backoff + * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) + * async.retry({ + * times: 10, + * interval: function(retryCount) { + * return 50 * Math.pow(2, retryCount); + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod the default 5 times no delay between each retry + * async.retry(apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // try calling apiMethod only when error condition satisfies, all other + * // errors will abort the retry control flow and return to final callback + * async.retry({ + * errorFilter: function(err) { + * return err.message === 'Temporary error'; // only retry on a specific error + * } + * }, apiMethod, function(err, result) { + * // do something with the result + * }); + * + * // to retry individual methods that are not as reliable within other + * // control flow functions, use the `retryable` wrapper: + * async.auto({ + * users: api.getUsers.bind(api), + * payments: async.retryable(3, api.getPayments.bind(api)) + * }, function(err, results) { + * // do something with the results + * }); + * + */ + const DEFAULT_TIMES = 5; + const DEFAULT_INTERVAL = 0; - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } + function retry(opts, task, callback) { + var options = { + times: DEFAULT_TIMES, + intervalFunc: constant(DEFAULT_INTERVAL) + }; - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } + if (arguments.length < 3 && typeof opts === 'function') { + callback = task || promiseCallback(); + task = opts; + } else { + parseTimes(options, opts); + callback = callback || promiseCallback(); + } - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; + if (typeof task !== 'function') { + throw new Error("Invalid arguments for async.retry"); + } - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } + var _task = wrapAsync(task); - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; + var attempt = 1; + function retryAttempt() { + _task((err, ...args) => { + if (err === false) return + if (err && attempt++ < options.times && + (typeof options.errorFilter != 'function' || + options.errorFilter(err))) { + setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); + } else { + callback(err, ...args); + } + }); + } - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } + retryAttempt(); + return callback[PROMISE_SYMBOL] + } - if (ret !== null) this.emit('data', ret); + function parseTimes(acc, t) { + if (typeof t === 'object') { + acc.times = +t.times || DEFAULT_TIMES; - return ret; -}; + acc.intervalFunc = typeof t.interval === 'function' ? + t.interval : + constant(+t.interval || DEFAULT_INTERVAL); -function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; + acc.errorFilter = t.errorFilter; + } else if (typeof t === 'number' || typeof t === 'string') { + acc.times = +t || DEFAULT_TIMES; + } else { + throw new Error("Invalid arguments for async.retry"); + } } - } - state.ended = true; - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); -} + /** + * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method + * wraps a task and makes it retryable, rather than immediately calling it + * with retries. + * + * @name retryable + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.retry]{@link module:ControlFlow.retry} + * @category Control Flow + * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional + * options, exactly the same as from `retry`, except for a `opts.arity` that + * is the arity of the `task` function, defaulting to `task.length` + * @param {AsyncFunction} task - the asynchronous function to wrap. + * This function will be passed any arguments passed to the returned wrapper. + * Invoked with (...args, callback). + * @returns {AsyncFunction} The wrapped function, which when invoked, will + * retry on an error, based on the parameters specified in `opts`. + * This function will accept the same parameters as `task`. + * @example + * + * async.auto({ + * dep1: async.retryable(3, getFromFlakyService), + * process: ["dep1", async.retryable(3, function (results, cb) { + * maybeProcessData(results.dep1, cb); + * })] + * }, callback); + */ + function retryable (opts, task) { + if (!task) { + task = opts; + opts = null; + } + let arity = (opts && opts.arity) || task.length; + if (isAsync(task)) { + arity += 1; + } + var _task = wrapAsync(task); + return initialParams((args, callback) => { + if (args.length < arity - 1 || callback == null) { + args.push(callback); + callback = promiseCallback(); + } + function taskFn(cb) { + _task(...args, cb); + } -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); - } -} + if (opts) retry(opts, taskFn, callback); + else retry(taskFn, callback); -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} - -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - pna.nextTick(maybeReadMore_, stream, state); - } -} - -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; -} - -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); -}; - -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; - - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); - - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; - - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); - - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } + return callback[PROMISE_SYMBOL] + }); } - } - - function onend() { - debug('onend'); - dest.end(); - } - - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); - - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); - - cleanedUp = true; - - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); + /** + * Run the functions in the `tasks` collection in series, each one running once + * the previous function has completed. If any functions in the series pass an + * error to its callback, no more functions are run, and `callback` is + * immediately called with the value of the error. Otherwise, `callback` + * receives an array of results when `tasks` have completed. + * + * It is also possible to use an object instead of an array. Each property will + * be run as a function, and the results will be passed to the final `callback` + * as an object instead of an array. This can be a more readable way of handling + * results from {@link async.series}. + * + * **Note** that while many implementations preserve the order of object + * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) + * explicitly states that + * + * > The mechanics and order of enumerating the properties is not specified. + * + * So if you rely on the order in which your series of functions are executed, + * and want this to work on all platforms, consider using an array. + * + * @name series + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing + * [async functions]{@link AsyncFunction} to run in series. + * Each function can complete with any number of optional `result` values. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This function gets a results array (or object) + * containing all the result arguments passed to the `task` callbacks. Invoked + * with (err, result). + * @return {Promise} a promise, if no callback is passed + * @example + * + * //Using Callbacks + * async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ], function(err, results) { + * console.log(results); + * // results is equal to ['one','two'] + * }); + * + * // an example using objects instead of arrays + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }, function(err, results) { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }); + * + * //Using Promises + * async.series([ + * function(callback) { + * setTimeout(function() { + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * callback(null, 'two'); + * }, 100); + * } + * ]).then(results => { + * console.log(results); + * // results is equal to ['one','two'] + * }).catch(err => { + * console.log(err); + * }); + * + * // an example using an object instead of an array + * async.series({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }).then(results => { + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * }).catch(err => { + * console.log(err); + * }); + * + * //Using async/await + * async () => { + * try { + * let results = await async.series([ + * function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 'one'); + * }, 200); + * }, + * function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 'two'); + * }, 100); + * } + * ]); + * console.log(results); + * // results is equal to ['one','two'] + * } + * catch (err) { + * console.log(err); + * } + * } + * + * // an example using an object instead of an array + * async () => { + * try { + * let results = await async.parallel({ + * one: function(callback) { + * setTimeout(function() { + * // do some async task + * callback(null, 1); + * }, 200); + * }, + * two: function(callback) { + * setTimeout(function() { + * // then do another async task + * callback(null, 2); + * }, 100); + * } + * }); + * console.log(results); + * // results is equal to: { one: 1, two: 2 } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function series(tasks, callback) { + return _parallel(eachOfSeries$1, tasks, callback); } - } - - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); - } - - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); - - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); - - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } - - // tell the dest that it's being piped to - dest.emit('pipe', src); - - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - - return dest; -}; -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); + /** + * Returns `true` if at least one element in the `coll` satisfies an async test. + * If any iteratee call returns `true`, the main `callback` is immediately + * called. + * + * @name some + * @static + * @memberOf module:Collections + * @method + * @alias any + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // dir1 is a directory that contains file1.txt, file2.txt + * // dir2 is a directory that contains file3.txt, file4.txt + * // dir3 is a directory that contains file5.txt + * // dir4 does not exist + * + * // asynchronous function that checks if a file exists + * function fileExists(file, callback) { + * fs.access(file, fs.constants.F_OK, (err) => { + * callback(null, !err); + * }); + * } + * + * // Using callbacks + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + *); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, + * function(err, result) { + * console.log(result); + * // false + * // result is false since none of the files exists + * } + *); + * + * // Using Promises + * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) + * .then( result => { + * console.log(result); + * // true + * // result is true since some file in the list exists + * }).catch( err => { + * console.log(err); + * }); + * + * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) + * .then( result => { + * console.log(result); + * // false + * // result is false since none of the files exists + * }).catch( err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); + * console.log(result); + * // true + * // result is true since some file in the list exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + * async () => { + * try { + * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); + * console.log(result); + * // false + * // result is false since none of the files exists + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function some(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) } - }; -} - -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { hasUnpiped: false }; - - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; + var some$1 = awaitify(some, 3); - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; + /** + * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. + * + * @name someLimit + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anyLimit + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in parallel. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someLimit(coll, limit, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfLimit$2(limit), coll, iteratee, callback) + } + var someLimit$1 = awaitify(someLimit, 4); - if (!dest) dest = state.pipes; + /** + * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. + * + * @name someSeries + * @static + * @memberOf module:Collections + * @method + * @see [async.some]{@link module:Collections.some} + * @alias anySeries + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async truth test to apply to each item + * in the collections in series. + * The iteratee should complete with a boolean `result` value. + * Invoked with (item, callback). + * @param {Function} [callback] - A callback which is called as soon as any + * iteratee returns `true`, or after all the iteratee functions have finished. + * Result will be either `true` or `false` depending on the values of the async + * tests. Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + */ + function someSeries(coll, iteratee, callback) { + return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) + } + var someSeries$1 = awaitify(someSeries, 3); - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } - - // slow case. multiple pipe destinations. - - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { hasUnpiped: false }); - }return this; - } - - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; - - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; - - dest.emit('unpipe', this, unpipeInfo); - - return this; -}; - -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); + /** + * Sorts a list by the results of running each `coll` value through an async + * `iteratee`. + * + * @name sortBy + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {AsyncFunction} iteratee - An async function to apply to each item in + * `coll`. + * The iteratee should complete with a value to use as the sort criteria as + * its `result`. + * Invoked with (item, callback). + * @param {Function} callback - A callback which is called after all the + * `iteratee` functions have finished, or an error occurs. Results is the items + * from the original `coll` sorted by the values returned by the `iteratee` + * calls. Invoked with (err, results). + * @returns {Promise} a promise, if no callback passed + * @example + * + * // bigfile.txt is a file that is 251100 bytes in size + * // mediumfile.txt is a file that is 11000 bytes in size + * // smallfile.txt is a file that is 121 bytes in size + * + * // asynchronous function that returns the file size in bytes + * function getFileSizeInBytes(file, callback) { + * fs.stat(file, function(err, stat) { + * if (err) { + * return callback(err); + * } + * callback(null, stat.size); + * }); + * } + * + * // Using callbacks + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // By modifying the callback parameter the + * // sorting order can be influenced: + * + * // ascending order + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) return callback(getFileSizeErr); + * callback(null, fileSize); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * } + * ); + * + * // descending order + * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { + * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { + * if (getFileSizeErr) { + * return callback(getFileSizeErr); + * } + * callback(null, fileSize * -1); + * }); + * }, function(err, results) { + * if (err) { + * console.log(err); + * } else { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] + * } + * } + * ); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, + * function(err, results) { + * if (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } else { + * console.log(results); + * } + * } + * ); + * + * // Using Promises + * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * }).catch( err => { + * console.log(err); + * }); + * + * // Error handling + * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) + * .then( results => { + * console.log(results); + * }).catch( err => { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * }); + * + * // Using async/await + * (async () => { + * try { + * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * // results is now the original array of files sorted by + * // file size (ascending by default), e.g. + * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * // Error handling + * async () => { + * try { + * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); + * console.log(results); + * } + * catch (err) { + * console.log(err); + * // [ Error: ENOENT: no such file or directory ] + * } + * } + * + */ + function sortBy (coll, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return map$1(coll, (x, iterCb) => { + _iteratee(x, (err, criteria) => { + if (err) return iterCb(err); + iterCb(err, {value: x, criteria}); + }); + }, (err, results) => { + if (err) return callback(err); + callback(null, results.sort(comparator).map(v => v.value)); + }); - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - pna.nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); - } + function comparator(left, right) { + var a = left.criteria, b = right.criteria; + return a < b ? -1 : a > b ? 1 : 0; + } } - } - - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; - -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} - -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; -}; - -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - pna.nextTick(resume_, stream, state); - } -} - -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } - - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} + var sortBy$1 = awaitify(sortBy, 3); -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; -}; + /** + * Sets a time limit on an asynchronous function. If the function does not call + * its callback within the specified milliseconds, it will be called with a + * timeout error. The code property for the error object will be `'ETIMEDOUT'`. + * + * @name timeout + * @static + * @memberOf module:Utils + * @method + * @category Util + * @param {AsyncFunction} asyncFn - The async function to limit in time. + * @param {number} milliseconds - The specified time limit. + * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) + * to timeout Error for more information.. + * @returns {AsyncFunction} Returns a wrapped function that can be used with any + * of the control flow functions. + * Invoke this function with the same parameters as you would `asyncFunc`. + * @example + * + * function myFunction(foo, callback) { + * doAsyncTask(foo, function(err, data) { + * // handle errors + * if (err) return callback(err); + * + * // do some stuff ... + * + * // return processed data + * return callback(null, data); + * }); + * } + * + * var wrapped = async.timeout(myFunction, 1000); + * + * // call `wrapped` as you would `myFunction` + * wrapped({ bar: 'bar' }, function(err, data) { + * // if `myFunction` takes < 1000 ms to execute, `err` + * // and `data` will have their expected values + * + * // else `err` will be an Error with the code 'ETIMEDOUT' + * }); + */ + function timeout(asyncFn, milliseconds, info) { + var fn = wrapAsync(asyncFn); -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} -} + return initialParams((args, callback) => { + var timedOut = false; + var timer; -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var _this = this; + function timeoutCallback() { + var name = asyncFn.name || 'anonymous'; + var error = new Error('Callback function "' + name + '" timed out.'); + error.code = 'ETIMEDOUT'; + if (info) { + error.info = info; + } + timedOut = true; + callback(error); + } - var state = this._readableState; - var paused = false; + args.push((...cbArgs) => { + if (!timedOut) { + callback(...cbArgs); + clearTimeout(timer); + } + }); - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); + // setup timer and call original function + timer = setTimeout(timeoutCallback, milliseconds); + fn(...args); + }); } - _this.push(null); - }); - - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); - - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; - - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); + function range(size) { + var result = Array(size); + while (size--) { + result[size] = size; + } + return result; } - }); - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); + /** + * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a + * time. + * + * @name timesLimit + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} count - The number of times to run the function. + * @param {number} limit - The maximum number of async operations at a time. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see [async.map]{@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesLimit(count, limit, iteratee, callback) { + var _iteratee = wrapAsync(iteratee); + return mapLimit$1(range(count), limit, _iteratee, callback); } - } - - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } - // when we try to consume some more bytes, simply unpause the - // underlying stream. - this._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); + /** + * Calls the `iteratee` function `n` times, and accumulates results in the same + * manner you would use with [map]{@link module:Collections.map}. + * + * @name times + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.map]{@link module:Collections.map} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + * @example + * + * // Pretend this is some complicated async factory + * var createUser = function(id, callback) { + * callback(null, { + * id: 'user' + id + * }); + * }; + * + * // generate 5 users + * async.times(5, function(n, next) { + * createUser(n, function(err, user) { + * next(err, user); + * }); + * }, function(err, users) { + * // we should now have 5 users + * }); + */ + function times (n, iteratee, callback) { + return timesLimit(n, Infinity, iteratee, callback) } - }; - - return this; -}; - -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._readableState.highWaterMark; - } -}); - -// exposed for testing purposes only. -Readable._fromList = fromList; - -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; - - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } - return ret; -} + /** + * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. + * + * @name timesSeries + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.times]{@link module:ControlFlow.times} + * @category Control Flow + * @param {number} n - The number of times to run the function. + * @param {AsyncFunction} iteratee - The async function to call `n` times. + * Invoked with the iteration index and a callback: (n, next). + * @param {Function} callback - see {@link module:Collections.map}. + * @returns {Promise} a promise, if no callback is provided + */ + function timesSeries (n, iteratee, callback) { + return timesLimit(n, 1, iteratee, callback) + } -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} + /** + * A relative of `reduce`. Takes an Object or Array, and iterates over each + * element in parallel, each step potentially mutating an `accumulator` value. + * The type of the accumulator defaults to the type of collection passed in. + * + * @name transform + * @static + * @memberOf module:Collections + * @method + * @category Collection + * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. + * @param {*} [accumulator] - The initial state of the transform. If omitted, + * it will default to an empty Object or Array, depending on the type of `coll` + * @param {AsyncFunction} iteratee - A function applied to each item in the + * collection that potentially modifies the accumulator. + * Invoked with (accumulator, item, key, callback). + * @param {Function} [callback] - A callback which is called after all the + * `iteratee` functions have finished. Result is the transformed accumulator. + * Invoked with (err, result). + * @returns {Promise} a promise, if no callback provided + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileList = ['file1.txt','file2.txt','file3.txt']; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileList, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * }); + * + * // Using Promises + * async.transform(fileList, transformFileSize) + * .then(result => { + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * (async () => { + * try { + * let result = await async.transform(fileList, transformFileSize); + * console.log(result); + * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] + * } + * catch (err) { + * console.log(err); + * } + * })(); + * + * @example + * + * // file1.txt is a file that is 1000 bytes in size + * // file2.txt is a file that is 2000 bytes in size + * // file3.txt is a file that is 3000 bytes in size + * + * // helper function that returns human-readable size format from bytes + * function formatBytes(bytes, decimals = 2) { + * // implementation not included for brevity + * return humanReadbleFilesize; + * } + * + * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; + * + * // asynchronous function that returns the file size, transformed to human-readable format + * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. + * function transformFileSize(acc, value, key, callback) { + * fs.stat(value, function(err, stat) { + * if (err) { + * return callback(err); + * } + * acc[key] = formatBytes(stat.size); + * callback(null); + * }); + * } + * + * // Using callbacks + * async.transform(fileMap, transformFileSize, function(err, result) { + * if(err) { + * console.log(err); + * } else { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * }); + * + * // Using Promises + * async.transform(fileMap, transformFileSize) + * .then(result => { + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * }).catch(err => { + * console.log(err); + * }); + * + * // Using async/await + * async () => { + * try { + * let result = await async.transform(fileMap, transformFileSize); + * console.log(result); + * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } + * } + * catch (err) { + * console.log(err); + * } + * } + * + */ + function transform (coll, accumulator, iteratee, callback) { + if (arguments.length <= 3 && typeof accumulator === 'function') { + callback = iteratee; + iteratee = accumulator; + accumulator = Array.isArray(coll) ? [] : {}; + } + callback = once(callback || promiseCallback()); + var _iteratee = wrapAsync(iteratee); -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; + eachOf$1(coll, (v, k, cb) => { + _iteratee(accumulator, v, k, cb); + }, err => callback(err, accumulator)); + return callback[PROMISE_SYMBOL] } - ++c; - } - list.length -= c; - return ret; -} -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; + /** + * It runs each task in series but stops whenever any of the functions were + * successful. If one of the tasks were successful, the `callback` will be + * passed the result of the successful task. If all tasks fail, the callback + * will be passed the error and result (if any) of the final attempt. + * + * @name tryEach + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to + * run, each function is passed a `callback(err, result)` it must call on + * completion with an error `err` (which can be `null`) and an optional `result` + * value. + * @param {Function} [callback] - An optional callback which is called when one + * of the tasks has succeeded, or all have failed. It receives the `err` and + * `result` arguments of the last attempt at completing the `task`. Invoked with + * (err, results). + * @returns {Promise} a promise, if no callback is passed + * @example + * async.tryEach([ + * function getDataFromFirstWebsite(callback) { + * // Try getting the data from the first website + * callback(err, data); + * }, + * function getDataFromSecondWebsite(callback) { + * // First website failed, + * // Try getting the data from the backup website + * callback(err, data); + * } + * ], + * // optional callback + * function(err, results) { + * Now do something with the data. + * }); + * + */ + function tryEach(tasks, callback) { + var error = null; + var result; + return eachSeries$1(tasks, (task, taskCb) => { + wrapAsync(task)((err, ...args) => { + if (err === false) return taskCb(err); + + if (args.length < 2) { + [result] = args; + } else { + result = args; + } + error = err; + taskCb(err ? null : {}); + }); + }, () => callback(error, result)); } - ++c; - } - list.length -= c; - return ret; -} -function endReadable(stream) { - var state = stream._readableState; + var tryEach$1 = awaitify(tryEach); - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); + /** + * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, + * unmemoized form. Handy for testing. + * + * @name unmemoize + * @static + * @memberOf module:Utils + * @method + * @see [async.memoize]{@link module:Utils.memoize} + * @category Util + * @param {AsyncFunction} fn - the memoized function + * @returns {AsyncFunction} a function that calls the original unmemoized function + */ + function unmemoize(fn) { + return (...args) => { + return (fn.unmemoized || fn)(...args); + }; + } - if (!state.endEmitted) { - state.ended = true; - pna.nextTick(endReadableNT, state, stream); - } -} + /** + * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. + * + * @name whilst + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` passes. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has failed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if no callback is passed + * @example + * + * var count = 0; + * async.whilst( + * function test(cb) { cb(null, count < 5); }, + * function iter(callback) { + * count++; + * setTimeout(function() { + * callback(null, count); + * }, 1000); + * }, + * function (err, n) { + * // 5 seconds have passed, n = 5 + * } + * ); + */ + function whilst(test, iteratee, callback) { + callback = onlyOnce(callback); + var _fn = wrapAsync(iteratee); + var _test = wrapAsync(test); + var results = []; -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} + function next(err, ...rest) { + if (err) return callback(err); + results = rest; + if (err === false) return; + _test(check); + } -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} + function check(err, truth) { + if (err) return callback(err); + if (err === false) return; + if (!truth) return callback(null, ...results); + _fn(next); + } -/***/ }), + return _test(check); + } + var whilst$1 = awaitify(whilst, 3); -/***/ 95401: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when + * stopped, or an error occurs. `callback` will be passed an error and any + * arguments passed to the final `iteratee`'s callback. + * + * The inverse of [whilst]{@link module:ControlFlow.whilst}. + * + * @name until + * @static + * @memberOf module:ControlFlow + * @method + * @see [async.whilst]{@link module:ControlFlow.whilst} + * @category Control Flow + * @param {AsyncFunction} test - asynchronous truth test to perform before each + * execution of `iteratee`. Invoked with (callback). + * @param {AsyncFunction} iteratee - An async function which is called each time + * `test` fails. Invoked with (callback). + * @param {Function} [callback] - A callback which is called after the test + * function has passed and repeated execution of `iteratee` has stopped. `callback` + * will be passed an error and any arguments passed to the final `iteratee`'s + * callback. Invoked with (err, [results]); + * @returns {Promise} a promise, if a callback is not passed + * + * @example + * const results = [] + * let finished = false + * async.until(function test(cb) { + * cb(null, finished) + * }, function iter(next) { + * fetchPage(url, (err, body) => { + * if (err) return next(err) + * results = results.concat(body.objects) + * finished = !!body.next + * next(err) + * }) + * }, function done (err) { + * // all pages have been fetched + * }) + */ + function until(test, iteratee, callback) { + const _test = wrapAsync(test); + return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); + } -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. + /** + * Runs the `tasks` array of functions in series, each passing their results to + * the next in the array. However, if any of the `tasks` pass an error to their + * own callback, the next function is not executed, and the main `callback` is + * immediately called with the error. + * + * @name waterfall + * @static + * @memberOf module:ControlFlow + * @method + * @category Control Flow + * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} + * to run. + * Each function should complete with any number of `result` values. + * The `result` values will be passed as arguments, in order, to the next task. + * @param {Function} [callback] - An optional callback to run once all the + * functions have completed. This will be passed the results of the last task's + * callback. Invoked with (err, [results]). + * @returns {Promise} a promise, if a callback is omitted + * @example + * + * async.waterfall([ + * function(callback) { + * callback(null, 'one', 'two'); + * }, + * function(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * }, + * function(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + * ], function (err, result) { + * // result now equals 'done' + * }); + * + * // Or, with named functions: + * async.waterfall([ + * myFirstFunction, + * mySecondFunction, + * myLastFunction, + * ], function (err, result) { + * // result now equals 'done' + * }); + * function myFirstFunction(callback) { + * callback(null, 'one', 'two'); + * } + * function mySecondFunction(arg1, arg2, callback) { + * // arg1 now equals 'one' and arg2 now equals 'two' + * callback(null, 'three'); + * } + * function myLastFunction(arg1, callback) { + * // arg1 now equals 'three' + * callback(null, 'done'); + * } + */ + function waterfall (tasks, callback) { + callback = once(callback); + if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); + if (!tasks.length) return callback(); + var taskIndex = 0; + function nextTask(args) { + var task = wrapAsync(tasks[taskIndex++]); + task(...args, onlyOnce(next)); + } + function next(err, ...args) { + if (err === false) return + if (err || taskIndex === tasks.length) { + return callback(err, ...args); + } + nextTask(args); + } -module.exports = Transform; + nextTask([]); + } -var Duplex = __nccwpck_require__(5364); + var waterfall$1 = awaitify(waterfall); -/**/ -var util = Object.create(__nccwpck_require__(95898)); -util.inherits = __nccwpck_require__(44124); -/**/ + /** + * An "async function" in the context of Async is an asynchronous function with + * a variable number of parameters, with the final parameter being a callback. + * (`function (arg1, arg2, ..., callback) {}`) + * The final callback is of the form `callback(err, results...)`, which must be + * called once the function is completed. The callback should be called with a + * Error as its first argument to signal that an error occurred. + * Otherwise, if no error occurred, it should be called with `null` as the first + * argument, and any additional `result` arguments that may apply, to signal + * successful completion. + * The callback must be called exactly once, ideally on a later tick of the + * JavaScript event loop. + * + * This type of function is also referred to as a "Node-style async function", + * or a "continuation passing-style function" (CPS). Most of the methods of this + * library are themselves CPS/Node-style async functions, or functions that + * return CPS/Node-style async functions. + * + * Wherever we accept a Node-style async function, we also directly accept an + * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. + * In this case, the `async` function will not be passed a final callback + * argument, and any thrown error will be used as the `err` argument of the + * implicit callback, and the return value will be used as the `result` value. + * (i.e. a `rejected` of the returned Promise becomes the `err` callback + * argument, and a `resolved` value becomes the `result`.) + * + * Note, due to JavaScript limitations, we can only detect native `async` + * functions and not transpilied implementations. + * Your environment must have `async`/`await` support for this to work. + * (e.g. Node > v7.6, or a recent version of a modern browser). + * If you are using `async` functions through a transpiler (e.g. Babel), you + * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, + * because the `async function` will be compiled to an ordinary function that + * returns a promise. + * + * @typedef {Function} AsyncFunction + * @static + */ -util.inherits(Transform, Duplex); -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; + var index = { + apply, + applyEach, + applyEachSeries, + asyncify, + auto, + autoInject, + cargo: cargo$1, + cargoQueue: cargo, + compose, + concat: concat$1, + concatLimit: concatLimit$1, + concatSeries: concatSeries$1, + constant: constant$1, + detect: detect$1, + detectLimit: detectLimit$1, + detectSeries: detectSeries$1, + dir, + doUntil, + doWhilst: doWhilst$1, + each, + eachLimit: eachLimit$1, + eachOf: eachOf$1, + eachOfLimit: eachOfLimit$1, + eachOfSeries: eachOfSeries$1, + eachSeries: eachSeries$1, + ensureAsync, + every: every$1, + everyLimit: everyLimit$1, + everySeries: everySeries$1, + filter: filter$1, + filterLimit: filterLimit$1, + filterSeries: filterSeries$1, + forever: forever$1, + groupBy, + groupByLimit: groupByLimit$1, + groupBySeries, + log, + map: map$1, + mapLimit: mapLimit$1, + mapSeries: mapSeries$1, + mapValues, + mapValuesLimit: mapValuesLimit$1, + mapValuesSeries, + memoize, + nextTick, + parallel, + parallelLimit, + priorityQueue, + queue, + race: race$1, + reduce: reduce$1, + reduceRight, + reflect, + reflectAll, + reject: reject$1, + rejectLimit: rejectLimit$1, + rejectSeries: rejectSeries$1, + retry, + retryable, + seq, + series, + setImmediate: setImmediate$1, + some: some$1, + someLimit: someLimit$1, + someSeries: someSeries$1, + sortBy: sortBy$1, + timeout, + times, + timesLimit, + timesSeries, + transform, + tryEach: tryEach$1, + unmemoize, + until, + waterfall: waterfall$1, + whilst: whilst$1, - var cb = ts.writecb; + // aliases + all: every$1, + allLimit: everyLimit$1, + allSeries: everySeries$1, + any: some$1, + anyLimit: someLimit$1, + anySeries: someSeries$1, + find: detect$1, + findLimit: detectLimit$1, + findSeries: detectSeries$1, + flatMap: concat$1, + flatMapLimit: concatLimit$1, + flatMapSeries: concatSeries$1, + forEach: each, + forEachSeries: eachSeries$1, + forEachLimit: eachLimit$1, + forEachOf: eachOf$1, + forEachOfSeries: eachOfSeries$1, + forEachOfLimit: eachOfLimit$1, + inject: reduce$1, + foldl: reduce$1, + foldr: reduceRight, + select: filter$1, + selectLimit: filterLimit$1, + selectSeries: filterSeries$1, + wrapSync: asyncify, + during: whilst$1, + doDuring: doWhilst$1 + }; - if (!cb) { - return this.emit('error', new Error('write callback called multiple times')); - } + exports.all = every$1; + exports.allLimit = everyLimit$1; + exports.allSeries = everySeries$1; + exports.any = some$1; + exports.anyLimit = someLimit$1; + exports.anySeries = someSeries$1; + exports.apply = apply; + exports.applyEach = applyEach; + exports.applyEachSeries = applyEachSeries; + exports.asyncify = asyncify; + exports.auto = auto; + exports.autoInject = autoInject; + exports.cargo = cargo$1; + exports.cargoQueue = cargo; + exports.compose = compose; + exports.concat = concat$1; + exports.concatLimit = concatLimit$1; + exports.concatSeries = concatSeries$1; + exports.constant = constant$1; + exports.default = index; + exports.detect = detect$1; + exports.detectLimit = detectLimit$1; + exports.detectSeries = detectSeries$1; + exports.dir = dir; + exports.doDuring = doWhilst$1; + exports.doUntil = doUntil; + exports.doWhilst = doWhilst$1; + exports.during = whilst$1; + exports.each = each; + exports.eachLimit = eachLimit$1; + exports.eachOf = eachOf$1; + exports.eachOfLimit = eachOfLimit$1; + exports.eachOfSeries = eachOfSeries$1; + exports.eachSeries = eachSeries$1; + exports.ensureAsync = ensureAsync; + exports.every = every$1; + exports.everyLimit = everyLimit$1; + exports.everySeries = everySeries$1; + exports.filter = filter$1; + exports.filterLimit = filterLimit$1; + exports.filterSeries = filterSeries$1; + exports.find = detect$1; + exports.findLimit = detectLimit$1; + exports.findSeries = detectSeries$1; + exports.flatMap = concat$1; + exports.flatMapLimit = concatLimit$1; + exports.flatMapSeries = concatSeries$1; + exports.foldl = reduce$1; + exports.foldr = reduceRight; + exports.forEach = each; + exports.forEachLimit = eachLimit$1; + exports.forEachOf = eachOf$1; + exports.forEachOfLimit = eachOfLimit$1; + exports.forEachOfSeries = eachOfSeries$1; + exports.forEachSeries = eachSeries$1; + exports.forever = forever$1; + exports.groupBy = groupBy; + exports.groupByLimit = groupByLimit$1; + exports.groupBySeries = groupBySeries; + exports.inject = reduce$1; + exports.log = log; + exports.map = map$1; + exports.mapLimit = mapLimit$1; + exports.mapSeries = mapSeries$1; + exports.mapValues = mapValues; + exports.mapValuesLimit = mapValuesLimit$1; + exports.mapValuesSeries = mapValuesSeries; + exports.memoize = memoize; + exports.nextTick = nextTick; + exports.parallel = parallel; + exports.parallelLimit = parallelLimit; + exports.priorityQueue = priorityQueue; + exports.queue = queue; + exports.race = race$1; + exports.reduce = reduce$1; + exports.reduceRight = reduceRight; + exports.reflect = reflect; + exports.reflectAll = reflectAll; + exports.reject = reject$1; + exports.rejectLimit = rejectLimit$1; + exports.rejectSeries = rejectSeries$1; + exports.retry = retry; + exports.retryable = retryable; + exports.select = filter$1; + exports.selectLimit = filterLimit$1; + exports.selectSeries = filterSeries$1; + exports.seq = seq; + exports.series = series; + exports.setImmediate = setImmediate$1; + exports.some = some$1; + exports.someLimit = someLimit$1; + exports.someSeries = someSeries$1; + exports.sortBy = sortBy$1; + exports.timeout = timeout; + exports.times = times; + exports.timesLimit = timesLimit; + exports.timesSeries = timesSeries; + exports.transform = transform; + exports.tryEach = tryEach$1; + exports.unmemoize = unmemoize; + exports.until = until; + exports.waterfall = waterfall$1; + exports.whilst = whilst$1; + exports.wrapSync = asyncify; - ts.writechunk = null; - ts.writecb = null; + Object.defineProperty(exports, '__esModule', { value: true }); - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); +})); - cb(er); - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } -} +/***/ }), -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); +/***/ 14812: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Duplex.call(this, options); +module.exports = +{ + parallel : __nccwpck_require__(8210), + serial : __nccwpck_require__(50445), + serialOrdered : __nccwpck_require__(3578) +}; - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; +/***/ }), - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; +/***/ 1700: +/***/ ((module) => { - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; +// API +module.exports = abort; - if (typeof options.flush === 'function') this._flush = options.flush; - } +/** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ +function abort(state) +{ + Object.keys(state.jobs).forEach(clean.bind(state)); - // When the writable side finishes, then flush out anything remaining. - this.on('prefinish', prefinish); + // reset leftover jobs + state.jobs = {}; } -function prefinish() { - var _this = this; - - if (typeof this._flush === 'function') { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); +/** + * Cleans up leftover job by invoking abort function for the provided job id + * + * @this state + * @param {string|number} key - job id to abort + */ +function clean(key) +{ + if (typeof this.jobs[key] == 'function') + { + this.jobs[key](); } } -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); -}; +/***/ }), -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; +/***/ 72794: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; +var defer = __nccwpck_require__(15295); - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; +// API +module.exports = async; -Transform.prototype._destroy = function (err, cb) { - var _this2 = this; +/** + * Runs provided callback asynchronously + * even if callback itself is not + * + * @param {function} callback - callback to invoke + * @returns {function} - augmented callback + */ +function async(callback) +{ + var isAsync = false; - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - _this2.emit('close'); - }); -}; + // check if async happened + defer(function() { isAsync = true; }); -function done(stream, er, data) { - if (er) return stream.emit('error', er); + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); + } + else + { + defer(function nextTick_callback() + { + callback(err, result); + }); + } + }; +} - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); +/***/ }), - if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); +/***/ 15295: +/***/ ((module) => { - return stream.push(null); +module.exports = defer; + +/** + * Runs provided function on next iteration of the event loop + * + * @param {function} fn - function to run + */ +function defer(fn) +{ + var nextTick = typeof setImmediate == 'function' + ? setImmediate + : ( + typeof process == 'object' && typeof process.nextTick == 'function' + ? process.nextTick + : null + ); + + if (nextTick) + { + nextTick(fn); + } + else + { + setTimeout(fn, 0); + } } + /***/ }), -/***/ 33369: +/***/ 9023: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. +var async = __nccwpck_require__(72794) + , abort = __nccwpck_require__(1700) + ; +// API +module.exports = iterate; +/** + * Iterates over each job object + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {object} state - current job status + * @param {function} callback - invoked when all elements processed + */ +function iterate(list, iterator, state, callback) +{ + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; -/**/ + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; + } -var pna = __nccwpck_require__(47810); -/**/ + // clean up jobs + delete state.jobs[key]; -module.exports = Writable; + if (error) + { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort(state); + } + else + { + state.results[key] = output; + } -/* */ -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; + // return salvaged results + callback(error, state.results); + }); } -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; +/** + * Runs iterator over provided job element + * + * @param {function} iterator - iterator to invoke + * @param {string|number} key - key/index of the element in the list of jobs + * @param {mixed} item - job description + * @param {function} callback - invoked after iterator is done with the job + * @returns {function|mixed} - job abort function or something else + */ +function runJob(iterator, key, item, callback) +{ + var aborter; - this.next = null; - this.entry = null; - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ + // allow shortcut if iterator expects only two arguments + if (iterator.length == 2) + { + aborter = iterator(item, async(callback)); + } + // otherwise go with full three arguments + else + { + aborter = iterator(item, key, async(callback)); + } -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; -/**/ + return aborter; +} -/**/ -var Duplex; -/**/ -Writable.WritableState = WritableState; +/***/ }), -/**/ -var util = Object.create(__nccwpck_require__(95898)); -util.inherits = __nccwpck_require__(44124); -/**/ +/***/ 42474: +/***/ ((module) => { -/**/ -var internalUtil = { - deprecate: __nccwpck_require__(65278) -}; -/**/ +// API +module.exports = state; -/**/ -var Stream = __nccwpck_require__(41715); -/**/ +/** + * Creates initial state object + * for iteration over list + * + * @param {array|object} list - list to iterate over + * @param {function|null} sortMethod - function to use for keys sort, + * or `null` to keep them as is + * @returns {object} - initial state object + */ +function state(list, sortMethod) +{ + var isNamedList = !Array.isArray(list) + , initState = + { + index : 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs : {}, + results : isNamedList ? {} : [], + size : isNamedList ? Object.keys(list).length : list.length + } + ; -/**/ + if (sortMethod) + { + // sort array keys based on it's values + // sort object's keys just on own merit + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) + { + return sortMethod(list[a], list[b]); + }); + } -var Buffer = (__nccwpck_require__(36476).Buffer); -var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + return initState; } -/**/ - -var destroyImpl = __nccwpck_require__(71890); -util.inherits(Writable, Stream); +/***/ }), -function nop() {} +/***/ 37942: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function WritableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(5364); +var abort = __nccwpck_require__(1700) + , async = __nccwpck_require__(72794) + ; - options = options || {}; +// API +module.exports = terminator; - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; +/** + * Terminates jobs in the attached state context + * + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination + */ +function terminator(callback) +{ + if (!Object.keys(this.jobs).length) + { + return; + } - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + // fast forward iteration index + this.index = this.size; - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + // abort jobs + abort(this); - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var writableHwm = options.writableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; + // send back results we have so far + async(callback)(null, this.results); +} - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); +/***/ }), - // if _final has been called - this.finalCalled = false; +/***/ 8210: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(42474) + , terminator = __nccwpck_require__(37942) + ; - // has it been destroyed - this.destroyed = false; +// Public API +module.exports = parallel; - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; +/** + * Runs iterator over provided array elements in parallel + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function parallel(list, iterator, callback) +{ + var state = initState(list); - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); - // a flag to see when we're in the middle of a write. - this.writing = false; + state.index++; + } - // when true all writes will be buffered until .uncork() call - this.corked = 0; + return terminator.bind(state, callback); +} - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; +/***/ }), - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; +/***/ 50445: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; +var serialOrdered = __nccwpck_require__(3578); - // the amount that is being written when _write is called. - this.writelen = 0; +// Public API +module.exports = serial; - this.bufferedRequest = null; - this.lastBufferedRequest = null; +/** + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); +} - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; +/***/ }), - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; +/***/ 3578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // count buffered requests - this.bufferedRequestCount = 0; +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(42474) + , terminator = __nccwpck_require__(37942) + ; - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} +// Public API +module.exports = serialOrdered; +// sorting helpers +module.exports.ascending = ascending; +module.exports.descending = descending; -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; -}; +/** + * Runs iterator over provided sorted array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serialOrdered(list, iterator, sortMethod, callback) +{ + var state = initState(list, sortMethod); -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; + } -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; + state.index++; - return object && object._writableState instanceof WritableState; + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; } + + // done here + callback(null, state.results); }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; + + return terminator.bind(state, callback); } -function Writable(options) { - Duplex = Duplex || __nccwpck_require__(5364); +/* + * -- Sort methods + */ - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. +/** + * sort helper to sort array elements in ascending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function ascending(a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); - } +/** + * sort helper to sort array elements in descending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function descending(a, b) +{ + return -1 * ascending(a, b); +} - this._writableState = new WritableState(options, this); - // legacy. - this.writable = true; +/***/ }), - if (options) { - if (typeof options.write === 'function') this._write = options.write; +/***/ 33497: +/***/ ((module) => { - if (typeof options.writev === 'function') this._writev = options.writev; +function isBuffer (value) { + return Buffer.isBuffer(value) || value instanceof Uint8Array +} - if (typeof options.destroy === 'function') this._destroy = options.destroy; +function isEncoding (encoding) { + return Buffer.isEncoding(encoding) +} - if (typeof options.final === 'function') this._final = options.final; - } +function alloc (size, fill, encoding) { + return Buffer.alloc(size, fill, encoding) +} - Stream.call(this); +function allocUnsafe (size) { + return Buffer.allocUnsafe(size) } -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; +function allocUnsafeSlow (size) { + return Buffer.allocUnsafeSlow(size) +} -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - pna.nextTick(cb, er); +function byteLength (string, encoding) { + return Buffer.byteLength(string, encoding) } -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; +function compare (a, b) { + return Buffer.compare(a, b) +} - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - pna.nextTick(cb, er); - valid = false; - } - return valid; +function concat (buffers, totalLength) { + return Buffer.concat(buffers, totalLength) } -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = !state.objectMode && _isUint8Array(chunk); +function copy (source, target, targetStart, start, end) { + return toBuffer(source).copy(target, targetStart, start, end) +} - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } +function equals (a, b) { + return toBuffer(a).equals(b) +} - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } +function fill (buffer, value, offset, end, encoding) { + return toBuffer(buffer).fill(value, offset, end, encoding) +} - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; +function from (value, encodingOrOffset, length) { + return Buffer.from(value, encodingOrOffset, length) +} - if (typeof cb !== 'function') cb = nop; +function includes (buffer, value, byteOffset, encoding) { + return toBuffer(buffer).includes(value, byteOffset, encoding) +} - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } +function indexOf (buffer, value, byfeOffset, encoding) { + return toBuffer(buffer).indexOf(value, byfeOffset, encoding) +} - return ret; -}; +function lastIndexOf (buffer, value, byteOffset, encoding) { + return toBuffer(buffer).lastIndexOf(value, byteOffset, encoding) +} -Writable.prototype.cork = function () { - var state = this._writableState; +function swap16 (buffer) { + return toBuffer(buffer).swap16() +} - state.corked++; -}; +function swap32 (buffer) { + return toBuffer(buffer).swap32() +} -Writable.prototype.uncork = function () { - var state = this._writableState; - - if (state.corked) { - state.corked--; - - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; +function swap64 (buffer) { + return toBuffer(buffer).swap64() +} -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; +function toBuffer (buffer) { + if (Buffer.isBuffer(buffer)) return buffer + return Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength) +} -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - return chunk; +function toString (buffer, encoding, start, end) { + return toBuffer(buffer).toString(encoding, start, end) } -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._writableState.highWaterMark; - } -}); +function write (buffer, string, offset, length, encoding) { + return toBuffer(buffer).write(string, offset, length, encoding) +} -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - var len = state.objectMode ? 1 : chunk.length; +function writeDoubleLE (buffer, value, offset) { + return toBuffer(buffer).writeDoubleLE(value, offset) +} - state.length += len; +function writeFloatLE (buffer, value, offset) { + return toBuffer(buffer).writeFloatLE(value, offset) +} - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; +function writeUInt32LE (buffer, value, offset) { + return toBuffer(buffer).writeUInt32LE(value, offset) +} - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } +function writeInt32LE (buffer, value, offset) { + return toBuffer(buffer).writeInt32LE(value, offset) +} - return ret; +function readDoubleLE (buffer, offset) { + return toBuffer(buffer).readDoubleLE(offset) } -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; +function readFloatLE (buffer, offset) { + return toBuffer(buffer).readFloatLE(offset) } -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; +function readUInt32LE (buffer, offset) { + return toBuffer(buffer).readUInt32LE(offset) +} - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - pna.nextTick(cb, er); - // this can emit finish, and it will always happen - // after error - pna.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - // this can emit finish, but finish must - // always follow error - finishMaybe(stream, state); - } +function readInt32LE (buffer, offset) { + return toBuffer(buffer).readInt32LE(offset) } -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; +module.exports = { + isBuffer, + isEncoding, + alloc, + allocUnsafe, + allocUnsafeSlow, + byteLength, + compare, + concat, + copy, + equals, + fill, + from, + includes, + indexOf, + lastIndexOf, + swap16, + swap32, + swap64, + toBuffer, + toString, + write, + writeDoubleLE, + writeFloatLE, + writeUInt32LE, + writeInt32LE, + readDoubleLE, + readFloatLE, + readUInt32LE, + readInt32LE } -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; - onwriteStateUpdate(state); +/***/ }), - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); +/***/ 9417: +/***/ ((module) => { - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } +"use strict"; - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } -} +module.exports = balanced; +function balanced(a, b, str) { + if (a instanceof RegExp) a = maybeMatch(a, str); + if (b instanceof RegExp) b = maybeMatch(b, str); -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); + var r = range(a, b, str); + + return r && { + start: r[0], + end: r[1], + pre: str.slice(0, r[0]), + body: str.slice(r[0] + a.length, r[1]), + post: str.slice(r[1] + b.length) + }; } -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } +function maybeMatch(reg, str) { + var m = str.match(reg); + return m ? m[0] : null; } -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; +balanced.range = range; +function range(a, b, str) { + var begs, beg, left, right, result; + var ai = str.indexOf(a); + var bi = str.indexOf(b, ai + 1); + var i = ai; - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; + if (ai >= 0 && bi > 0) { + begs = []; + left = str.length; - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; + while (i >= 0 && !result) { + if (i == ai) { + begs.push(i); + ai = str.indexOf(a, i + 1); + } else if (begs.length == 1) { + result = [ begs.pop(), bi ]; + } else { + beg = begs.pop(); + if (beg < left) { + left = beg; + right = bi; + } - doWrite(stream, state, true, state.length, buffer, '', holder.finish); + bi = str.indexOf(b, i + 1); + } - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); + i = ai < bi && ai >= 0 ? ai : bi; } - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } + if (begs.length) { + result = [ left, right ]; } - - if (entry === null) state.lastBufferedRequest = null; } - state.bufferedRequest = entry; - state.bufferProcessing = false; + return result; } -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); -}; - -Writable.prototype._writev = null; - -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } +/***/ }), - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); +/***/ 83682: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } +var register = __nccwpck_require__(44670); +var addHook = __nccwpck_require__(5549); +var removeHook = __nccwpck_require__(6819); - // ignore unnecessary end() calls. - if (!state.ending) endWritable(this, state, cb); -}; +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind; +var bindable = bind.bind(bind); -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - if (err) { - stream.emit('error', err); - } - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); +function bindApi(hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply( + null, + name ? [state, name] : [state] + ); + hook.api = { remove: removeHookRef }; + hook.remove = removeHookRef; + ["before", "error", "after", "wrap"].forEach(function (kind) { + var args = name ? [state, kind, name] : [state, kind]; + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); }); } -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function') { - state.pendingcb++; - state.finalCalled = true; - pna.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - } - } - return need; +function HookSingular() { + var singularHookName = "h"; + var singularHookState = { + registry: {}, + }; + var singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; } -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; +function HookCollection() { + var state = { + registry: {}, + }; + + var hook = register.bind(null, state); + bindApi(hook, state); + + return hook; } -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; +var collectionHookDeprecationMessageDisplayed = false; +function Hook() { + if (!collectionHookDeprecationMessageDisplayed) { + console.warn( + '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' + ); + collectionHookDeprecationMessageDisplayed = true; } - - // reuse the free corkReq. - state.corkedRequestsFree.next = corkReq; + return HookCollection(); } -Object.defineProperty(Writable.prototype, 'destroyed', { - get: function () { - if (this._writableState === undefined) { - return false; - } - return this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } +Hook.Singular = HookSingular.bind(); +Hook.Collection = HookCollection.bind(); - // backward compatibility, the user is explicitly - // managing destroyed - this._writableState.destroyed = value; - } -}); +module.exports = Hook; +// expose constructors as a named property for TypeScript +module.exports.Hook = Hook; +module.exports.Singular = Hook.Singular; +module.exports.Collection = Hook.Collection; -Writable.prototype.destroy = destroyImpl.destroy; -Writable.prototype._undestroy = destroyImpl.undestroy; -Writable.prototype._destroy = function (err, cb) { - this.end(); - cb(err); -}; /***/ }), -/***/ 37898: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 5549: +/***/ ((module) => { -"use strict"; +module.exports = addHook; +function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; + } -var Buffer = (__nccwpck_require__(36476).Buffer); -var util = __nccwpck_require__(73837); + if (kind === "after") { + hook = function (method, options) { + var result; + return Promise.resolve() + .then(method.bind(null, options)) + .then(function (result_) { + result = result_; + return orig(result, options); + }) + .then(function () { + return result; + }); + }; + } -function copyBuffer(src, target, offset) { - src.copy(target, offset); + if (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); + }; + } + + state.registry[name].push({ + hook: hook, + orig: orig, + }); } -module.exports = function () { - function BufferList() { - _classCallCheck(this, BufferList); - this.head = null; - this.tail = null; - this.length = 0; - } +/***/ }), - BufferList.prototype.push = function push(v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; +/***/ 44670: +/***/ ((module) => { - BufferList.prototype.unshift = function unshift(v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; +module.exports = register; - BufferList.prototype.shift = function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } - BufferList.prototype.clear = function clear() { - this.head = this.tail = null; - this.length = 0; - }; + if (!options) { + options = {}; + } - BufferList.prototype.join = function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options); + }, method)(); + } - BufferList.prototype.concat = function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; + return Promise.resolve().then(function () { + if (!state.registry[name]) { + return method(options); } - return ret; - }; - - return BufferList; -}(); -if (util && util.inspect && util.inspect.custom) { - module.exports.prototype[util.inspect.custom] = function () { - var obj = util.inspect({ length: this.length }); - return this.constructor.name + ' ' + obj; - }; + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); } -/***/ }), - -/***/ 71890: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -/**/ - -var pna = __nccwpck_require__(47810); -/**/ -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; +/***/ }), - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; +/***/ 6819: +/***/ ((module) => { - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - pna.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - pna.nextTick(emitErrorNT, this, err); - } - } +module.exports = removeHook; - return this; +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; } - // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks - - if (this._readableState) { - this._readableState.destroyed = true; - } + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; + if (index === -1) { + return; } - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - pna.nextTick(emitErrorNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - pna.nextTick(emitErrorNT, _this, err); - } - } else if (cb) { - cb(err); - } - }); - - return this; + state.registry[name].splice(index, 1); } -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} +/***/ }), -function emitErrorNT(self, err) { - self.emit('error', err); -} +/***/ 66474: +/***/ ((module, exports, __nccwpck_require__) => { -module.exports = { - destroy: destroy, - undestroy: undestroy +var Chainsaw = __nccwpck_require__(46533); +var EventEmitter = (__nccwpck_require__(82361).EventEmitter); +var Buffers = __nccwpck_require__(51590); +var Vars = __nccwpck_require__(13755); +var Stream = (__nccwpck_require__(12781).Stream); + +exports = module.exports = function (bufOrEm, eventName) { + if (Buffer.isBuffer(bufOrEm)) { + return exports.parse(bufOrEm); + } + + var s = exports.stream(); + if (bufOrEm && bufOrEm.pipe) { + bufOrEm.pipe(s); + } + else if (bufOrEm) { + bufOrEm.on(eventName || 'data', function (buf) { + s.write(buf); + }); + + bufOrEm.on('end', function () { + s.end(); + }); + } + return s; }; -/***/ }), +exports.stream = function (input) { + if (input) return exports.apply(null, arguments); + + var pending = null; + function getBytes (bytes, cb, skip) { + pending = { + bytes : bytes, + skip : skip, + cb : function (buf) { + pending = null; + cb(buf); + }, + }; + dispatch(); + } + + var offset = null; + function dispatch () { + if (!pending) { + if (caughtEnd) done = true; + return; + } + if (typeof pending === 'function') { + pending(); + } + else { + var bytes = offset + pending.bytes; + + if (buffers.length >= bytes) { + var buf; + if (offset == null) { + buf = buffers.splice(0, bytes); + if (!pending.skip) { + buf = buf.slice(); + } + } + else { + if (!pending.skip) { + buf = buffers.slice(offset, bytes); + } + offset = bytes; + } + + if (pending.skip) { + pending.cb(); + } + else { + pending.cb(buf); + } + } + } + } + + function builder (saw) { + function next () { if (!done) saw.next() } + + var self = words(function (bytes, cb) { + return function (name) { + getBytes(bytes, function (buf) { + vars.set(name, cb(buf)); + next(); + }); + }; + }); + + self.tap = function (cb) { + saw.nest(cb, vars.store); + }; + + self.into = function (key, cb) { + if (!vars.get(key)) vars.set(key, {}); + var parent = vars; + vars = Vars(parent.get(key)); + + saw.nest(function () { + cb.apply(this, arguments); + this.tap(function () { + vars = parent; + }); + }, vars.store); + }; + + self.flush = function () { + vars.store = {}; + next(); + }; + + self.loop = function (cb) { + var end = false; + + saw.nest(false, function loop () { + this.vars = vars.store; + cb.call(this, function () { + end = true; + next(); + }, vars.store); + this.tap(function () { + if (end) saw.next() + else loop.call(this) + }.bind(this)); + }, vars.store); + }; + + self.buffer = function (name, bytes) { + if (typeof bytes === 'string') { + bytes = vars.get(bytes); + } + + getBytes(bytes, function (buf) { + vars.set(name, buf); + next(); + }); + }; + + self.skip = function (bytes) { + if (typeof bytes === 'string') { + bytes = vars.get(bytes); + } + + getBytes(bytes, function () { + next(); + }); + }; + + self.scan = function find (name, search) { + if (typeof search === 'string') { + search = new Buffer(search); + } + else if (!Buffer.isBuffer(search)) { + throw new Error('search must be a Buffer or a string'); + } + + var taken = 0; + pending = function () { + var pos = buffers.indexOf(search, offset + taken); + var i = pos-offset-taken; + if (pos !== -1) { + pending = null; + if (offset != null) { + vars.set( + name, + buffers.slice(offset, offset + taken + i) + ); + offset += taken + i + search.length; + } + else { + vars.set( + name, + buffers.slice(0, taken + i) + ); + buffers.splice(0, taken + i + search.length); + } + next(); + dispatch(); + } else { + i = Math.max(buffers.length - search.length - offset - taken, 0); + } + taken += i; + }; + dispatch(); + }; + + self.peek = function (cb) { + offset = 0; + saw.nest(function () { + cb.call(this, vars.store); + this.tap(function () { + offset = null; + }); + }); + }; + + return self; + }; + + var stream = Chainsaw.light(builder); + stream.writable = true; + + var buffers = Buffers(); + + stream.write = function (buf) { + buffers.push(buf); + dispatch(); + }; + + var vars = Vars(); + + var done = false, caughtEnd = false; + stream.end = function () { + caughtEnd = true; + }; + + stream.pipe = Stream.prototype.pipe; + Object.getOwnPropertyNames(EventEmitter.prototype).forEach(function (name) { + stream[name] = EventEmitter.prototype[name]; + }); + + return stream; +}; -/***/ 41715: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +exports.parse = function parse (buffer) { + var self = words(function (bytes, cb) { + return function (name) { + if (offset + bytes <= buffer.length) { + var buf = buffer.slice(offset, offset + bytes); + offset += bytes; + vars.set(name, cb(buf)); + } + else { + vars.set(name, null); + } + return self; + }; + }); + + var offset = 0; + var vars = Vars(); + self.vars = vars.store; + + self.tap = function (cb) { + cb.call(self, vars.store); + return self; + }; + + self.into = function (key, cb) { + if (!vars.get(key)) { + vars.set(key, {}); + } + var parent = vars; + vars = Vars(parent.get(key)); + cb.call(self, vars.store); + vars = parent; + return self; + }; + + self.loop = function (cb) { + var end = false; + var ender = function () { end = true }; + while (end === false) { + cb.call(self, ender, vars.store); + } + return self; + }; + + self.buffer = function (name, size) { + if (typeof size === 'string') { + size = vars.get(size); + } + var buf = buffer.slice(offset, Math.min(buffer.length, offset + size)); + offset += size; + vars.set(name, buf); + + return self; + }; + + self.skip = function (bytes) { + if (typeof bytes === 'string') { + bytes = vars.get(bytes); + } + offset += bytes; + + return self; + }; + + self.scan = function (name, search) { + if (typeof search === 'string') { + search = new Buffer(search); + } + else if (!Buffer.isBuffer(search)) { + throw new Error('search must be a Buffer or a string'); + } + vars.set(name, null); + + // simple but slow string search + for (var i = 0; i + offset <= buffer.length - search.length + 1; i++) { + for ( + var j = 0; + j < search.length && buffer[offset+i+j] === search[j]; + j++ + ); + if (j === search.length) break; + } + + vars.set(name, buffer.slice(offset, offset + i)); + offset += i + search.length; + return self; + }; + + self.peek = function (cb) { + var was = offset; + cb.call(self, vars.store); + offset = was; + return self; + }; + + self.flush = function () { + vars.store = {}; + return self; + }; + + self.eof = function () { + return offset >= buffer.length; + }; + + return self; +}; -module.exports = __nccwpck_require__(12781); +// convert byte strings to unsigned little endian numbers +function decodeLEu (bytes) { + var acc = 0; + for (var i = 0; i < bytes.length; i++) { + acc += Math.pow(256,i) * bytes[i]; + } + return acc; +} +// convert byte strings to unsigned big endian numbers +function decodeBEu (bytes) { + var acc = 0; + for (var i = 0; i < bytes.length; i++) { + acc += Math.pow(256, bytes.length - i - 1) * bytes[i]; + } + return acc; +} -/***/ }), +// convert byte strings to signed big endian numbers +function decodeBEs (bytes) { + var val = decodeBEu(bytes); + if ((bytes[0] & 0x80) == 0x80) { + val -= Math.pow(256, bytes.length); + } + return val; +} -/***/ 44785: -/***/ ((module, exports, __nccwpck_require__) => { +// convert byte strings to signed little endian numbers +function decodeLEs (bytes) { + var val = decodeLEu(bytes); + if ((bytes[bytes.length - 1] & 0x80) == 0x80) { + val -= Math.pow(256, bytes.length); + } + return val; +} -var Stream = __nccwpck_require__(12781); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream; - exports = module.exports = Stream.Readable; - exports.Readable = Stream.Readable; - exports.Writable = Stream.Writable; - exports.Duplex = Stream.Duplex; - exports.Transform = Stream.Transform; - exports.PassThrough = Stream.PassThrough; - exports.Stream = Stream; -} else { - exports = module.exports = __nccwpck_require__(19647); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = __nccwpck_require__(33369); - exports.Duplex = __nccwpck_require__(5364); - exports.Transform = __nccwpck_require__(95401); - exports.PassThrough = __nccwpck_require__(47905); +function words (decode) { + var self = {}; + + [ 1, 2, 4, 8 ].forEach(function (bytes) { + var bits = bytes * 8; + + self['word' + bits + 'le'] + = self['word' + bits + 'lu'] + = decode(bytes, decodeLEu); + + self['word' + bits + 'ls'] + = decode(bytes, decodeLEs); + + self['word' + bits + 'be'] + = self['word' + bits + 'bu'] + = decode(bytes, decodeBEu); + + self['word' + bits + 'bs'] + = decode(bytes, decodeBEs); + }); + + // word8be(n) == word8le(n) for all n + self.word8 = self.word8u = self.word8be; + self.word8s = self.word8bs; + + return self; } /***/ }), -/***/ 36476: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 13755: +/***/ ((module) => { -/* eslint-disable node/no-deprecated-api */ -var buffer = __nccwpck_require__(14300) -var Buffer = buffer.Buffer +module.exports = function (store) { + function getset (name, value) { + var node = vars.store; + var keys = name.split('.'); + keys.slice(0,-1).forEach(function (k) { + if (node[k] === undefined) node[k] = {}; + node = node[k] + }); + var key = keys[keys.length - 1]; + if (arguments.length == 1) { + return node[key]; + } + else { + return node[key] = value; + } + } + + var vars = { + get : function (name) { + return getset(name); + }, + set : function (name, value) { + return getset(name, value); + }, + store : store || {}, + }; + return vars; +}; -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) -} +/***/ }), -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) +/***/ 11174: +/***/ (function(module) { -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} +/** + * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support. + * https://github.com/SGrondin/bottleneck + */ +(function (global, factory) { + true ? module.exports = factory() : + 0; +}(this, (function () { 'use strict'; -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} + function getCjsExportFromNamespace (n) { + return n && n['default'] || n; + } -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} + var load = function(received, defaults, onto = {}) { + var k, ref, v; + for (k in defaults) { + v = defaults[k]; + onto[k] = (ref = received[k]) != null ? ref : v; + } + return onto; + }; + var overwrite = function(received, defaults, onto = {}) { + var k, v; + for (k in received) { + v = received[k]; + if (defaults[k] !== void 0) { + onto[k] = v; + } + } + return onto; + }; -/***/ }), + var parser = { + load: load, + overwrite: overwrite + }; -/***/ 99708: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + var DLList; -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + DLList = class DLList { + constructor(incr, decr) { + this.incr = incr; + this.decr = decr; + this._first = null; + this._last = null; + this.length = 0; + } + push(value) { + var node; + this.length++; + if (typeof this.incr === "function") { + this.incr(); + } + node = { + value, + prev: this._last, + next: null + }; + if (this._last != null) { + this._last.next = node; + this._last = node; + } else { + this._first = this._last = node; + } + return void 0; + } + shift() { + var value; + if (this._first == null) { + return; + } else { + this.length--; + if (typeof this.decr === "function") { + this.decr(); + } + } + value = this._first.value; + if ((this._first = this._first.next) != null) { + this._first.prev = null; + } else { + this._last = null; + } + return value; + } -/**/ + first() { + if (this._first != null) { + return this._first.value; + } + } -var Buffer = (__nccwpck_require__(36476).Buffer); -/**/ + getArray() { + var node, ref, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } + return results; + } -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; + forEachShift(cb) { + var node; + node = this.shift(); + while (node != null) { + (cb(node), node = this.shift()); + } + return void 0; + } -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; + debug() { + var node, ref, ref1, ref2, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, { + value: ref.value, + prev: (ref1 = ref.prev) != null ? ref1.value : void 0, + next: (ref2 = ref.next) != null ? ref2.value : void 0 + })); + } + return results; + } -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} + }; -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.s = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} + var DLList_1 = DLList; -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; + var Events; -StringDecoder.prototype.end = utf8End; + Events = class Events { + constructor(instance) { + this.instance = instance; + this._events = {}; + if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) { + throw new Error("An Emitter already exists for this object"); + } + this.instance.on = (name, cb) => { + return this._addListener(name, "many", cb); + }; + this.instance.once = (name, cb) => { + return this._addListener(name, "once", cb); + }; + this.instance.removeAllListeners = (name = null) => { + if (name != null) { + return delete this._events[name]; + } else { + return this._events = {}; + } + }; + } -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; + _addListener(name, status, cb) { + var base; + if ((base = this._events)[name] == null) { + base[name] = []; + } + this._events[name].push({cb, status}); + return this.instance; + } -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; + listenerCount(name) { + if (this._events[name] != null) { + return this._events[name].length; + } else { + return 0; + } + } -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} + async trigger(name, ...args) { + var e, promises; + try { + if (name !== "debug") { + this.trigger("debug", `Event triggered: ${name}`, args); + } + if (this._events[name] == null) { + return; + } + this._events[name] = this._events[name].filter(function(listener) { + return listener.status !== "none"; + }); + promises = this._events[name].map(async(listener) => { + var e, returned; + if (listener.status === "none") { + return; + } + if (listener.status === "once") { + listener.status = "none"; + } + try { + returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; + if (typeof (returned != null ? returned.then : void 0) === "function") { + return (await returned); + } else { + return returned; + } + } catch (error) { + e = error; + { + this.trigger("error", e); + } + return null; + } + }); + return ((await Promise.all(promises))).find(function(x) { + return x != null; + }); + } catch (error) { + e = error; + { + this.trigger("error", e); + } + return null; + } + } -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} + }; -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } -} + var Events_1 = Events; -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} + var DLList$1, Events$1, Queues; -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} + DLList$1 = DLList_1; -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} + Events$1 = Events_1; -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} + Queues = class Queues { + constructor(num_priorities) { + var i; + this.Events = new Events$1(this); + this._length = 0; + this._lists = (function() { + var j, ref, results; + results = []; + for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { + results.push(new DLList$1((() => { + return this.incr(); + }), (() => { + return this.decr(); + }))); + } + return results; + }).call(this); + } -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); + } + } -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); + } + } -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; -} + push(job) { + return this._lists[job.options.priority].push(job); + } -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; + } + } -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; -} + shiftAll(fn) { + return this._lists.forEach(function(list) { + return list.forEachShift(fn); + }); + } -/***/ }), + getFirst(arr = this._lists) { + var j, len, list; + for (j = 0, len = arr.length; j < len; j++) { + list = arr[j]; + if (list.length > 0) { + return list; + } + } + return []; + } -/***/ 43084: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + shiftLastFrom(priority) { + return this.getFirst(this._lists.slice(priority).reverse()).shift(); + } -/** - * Archiver Vending - * - * @ignore - * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} - * @copyright (c) 2012-2014 Chris Talkington, contributors. - */ -var Archiver = __nccwpck_require__(35010); + }; -var formats = {}; + var Queues_1 = Queues; -/** - * Dispenses a new Archiver instance. - * - * @constructor - * @param {String} format The archive format to use. - * @param {Object} options See [Archiver]{@link Archiver} - * @return {Archiver} - */ -var vending = function(format, options) { - return vending.create(format, options); -}; + var BottleneckError; -/** - * Creates a new Archiver instance. - * - * @param {String} format The archive format to use. - * @param {Object} options See [Archiver]{@link Archiver} - * @return {Archiver} - */ -vending.create = function(format, options) { - if (formats[format]) { - var instance = new Archiver(format, options); - instance.setFormat(format); - instance.setModule(new formats[format](options)); + BottleneckError = class BottleneckError extends Error {}; - return instance; - } else { - throw new Error('create(' + format + '): format not registered'); - } -}; + var BottleneckError_1 = BottleneckError; -/** - * Registers a format for use with archiver. - * - * @param {String} format The name of the format. - * @param {Function} module The function for archiver to interact with. - * @return void - */ -vending.registerFormat = function(format, module) { - if (formats[format]) { - throw new Error('register(' + format + '): format already registered'); - } + var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; - if (typeof module !== 'function') { - throw new Error('register(' + format + '): format module invalid'); - } + NUM_PRIORITIES = 10; - if (typeof module.prototype.append !== 'function' || typeof module.prototype.finalize !== 'function') { - throw new Error('register(' + format + '): format module missing methods'); - } + DEFAULT_PRIORITY = 5; - formats[format] = module; -}; + parser$1 = parser; -/** - * Check if the format is already registered. - * - * @param {String} format the name of the format. - * @return boolean - */ -vending.isRegisteredFormat = function (format) { - if (formats[format]) { - return true; - } - - return false; -}; + BottleneckError$1 = BottleneckError_1; -vending.registerFormat('zip', __nccwpck_require__(8987)); -vending.registerFormat('tar', __nccwpck_require__(33614)); -vending.registerFormat('json', __nccwpck_require__(99827)); + Job = class Job { + constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { + this.task = task; + this.args = args; + this.rejectOnDrop = rejectOnDrop; + this.Events = Events; + this._states = _states; + this.Promise = Promise; + this.options = parser$1.load(options, jobDefaults); + this.options.priority = this._sanitizePriority(this.options.priority); + if (this.options.id === jobDefaults.id) { + this.options.id = `${this.options.id}-${this._randomIndex()}`; + } + this.promise = new this.Promise((_resolve, _reject) => { + this._resolve = _resolve; + this._reject = _reject; + }); + this.retryCount = 0; + } -module.exports = vending; + _sanitizePriority(priority) { + var sProperty; + sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; + if (sProperty < 0) { + return 0; + } else if (sProperty > NUM_PRIORITIES - 1) { + return NUM_PRIORITIES - 1; + } else { + return sProperty; + } + } -/***/ }), + _randomIndex() { + return Math.random().toString(36).slice(2); + } -/***/ 35010: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + doDrop({error, message = "This job has been dropped by Bottleneck"} = {}) { + if (this._states.remove(this.options.id)) { + if (this.rejectOnDrop) { + this._reject(error != null ? error : new BottleneckError$1(message)); + } + this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise}); + return true; + } else { + return false; + } + } -/** - * Archiver Core - * - * @ignore - * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} - * @copyright (c) 2012-2014 Chris Talkington, contributors. - */ -var fs = __nccwpck_require__(57147); -var glob = __nccwpck_require__(44967); -var async = __nccwpck_require__(57888); -var path = __nccwpck_require__(71017); -var util = __nccwpck_require__(82072); + _assertStatus(expected) { + var status; + status = this._states.jobStatus(this.options.id); + if (!(status === expected || (expected === "DONE" && status === null))) { + throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); + } + } -var inherits = (__nccwpck_require__(73837).inherits); -var ArchiverError = __nccwpck_require__(13143); -var Transform = (__nccwpck_require__(51642).Transform); + doReceive() { + this._states.start(this.options.id); + return this.Events.trigger("received", {args: this.args, options: this.options}); + } -var win32 = process.platform === 'win32'; + doQueue(reachedHWM, blocked) { + this._assertStatus("RECEIVED"); + this._states.next(this.options.id); + return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked}); + } -/** - * @constructor - * @param {String} format The archive format to use. - * @param {(CoreOptions|TransformOptions)} options See also {@link ZipOptions} and {@link TarOptions}. - */ -var Archiver = function(format, options) { - if (!(this instanceof Archiver)) { - return new Archiver(format, options); - } + doRun() { + if (this.retryCount === 0) { + this._assertStatus("QUEUED"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + return this.Events.trigger("scheduled", {args: this.args, options: this.options}); + } - if (typeof format !== 'string') { - options = format; - format = 'zip'; - } + async doExecute(chained, clearGlobalState, run, free) { + var error, eventInfo, passed; + if (this.retryCount === 0) { + this._assertStatus("RUNNING"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; + this.Events.trigger("executing", eventInfo); + try { + passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args))); + if (clearGlobalState()) { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._resolve(passed); + } + } catch (error1) { + error = error1; + return this._onFailure(error, eventInfo, clearGlobalState, run, free); + } + } - options = this.options = util.defaults(options, { - highWaterMark: 1024 * 1024, - statConcurrency: 4 - }); + doExpire(clearGlobalState, run, free) { + var error, eventInfo; + if (this._states.jobStatus(this.options.id === "RUNNING")) { + this._states.next(this.options.id); + } + this._assertStatus("EXECUTING"); + eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; + error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`); + return this._onFailure(error, eventInfo, clearGlobalState, run, free); + } - Transform.call(this, options); + async _onFailure(error, eventInfo, clearGlobalState, run, free) { + var retry, retryAfter; + if (clearGlobalState()) { + retry = (await this.Events.trigger("failed", error, eventInfo)); + if (retry != null) { + retryAfter = ~~retry; + this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); + this.retryCount++; + return run(retryAfter); + } else { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._reject(error); + } + } + } - this._format = false; - this._module = false; - this._pending = 0; - this._pointer = 0; + doDone(eventInfo) { + this._assertStatus("EXECUTING"); + this._states.next(this.options.id); + return this.Events.trigger("done", eventInfo); + } - this._entriesCount = 0; - this._entriesProcessedCount = 0; - this._fsEntriesTotalBytes = 0; - this._fsEntriesProcessedBytes = 0; + }; - this._queue = async.queue(this._onQueueTask.bind(this), 1); - this._queue.drain(this._onQueueDrain.bind(this)); + var Job_1 = Job; - this._statQueue = async.queue(this._onStatQueueTask.bind(this), options.statConcurrency); - this._statQueue.drain(this._onQueueDrain.bind(this)); + var BottleneckError$2, LocalDatastore, parser$2; - this._state = { - aborted: false, - finalize: false, - finalizing: false, - finalized: false, - modulePiped: false - }; + parser$2 = parser; - this._streams = []; -}; + BottleneckError$2 = BottleneckError_1; -inherits(Archiver, Transform); + LocalDatastore = class LocalDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.clientId = this.instance._randomIndex(); + parser$2.load(storeInstanceOptions, storeInstanceOptions, this); + this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); + this._running = 0; + this._done = 0; + this._unblockTime = 0; + this.ready = this.Promise.resolve(); + this.clients = {}; + this._startHeartbeat(); + } -/** - * Internal logic for `abort`. - * - * @private - * @return void - */ -Archiver.prototype._abort = function() { - this._state.aborted = true; - this._queue.kill(); - this._statQueue.kill(); + _startHeartbeat() { + var base; + if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) { + return typeof (base = (this.heartbeat = setInterval(() => { + var amount, incr, maximum, now, reservoir; + now = Date.now(); + if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { + this._lastReservoirRefresh = now; + this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; + this.instance._drainAll(this.computeCapacity()); + } + if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { + ({ + reservoirIncreaseAmount: amount, + reservoirIncreaseMaximum: maximum, + reservoir + } = this.storeOptions); + this._lastReservoirIncrease = now; + incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; + if (incr > 0) { + this.storeOptions.reservoir += incr; + return this.instance._drainAll(this.computeCapacity()); + } + } + }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0; + } else { + return clearInterval(this.heartbeat); + } + } - if (this._queue.idle()) { - this._shutdown(); - } -}; + async __publish__(message) { + await this.yieldLoop(); + return this.instance.Events.trigger("message", message.toString()); + } -/** - * Internal helper for appending files. - * - * @private - * @param {String} filepath The source filepath. - * @param {EntryData} data The entry data. - * @return void - */ -Archiver.prototype._append = function(filepath, data) { - data = data || {}; + async __disconnect__(flush) { + await this.yieldLoop(); + clearInterval(this.heartbeat); + return this.Promise.resolve(); + } - var task = { - source: null, - filepath: filepath - }; + yieldLoop(t = 0) { + return new this.Promise(function(resolve, reject) { + return setTimeout(resolve, t); + }); + } - if (!data.name) { - data.name = filepath; - } + computePenalty() { + var ref; + return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; + } - data.sourcePath = filepath; - task.data = data; - this._entriesCount++; + async __updateSettings__(options) { + await this.yieldLoop(); + parser$2.overwrite(options, options, this.storeOptions); + this._startHeartbeat(); + this.instance._drainAll(this.computeCapacity()); + return true; + } - if (data.stats && data.stats instanceof fs.Stats) { - task = this._updateQueueTaskWithStats(task, data.stats); - if (task) { - if (data.stats.size) { - this._fsEntriesTotalBytes += data.stats.size; - } + async __running__() { + await this.yieldLoop(); + return this._running; + } - this._queue.push(task); - } - } else { - this._statQueue.push(task); - } -}; + async __queued__() { + await this.yieldLoop(); + return this.instance.queued(); + } -/** - * Internal logic for `finalize`. - * - * @private - * @return void - */ -Archiver.prototype._finalize = function() { - if (this._state.finalizing || this._state.finalized || this._state.aborted) { - return; - } + async __done__() { + await this.yieldLoop(); + return this._done; + } - this._state.finalizing = true; + async __groupCheck__(time) { + await this.yieldLoop(); + return (this._nextRequest + this.timeout) < time; + } - this._moduleFinalize(); + computeCapacity() { + var maxConcurrent, reservoir; + ({maxConcurrent, reservoir} = this.storeOptions); + if ((maxConcurrent != null) && (reservoir != null)) { + return Math.min(maxConcurrent - this._running, reservoir); + } else if (maxConcurrent != null) { + return maxConcurrent - this._running; + } else if (reservoir != null) { + return reservoir; + } else { + return null; + } + } - this._state.finalizing = false; - this._state.finalized = true; -}; + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return (capacity == null) || weight <= capacity; + } -/** - * Checks the various state variables to determine if we can `finalize`. - * - * @private - * @return {Boolean} - */ -Archiver.prototype._maybeFinalize = function() { - if (this._state.finalizing || this._state.finalized || this._state.aborted) { - return false; - } + async __incrementReservoir__(incr) { + var reservoir; + await this.yieldLoop(); + reservoir = this.storeOptions.reservoir += incr; + this.instance._drainAll(this.computeCapacity()); + return reservoir; + } - if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { - this._finalize(); - return true; - } + async __currentReservoir__() { + await this.yieldLoop(); + return this.storeOptions.reservoir; + } - return false; -}; + isBlocked(now) { + return this._unblockTime >= now; + } -/** - * Appends an entry to the module. - * - * @private - * @fires Archiver#entry - * @param {(Buffer|Stream)} source - * @param {EntryData} data - * @param {Function} callback - * @return void - */ -Archiver.prototype._moduleAppend = function(source, data, callback) { - if (this._state.aborted) { - callback(); - return; - } + check(weight, now) { + return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; + } - this._module.append(source, data, function(err) { - this._task = null; + async __check__(weight) { + var now; + await this.yieldLoop(); + now = Date.now(); + return this.check(weight, now); + } - if (this._state.aborted) { - this._shutdown(); - return; - } + async __register__(index, weight, expiration) { + var now, wait; + await this.yieldLoop(); + now = Date.now(); + if (this.conditionsCheck(weight)) { + this._running += weight; + if (this.storeOptions.reservoir != null) { + this.storeOptions.reservoir -= weight; + } + wait = Math.max(this._nextRequest - now, 0); + this._nextRequest = now + wait + this.storeOptions.minTime; + return { + success: true, + wait, + reservoir: this.storeOptions.reservoir + }; + } else { + return { + success: false + }; + } + } - if (err) { - this.emit('error', err); - setImmediate(callback); - return; - } + strategyIsBlock() { + return this.storeOptions.strategy === 3; + } - /** - * Fires when the entry's input has been processed and appended to the archive. - * - * @event Archiver#entry - * @type {EntryData} - */ - this.emit('entry', data); - this._entriesProcessedCount++; + async __submit__(queueLength, weight) { + var blocked, now, reachedHWM; + await this.yieldLoop(); + if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { + throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); + } + now = Date.now(); + reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now); + blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); + if (blocked) { + this._unblockTime = now + this.computePenalty(); + this._nextRequest = this._unblockTime + this.storeOptions.minTime; + this.instance._dropAllQueued(); + } + return { + reachedHWM, + blocked, + strategy: this.storeOptions.strategy + }; + } - if (data.stats && data.stats.size) { - this._fsEntriesProcessedBytes += data.stats.size; - } + async __free__(index, weight) { + await this.yieldLoop(); + this._running -= weight; + this._done += weight; + this.instance._drainAll(this.computeCapacity()); + return { + running: this._running + }; + } - /** - * @event Archiver#progress - * @type {ProgressData} - */ - this.emit('progress', { - entries: { - total: this._entriesCount, - processed: this._entriesProcessedCount - }, - fs: { - totalBytes: this._fsEntriesTotalBytes, - processedBytes: this._fsEntriesProcessedBytes - } - }); + }; - setImmediate(callback); - }.bind(this)); -}; + var LocalDatastore_1 = LocalDatastore; -/** - * Finalizes the module. - * - * @private - * @return void - */ -Archiver.prototype._moduleFinalize = function() { - if (typeof this._module.finalize === 'function') { - this._module.finalize(); - } else if (typeof this._module.end === 'function') { - this._module.end(); - } else { - this.emit('error', new ArchiverError('NOENDMETHOD')); - } -}; + var BottleneckError$3, States; -/** - * Pipes the module to our internal stream with error bubbling. - * - * @private - * @return void - */ -Archiver.prototype._modulePipe = function() { - this._module.on('error', this._onModuleError.bind(this)); - this._module.pipe(this); - this._state.modulePiped = true; -}; + BottleneckError$3 = BottleneckError_1; -/** - * Determines if the current module supports a defined feature. - * - * @private - * @param {String} key - * @return {Boolean} - */ -Archiver.prototype._moduleSupports = function(key) { - if (!this._module.supports || !this._module.supports[key]) { - return false; - } + States = class States { + constructor(status1) { + this.status = status1; + this._jobs = {}; + this.counts = this.status.map(function() { + return 0; + }); + } - return this._module.supports[key]; -}; + next(id) { + var current, next; + current = this._jobs[id]; + next = current + 1; + if ((current != null) && next < this.status.length) { + this.counts[current]--; + this.counts[next]++; + return this._jobs[id]++; + } else if (current != null) { + this.counts[current]--; + return delete this._jobs[id]; + } + } -/** - * Unpipes the module from our internal stream. - * - * @private - * @return void - */ -Archiver.prototype._moduleUnpipe = function() { - this._module.unpipe(this); - this._state.modulePiped = false; -}; + start(id) { + var initial; + initial = 0; + this._jobs[id] = initial; + return this.counts[initial]++; + } -/** - * Normalizes entry data with fallbacks for key properties. - * - * @private - * @param {Object} data - * @param {fs.Stats} stats - * @return {Object} - */ -Archiver.prototype._normalizeEntryData = function(data, stats) { - data = util.defaults(data, { - type: 'file', - name: null, - date: null, - mode: null, - prefix: null, - sourcePath: null, - stats: false - }); + remove(id) { + var current; + current = this._jobs[id]; + if (current != null) { + this.counts[current]--; + delete this._jobs[id]; + } + return current != null; + } - if (stats && data.stats === false) { - data.stats = stats; - } + jobStatus(id) { + var ref; + return (ref = this.status[this._jobs[id]]) != null ? ref : null; + } - var isDir = data.type === 'directory'; + statusJobs(status) { + var k, pos, ref, results, v; + if (status != null) { + pos = this.status.indexOf(status); + if (pos < 0) { + throw new BottleneckError$3(`status must be one of ${this.status.join(', ')}`); + } + ref = this._jobs; + results = []; + for (k in ref) { + v = ref[k]; + if (v === pos) { + results.push(k); + } + } + return results; + } else { + return Object.keys(this._jobs); + } + } - if (data.name) { - if (typeof data.prefix === 'string' && '' !== data.prefix) { - data.name = data.prefix + '/' + data.name; - data.prefix = null; - } + statusCounts() { + return this.counts.reduce(((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }), {}); + } - data.name = util.sanitizePath(data.name); + }; - if (data.type !== 'symlink' && data.name.slice(-1) === '/') { - isDir = true; - data.type = 'directory'; - } else if (isDir) { - data.name += '/'; - } - } + var States_1 = States; - // 511 === 0777; 493 === 0755; 438 === 0666; 420 === 0644 - if (typeof data.mode === 'number') { - if (win32) { - data.mode &= 511; - } else { - data.mode &= 4095 - } - } else if (data.stats && data.mode === null) { - if (win32) { - data.mode = data.stats.mode & 511; - } else { - data.mode = data.stats.mode & 4095; - } + var DLList$2, Sync; - // stat isn't reliable on windows; force 0755 for dir - if (win32 && isDir) { - data.mode = 493; - } - } else if (data.mode === null) { - data.mode = isDir ? 493 : 420; - } + DLList$2 = DLList_1; - if (data.stats && data.date === null) { - data.date = data.stats.mtime; - } else { - data.date = util.dateify(data.date); - } + Sync = class Sync { + constructor(name, Promise) { + this.schedule = this.schedule.bind(this); + this.name = name; + this.Promise = Promise; + this._running = 0; + this._queue = new DLList$2(); + } - return data; -}; + isEmpty() { + return this._queue.length === 0; + } -/** - * Error listener that re-emits error on to our internal stream. - * - * @private - * @param {Error} err - * @return void - */ -Archiver.prototype._onModuleError = function(err) { - /** - * @event Archiver#error - * @type {ErrorData} - */ - this.emit('error', err); -}; + async _tryToRun() { + var args, cb, error, reject, resolve, returned, task; + if ((this._running < 1) && this._queue.length > 0) { + this._running++; + ({task, args, resolve, reject} = this._queue.shift()); + cb = (await (async function() { + try { + returned = (await task(...args)); + return function() { + return resolve(returned); + }; + } catch (error1) { + error = error1; + return function() { + return reject(error); + }; + } + })()); + this._running--; + this._tryToRun(); + return cb(); + } + } -/** - * Checks the various state variables after queue has drained to determine if - * we need to `finalize`. - * - * @private - * @return void - */ -Archiver.prototype._onQueueDrain = function() { - if (this._state.finalizing || this._state.finalized || this._state.aborted) { - return; - } + schedule(task, ...args) { + var promise, reject, resolve; + resolve = reject = null; + promise = new this.Promise(function(_resolve, _reject) { + resolve = _resolve; + return reject = _reject; + }); + this._queue.push({task, args, resolve, reject}); + this._tryToRun(); + return promise; + } - if (this._state.finalize && this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { - this._finalize(); - } -}; + }; -/** - * Appends each queue task to the module. - * - * @private - * @param {Object} task - * @param {Function} callback - * @return void - */ -Archiver.prototype._onQueueTask = function(task, callback) { - var fullCallback = () => { - if(task.data.callback) { - task.data.callback(); - } - callback(); - } + var Sync_1 = Sync; - if (this._state.finalizing || this._state.finalized || this._state.aborted) { - fullCallback(); - return; - } + var version = "2.19.5"; + var version$1 = { + version: version + }; - this._task = task; - this._moduleAppend(task.source, task.data, fullCallback); -}; + var version$2 = /*#__PURE__*/Object.freeze({ + version: version, + default: version$1 + }); -/** - * Performs a file stat and reinjects the task back into the queue. - * - * @private - * @param {Object} task - * @param {Function} callback - * @return void - */ -Archiver.prototype._onStatQueueTask = function(task, callback) { - if (this._state.finalizing || this._state.finalized || this._state.aborted) { - callback(); - return; - } + var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - fs.lstat(task.filepath, function(err, stats) { - if (this._state.aborted) { - setImmediate(callback); - return; - } + var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - if (err) { - this._entriesCount--; + var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - /** - * @event Archiver#warning - * @type {ErrorData} - */ - this.emit('warning', err); - setImmediate(callback); - return; - } + var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; - task = this._updateQueueTaskWithStats(task, stats); + parser$3 = parser; - if (task) { - if (stats.size) { - this._fsEntriesTotalBytes += stats.size; - } + Events$2 = Events_1; - this._queue.push(task); - } + RedisConnection$1 = require$$2; - setImmediate(callback); - }.bind(this)); -}; + IORedisConnection$1 = require$$3; -/** - * Unpipes the module and ends our internal stream. - * - * @private - * @return void - */ -Archiver.prototype._shutdown = function() { - this._moduleUnpipe(); - this.end(); -}; + Scripts$1 = require$$4; -/** - * Tracks the bytes emitted by our internal stream. - * - * @private - * @param {Buffer} chunk - * @param {String} encoding - * @param {Function} callback - * @return void - */ -Archiver.prototype._transform = function(chunk, encoding, callback) { - if (chunk) { - this._pointer += chunk.length; - } + Group = (function() { + class Group { + constructor(limiterOptions = {}) { + this.deleteKey = this.deleteKey.bind(this); + this.limiterOptions = limiterOptions; + parser$3.load(this.limiterOptions, this.defaults, this); + this.Events = new Events$2(this); + this.instances = {}; + this.Bottleneck = Bottleneck_1; + this._startAutoCleanup(); + this.sharedConnection = this.connection != null; + if (this.connection == null) { + if (this.limiterOptions.datastore === "redis") { + this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); + } else if (this.limiterOptions.datastore === "ioredis") { + this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); + } + } + } - callback(null, chunk); -}; + key(key = "") { + var ref; + return (ref = this.instances[key]) != null ? ref : (() => { + var limiter; + limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { + id: `${this.id}-${key}`, + timeout: this.timeout, + connection: this.connection + })); + this.Events.trigger("created", limiter, key); + return limiter; + })(); + } -/** - * Updates and normalizes a queue task using stats data. - * - * @private - * @param {Object} task - * @param {fs.Stats} stats - * @return {Object} - */ -Archiver.prototype._updateQueueTaskWithStats = function(task, stats) { - if (stats.isFile()) { - task.data.type = 'file'; - task.data.sourceType = 'stream'; - task.source = util.lazyReadStream(task.filepath); - } else if (stats.isDirectory() && this._moduleSupports('directory')) { - task.data.name = util.trailingSlashIt(task.data.name); - task.data.type = 'directory'; - task.data.sourcePath = util.trailingSlashIt(task.filepath); - task.data.sourceType = 'buffer'; - task.source = Buffer.concat([]); - } else if (stats.isSymbolicLink() && this._moduleSupports('symlink')) { - var linkPath = fs.readlinkSync(task.filepath); - var dirName = path.dirname(task.filepath); - task.data.type = 'symlink'; - task.data.linkname = path.relative(dirName, path.resolve(dirName, linkPath)); - task.data.sourceType = 'buffer'; - task.source = Buffer.concat([]); - } else { - if (stats.isDirectory()) { - this.emit('warning', new ArchiverError('DIRECTORYNOTSUPPORTED', task.data)); - } else if (stats.isSymbolicLink()) { - this.emit('warning', new ArchiverError('SYMLINKNOTSUPPORTED', task.data)); - } else { - this.emit('warning', new ArchiverError('ENTRYNOTSUPPORTED', task.data)); - } + async deleteKey(key = "") { + var deleted, instance; + instance = this.instances[key]; + if (this.connection) { + deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)])); + } + if (instance != null) { + delete this.instances[key]; + await instance.disconnect(); + } + return (instance != null) || deleted > 0; + } - return null; - } + limiters() { + var k, ref, results, v; + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + results.push({ + key: k, + limiter: v + }); + } + return results; + } - task.data = this._normalizeEntryData(task.data, stats); + keys() { + return Object.keys(this.instances); + } - return task; -}; + async clusterKeys() { + var cursor, end, found, i, k, keys, len, next, start; + if (this.connection == null) { + return this.Promise.resolve(this.keys()); + } + keys = []; + cursor = null; + start = `b_${this.id}-`.length; + end = "_settings".length; + while (cursor !== 0) { + [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000])); + cursor = ~~next; + for (i = 0, len = found.length; i < len; i++) { + k = found[i]; + keys.push(k.slice(start, -end)); + } + } + return keys; + } -/** - * Aborts the archiving process, taking a best-effort approach, by: - * - * - removing any pending queue tasks - * - allowing any active queue workers to finish - * - detaching internal module pipes - * - ending both sides of the Transform stream - * - * It will NOT drain any remaining sources. - * - * @return {this} - */ -Archiver.prototype.abort = function() { - if (this._state.aborted || this._state.finalized) { - return this; - } + _startAutoCleanup() { + var base; + clearInterval(this.interval); + return typeof (base = (this.interval = setInterval(async() => { + var e, k, ref, results, time, v; + time = Date.now(); + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + try { + if ((await v._store.__groupCheck__(time))) { + results.push(this.deleteKey(k)); + } else { + results.push(void 0); + } + } catch (error) { + e = error; + results.push(v.Events.trigger("error", e)); + } + } + return results; + }, this.timeout / 2))).unref === "function" ? base.unref() : void 0; + } - this._abort(); + updateSettings(options = {}) { + parser$3.overwrite(options, this.defaults, this); + parser$3.overwrite(options, options, this.limiterOptions); + if (options.timeout != null) { + return this._startAutoCleanup(); + } + } - return this; -}; + disconnect(flush = true) { + var ref; + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; + } + } -/** - * Appends an input source (text string, buffer, or stream) to the instance. - * - * When the instance has received, processed, and emitted the input, the `entry` - * event is fired. - * - * @fires Archiver#entry - * @param {(Buffer|Stream|String)} source The input source. - * @param {EntryData} data See also {@link ZipEntryData} and {@link TarEntryData}. - * @return {this} - */ -Archiver.prototype.append = function(source, data) { - if (this._state.finalize || this._state.aborted) { - this.emit('error', new ArchiverError('QUEUECLOSED')); - return this; - } + } + Group.prototype.defaults = { + timeout: 1000 * 60 * 5, + connection: null, + Promise: Promise, + id: "group-key" + }; - data = this._normalizeEntryData(data); + return Group; - if (typeof data.name !== 'string' || data.name.length === 0) { - this.emit('error', new ArchiverError('ENTRYNAMEREQUIRED')); - return this; - } + }).call(commonjsGlobal); - if (data.type === 'directory' && !this._moduleSupports('directory')) { - this.emit('error', new ArchiverError('DIRECTORYNOTSUPPORTED', { name: data.name })); - return this; - } + var Group_1 = Group; - source = util.normalizeInputSource(source); + var Batcher, Events$3, parser$4; - if (Buffer.isBuffer(source)) { - data.sourceType = 'buffer'; - } else if (util.isStream(source)) { - data.sourceType = 'stream'; - } else { - this.emit('error', new ArchiverError('INPUTSTEAMBUFFERREQUIRED', { name: data.name })); - return this; - } + parser$4 = parser; - this._entriesCount++; - this._queue.push({ - data: data, - source: source - }); + Events$3 = Events_1; - return this; -}; + Batcher = (function() { + class Batcher { + constructor(options = {}) { + this.options = options; + parser$4.load(this.options, this.defaults, this); + this.Events = new Events$3(this); + this._arr = []; + this._resetPromise(); + this._lastFlush = Date.now(); + } -/** - * Appends a directory and its files, recursively, given its dirpath. - * - * @param {String} dirpath The source directory path. - * @param {String} destpath The destination path within the archive. - * @param {(EntryData|Function)} data See also [ZipEntryData]{@link ZipEntryData} and - * [TarEntryData]{@link TarEntryData}. - * @return {this} - */ -Archiver.prototype.directory = function(dirpath, destpath, data) { - if (this._state.finalize || this._state.aborted) { - this.emit('error', new ArchiverError('QUEUECLOSED')); - return this; - } + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } - if (typeof dirpath !== 'string' || dirpath.length === 0) { - this.emit('error', new ArchiverError('DIRECTORYDIRPATHREQUIRED')); - return this; - } + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); + this._resolve(); + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); + } - this._pending++; + add(data) { + var ret; + this._arr.push(data); + ret = this._promise; + if (this._arr.length === this.maxSize) { + this._flush(); + } else if ((this.maxTime != null) && this._arr.length === 1) { + this._timeout = setTimeout(() => { + return this._flush(); + }, this.maxTime); + } + return ret; + } - if (destpath === false) { - destpath = ''; - } else if (typeof destpath !== 'string'){ - destpath = dirpath; - } + } + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise + }; - var dataFunction = false; - if (typeof data === 'function') { - dataFunction = data; - data = {}; - } else if (typeof data !== 'object') { - data = {}; - } + return Batcher; - var globOptions = { - stat: true, - dot: true - }; + }).call(commonjsGlobal); - function onGlobEnd() { - this._pending--; - this._maybeFinalize(); - } + var Batcher_1 = Batcher; - function onGlobError(err) { - this.emit('error', err); - } + var require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - function onGlobMatch(match){ - globber.pause(); + var require$$8 = getCjsExportFromNamespace(version$2); - var ignoreMatch = false; - var entryData = Object.assign({}, data); - entryData.name = match.relative; - entryData.prefix = destpath; - entryData.stats = match.stat; - entryData.callback = globber.resume.bind(globber); + var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, + splice = [].splice; - try { - if (dataFunction) { - entryData = dataFunction(entryData); + NUM_PRIORITIES$1 = 10; - if (entryData === false) { - ignoreMatch = true; - } else if (typeof entryData !== 'object') { - throw new ArchiverError('DIRECTORYFUNCTIONINVALIDDATA', { dirpath: dirpath }); - } - } - } catch(e) { - this.emit('error', e); - return; - } + DEFAULT_PRIORITY$1 = 5; - if (ignoreMatch) { - globber.resume(); - return; - } + parser$5 = parser; - this._append(match.absolute, entryData); - } + Queues$1 = Queues_1; - var globber = glob(dirpath, globOptions); - globber.on('error', onGlobError.bind(this)); - globber.on('match', onGlobMatch.bind(this)); - globber.on('end', onGlobEnd.bind(this)); + Job$1 = Job_1; - return this; -}; + LocalDatastore$1 = LocalDatastore_1; -/** - * Appends a file given its filepath using a - * [lazystream]{@link https://github.com/jpommerening/node-lazystream} wrapper to - * prevent issues with open file limits. - * - * When the instance has received, processed, and emitted the file, the `entry` - * event is fired. - * - * @param {String} filepath The source filepath. - * @param {EntryData} data See also [ZipEntryData]{@link ZipEntryData} and - * [TarEntryData]{@link TarEntryData}. - * @return {this} - */ -Archiver.prototype.file = function(filepath, data) { - if (this._state.finalize || this._state.aborted) { - this.emit('error', new ArchiverError('QUEUECLOSED')); - return this; - } + RedisDatastore$1 = require$$4$1; - if (typeof filepath !== 'string' || filepath.length === 0) { - this.emit('error', new ArchiverError('FILEFILEPATHREQUIRED')); - return this; - } + Events$4 = Events_1; - this._append(filepath, data); + States$1 = States_1; - return this; -}; + Sync$1 = Sync_1; -/** - * Appends multiple files that match a glob pattern. - * - * @param {String} pattern The [glob pattern]{@link https://github.com/isaacs/minimatch} to match. - * @param {Object} options See [node-readdir-glob]{@link https://github.com/yqnn/node-readdir-glob#options}. - * @param {EntryData} data See also [ZipEntryData]{@link ZipEntryData} and - * [TarEntryData]{@link TarEntryData}. - * @return {this} - */ -Archiver.prototype.glob = function(pattern, options, data) { - this._pending++; + Bottleneck = (function() { + class Bottleneck { + constructor(options = {}, ...invalid) { + var storeInstanceOptions, storeOptions; + this._addToQueue = this._addToQueue.bind(this); + this._validateOptions(options, invalid); + parser$5.load(options, this.instanceDefaults, this); + this._queues = new Queues$1(NUM_PRIORITIES$1); + this._scheduled = {}; + this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); + this._limiter = null; + this.Events = new Events$4(this); + this._submitLock = new Sync$1("submit", this.Promise); + this._registerLock = new Sync$1("register", this.Promise); + storeOptions = parser$5.load(options, this.storeDefaults, {}); + this._store = (function() { + if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { + storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {}); + return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); + } else if (this.datastore === "local") { + storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {}); + return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); + } else { + throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); + } + }).call(this); + this._queues.on("leftzero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; + }); + this._queues.on("zero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; + }); + } - options = util.defaults(options, { - stat: true, - pattern: pattern - }); + _validateOptions(options, invalid) { + if (!((options != null) && typeof options === "object" && invalid.length === 0)) { + throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); + } + } - function onGlobEnd() { - this._pending--; - this._maybeFinalize(); - } + ready() { + return this._store.ready; + } - function onGlobError(err) { - this.emit('error', err); - } + clients() { + return this._store.clients; + } - function onGlobMatch(match){ - globber.pause(); - var entryData = Object.assign({}, data); - entryData.callback = globber.resume.bind(globber); - entryData.stats = match.stat; - entryData.name = match.relative; + channel() { + return `b_${this.id}`; + } - this._append(match.absolute, entryData); - } + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } - var globber = glob(options.cwd || '.', options); - globber.on('error', onGlobError.bind(this)); - globber.on('match', onGlobMatch.bind(this)); - globber.on('end', onGlobEnd.bind(this)); + publish(message) { + return this._store.__publish__(message); + } - return this; -}; + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } -/** - * Finalizes the instance and prevents further appending to the archive - * structure (queue will continue til drained). - * - * The `end`, `close` or `finish` events on the destination stream may fire - * right after calling this method so you should set listeners beforehand to - * properly detect stream completion. - * - * @return {Promise} - */ -Archiver.prototype.finalize = function() { - if (this._state.aborted) { - var abortedError = new ArchiverError('ABORTED'); - this.emit('error', abortedError); - return Promise.reject(abortedError); - } + chain(_limiter) { + this._limiter = _limiter; + return this; + } - if (this._state.finalize) { - var finalizingError = new ArchiverError('FINALIZING'); - this.emit('error', finalizingError); - return Promise.reject(finalizingError); - } + queued(priority) { + return this._queues.queued(priority); + } - this._state.finalize = true; + clusterQueued() { + return this._store.__queued__(); + } - if (this._pending === 0 && this._queue.idle() && this._statQueue.idle()) { - this._finalize(); - } + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } - var self = this; + running() { + return this._store.__running__(); + } - return new Promise(function(resolve, reject) { - var errored; + done() { + return this._store.__done__(); + } - self._module.on('end', function() { - if (!errored) { - resolve(); - } - }) + jobStatus(id) { + return this._states.jobStatus(id); + } - self._module.on('error', function(err) { - errored = true; - reject(err); - }) - }) -}; + jobs(status) { + return this._states.statusJobs(status); + } -/** - * Sets the module format name used for archiving. - * - * @param {String} format The name of the format. - * @return {this} - */ -Archiver.prototype.setFormat = function(format) { - if (this._format) { - this.emit('error', new ArchiverError('FORMATSET')); - return this; - } + counts() { + return this._states.statusCounts(); + } - this._format = format; + _randomIndex() { + return Math.random().toString(36).slice(2); + } - return this; -}; + check(weight = 1) { + return this._store.__check__(weight); + } -/** - * Sets the module used for archiving. - * - * @param {Function} module The function for archiver to interact with. - * @return {this} - */ -Archiver.prototype.setModule = function(module) { - if (this._state.aborted) { - this.emit('error', new ArchiverError('ABORTED')); - return this; - } + _clearGlobalState(index) { + if (this._scheduled[index] != null) { + clearTimeout(this._scheduled[index].expiration); + delete this._scheduled[index]; + return true; + } else { + return false; + } + } - if (this._state.module) { - this.emit('error', new ArchiverError('MODULESET')); - return this; - } + async _free(index, job, options, eventInfo) { + var e, running; + try { + ({running} = (await this._store.__free__(index, options.weight))); + this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); + if (running === 0 && this.empty()) { + return this.Events.trigger("idle"); + } + } catch (error1) { + e = error1; + return this.Events.trigger("error", e); + } + } - this._module = module; - this._modulePipe(); + _run(index, job, wait) { + var clearGlobalState, free, run; + job.doRun(); + clearGlobalState = this._clearGlobalState.bind(this, index); + run = this._run.bind(this, index, job); + free = this._free.bind(this, index, job); + return this._scheduled[index] = { + timeout: setTimeout(() => { + return job.doExecute(this._limiter, clearGlobalState, run, free); + }, wait), + expiration: job.options.expiration != null ? setTimeout(function() { + return job.doExpire(clearGlobalState, run, free); + }, wait + job.options.expiration) : void 0, + job: job + }; + } - return this; -}; + _drainOne(capacity) { + return this._registerLock.schedule(() => { + var args, index, next, options, queue; + if (this.queued() === 0) { + return this.Promise.resolve(null); + } + queue = this._queues.getFirst(); + ({options, args} = next = queue.first()); + if ((capacity != null) && options.weight > capacity) { + return this.Promise.resolve(null); + } + this.Events.trigger("debug", `Draining ${options.id}`, {args, options}); + index = this._randomIndex(); + return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => { + var empty; + this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options}); + if (success) { + queue.shift(); + empty = this.empty(); + if (empty) { + this.Events.trigger("empty"); + } + if (reservoir === 0) { + this.Events.trigger("depleted", empty); + } + this._run(index, next, wait); + return this.Promise.resolve(options.weight); + } else { + return this.Promise.resolve(null); + } + }); + }); + } -/** - * Appends a symlink to the instance. - * - * This does NOT interact with filesystem and is used for programmatically creating symlinks. - * - * @param {String} filepath The symlink path (within archive). - * @param {String} target The target path (within archive). - * @param {Number} mode Sets the entry permissions. - * @return {this} - */ -Archiver.prototype.symlink = function(filepath, target, mode) { - if (this._state.finalize || this._state.aborted) { - this.emit('error', new ArchiverError('QUEUECLOSED')); - return this; - } + _drainAll(capacity, total = 0) { + return this._drainOne(capacity).then((drained) => { + var newCapacity; + if (drained != null) { + newCapacity = capacity != null ? capacity - drained : capacity; + return this._drainAll(newCapacity, total + drained); + } else { + return this.Promise.resolve(total); + } + }).catch((e) => { + return this.Events.trigger("error", e); + }); + } - if (typeof filepath !== 'string' || filepath.length === 0) { - this.emit('error', new ArchiverError('SYMLINKFILEPATHREQUIRED')); - return this; - } + _dropAllQueued(message) { + return this._queues.shiftAll(function(job) { + return job.doDrop({message}); + }); + } - if (typeof target !== 'string' || target.length === 0) { - this.emit('error', new ArchiverError('SYMLINKTARGETREQUIRED', { filepath: filepath })); - return this; - } + stop(options = {}) { + var done, waitForExecuting; + options = parser$5.load(options, this.stopDefaults); + waitForExecuting = (at) => { + var finished; + finished = () => { + var counts; + counts = this._states.counts; + return (counts[0] + counts[1] + counts[2] + counts[3]) === at; + }; + return new this.Promise((resolve, reject) => { + if (finished()) { + return resolve(); + } else { + return this.on("done", () => { + if (finished()) { + this.removeAllListeners("done"); + return resolve(); + } + }); + } + }); + }; + done = options.dropWaitingJobs ? (this._run = function(index, next) { + return next.doDrop({ + message: options.dropErrorMessage + }); + }, this._drainOne = () => { + return this.Promise.resolve(null); + }, this._registerLock.schedule(() => { + return this._submitLock.schedule(() => { + var k, ref, v; + ref = this._scheduled; + for (k in ref) { + v = ref[k]; + if (this.jobStatus(v.job.options.id) === "RUNNING") { + clearTimeout(v.timeout); + clearTimeout(v.expiration); + v.job.doDrop({ + message: options.dropErrorMessage + }); + } + } + this._dropAllQueued(options.dropErrorMessage); + return waitForExecuting(0); + }); + })) : this.schedule({ + priority: NUM_PRIORITIES$1 - 1, + weight: 0 + }, () => { + return waitForExecuting(1); + }); + this._receive = function(job) { + return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); + }; + this.stop = () => { + return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); + }; + return done; + } - if (!this._moduleSupports('symlink')) { - this.emit('error', new ArchiverError('SYMLINKNOTSUPPORTED', { filepath: filepath })); - return this; - } + async _addToQueue(job) { + var args, blocked, error, options, reachedHWM, shifted, strategy; + ({args, options} = job); + try { + ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); + } catch (error1) { + error = error1; + this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error}); + job.doDrop({error}); + return false; + } + if (blocked) { + job.doDrop(); + return true; + } else if (reachedHWM) { + shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; + if (shifted != null) { + shifted.doDrop(); + } + if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { + if (shifted == null) { + job.doDrop(); + } + return reachedHWM; + } + } + job.doQueue(reachedHWM, blocked); + this._queues.push(job); + await this._drainAll(); + return reachedHWM; + } - var data = {}; - data.type = 'symlink'; - data.name = filepath.replace(/\\/g, '/'); - data.linkname = target.replace(/\\/g, '/'); - data.sourceType = 'buffer'; + _receive(job) { + if (this._states.jobStatus(job.options.id) != null) { + job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); + return false; + } else { + job.doReceive(); + return this._submitLock.schedule(this._addToQueue, job); + } + } - if (typeof mode === "number") { - data.mode = mode; - } + submit(...args) { + var cb, fn, job, options, ref, ref1, task; + if (typeof args[0] === "function") { + ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1); + options = parser$5.load({}, this.jobDefaults); + } else { + ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1); + options = parser$5.load(options, this.jobDefaults); + } + task = (...args) => { + return new this.Promise(function(resolve, reject) { + return fn(...args, function(...args) { + return (args[0] != null ? reject : resolve)(args); + }); + }); + }; + job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + job.promise.then(function(args) { + return typeof cb === "function" ? cb(...args) : void 0; + }).catch(function(args) { + if (Array.isArray(args)) { + return typeof cb === "function" ? cb(...args) : void 0; + } else { + return typeof cb === "function" ? cb(args) : void 0; + } + }); + return this._receive(job); + } - this._entriesCount++; - this._queue.push({ - data: data, - source: Buffer.concat([]) - }); + schedule(...args) { + var job, options, task; + if (typeof args[0] === "function") { + [task, ...args] = args; + options = {}; + } else { + [options, task, ...args] = args; + } + job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + this._receive(job); + return job.promise; + } - return this; -}; + wrap(fn) { + var schedule, wrapped; + schedule = this.schedule.bind(this); + wrapped = function(...args) { + return schedule(fn.bind(this), ...args); + }; + wrapped.withOptions = function(options, ...args) { + return schedule(options, fn, ...args); + }; + return wrapped; + } -/** - * Returns the current length (in bytes) that has been emitted. - * - * @return {Number} - */ -Archiver.prototype.pointer = function() { - return this._pointer; -}; + async updateSettings(options = {}) { + await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); + parser$5.overwrite(options, this.instanceDefaults, this); + return this; + } -/** - * Middleware-like helper that has yet to be fully implemented. - * - * @private - * @param {Function} plugin - * @return {this} - */ -Archiver.prototype.use = function(plugin) { - this._streams.push(plugin); - return this; -}; + currentReservoir() { + return this._store.__currentReservoir__(); + } -module.exports = Archiver; + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } -/** - * @typedef {Object} CoreOptions - * @global - * @property {Number} [statConcurrency=4] Sets the number of workers used to - * process the internal fs stat queue. - */ + } + Bottleneck.default = Bottleneck; -/** - * @typedef {Object} TransformOptions - * @property {Boolean} [allowHalfOpen=true] If set to false, then the stream - * will automatically end the readable side when the writable side ends and vice - * versa. - * @property {Boolean} [readableObjectMode=false] Sets objectMode for readable - * side of the stream. Has no effect if objectMode is true. - * @property {Boolean} [writableObjectMode=false] Sets objectMode for writable - * side of the stream. Has no effect if objectMode is true. - * @property {Boolean} [decodeStrings=true] Whether or not to decode strings - * into Buffers before passing them to _write(). `Writable` - * @property {String} [encoding=NULL] If specified, then buffers will be decoded - * to strings using the specified encoding. `Readable` - * @property {Number} [highWaterMark=16kb] The maximum number of bytes to store - * in the internal buffer before ceasing to read from the underlying resource. - * `Readable` `Writable` - * @property {Boolean} [objectMode=false] Whether this stream should behave as a - * stream of objects. Meaning that stream.read(n) returns a single value instead - * of a Buffer of size n. `Readable` `Writable` - */ + Bottleneck.Events = Events$4; -/** - * @typedef {Object} EntryData - * @property {String} name Sets the entry name including internal path. - * @property {(String|Date)} [date=NOW()] Sets the entry date. - * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions. - * @property {String} [prefix] Sets a path prefix for the entry name. Useful - * when working with methods like `directory` or `glob`. - * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing - * for reduction of fs stat calls when stat data is already known. - */ + Bottleneck.version = Bottleneck.prototype.version = require$$8.version; -/** - * @typedef {Object} ErrorData - * @property {String} message The message of the error. - * @property {String} code The error code assigned to this error. - * @property {String} data Additional data provided for reporting or debugging (where available). - */ + Bottleneck.strategy = Bottleneck.prototype.strategy = { + LEAK: 1, + OVERFLOW: 2, + OVERFLOW_PRIORITY: 4, + BLOCK: 3 + }; -/** - * @typedef {Object} ProgressData - * @property {Object} entries - * @property {Number} entries.total Number of entries that have been appended. - * @property {Number} entries.processed Number of entries that have been processed. - * @property {Object} fs - * @property {Number} fs.totalBytes Number of bytes that have been appended. Calculated asynchronously and might not be accurate: it growth while entries are added. (based on fs.Stats) - * @property {Number} fs.processedBytes Number of bytes that have been processed. (based on fs.Stats) - */ + Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; + Bottleneck.Group = Bottleneck.prototype.Group = Group_1; -/***/ }), + Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; -/***/ 13143: -/***/ ((module, exports, __nccwpck_require__) => { + Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; -/** - * Archiver Core - * - * @ignore - * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} - * @copyright (c) 2012-2014 Chris Talkington, contributors. - */ + Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; -var util = __nccwpck_require__(73837); + Bottleneck.prototype.jobDefaults = { + priority: DEFAULT_PRIORITY$1, + weight: 1, + expiration: null, + id: "" + }; -const ERROR_CODES = { - 'ABORTED': 'archive was aborted', - 'DIRECTORYDIRPATHREQUIRED': 'diretory dirpath argument must be a non-empty string value', - 'DIRECTORYFUNCTIONINVALIDDATA': 'invalid data returned by directory custom data function', - 'ENTRYNAMEREQUIRED': 'entry name must be a non-empty string value', - 'FILEFILEPATHREQUIRED': 'file filepath argument must be a non-empty string value', - 'FINALIZING': 'archive already finalizing', - 'QUEUECLOSED': 'queue closed', - 'NOENDMETHOD': 'no suitable finalize/end method defined by module', - 'DIRECTORYNOTSUPPORTED': 'support for directory entries not defined by module', - 'FORMATSET': 'archive format already set', - 'INPUTSTEAMBUFFERREQUIRED': 'input source must be valid Stream or Buffer instance', - 'MODULESET': 'module already set', - 'SYMLINKNOTSUPPORTED': 'support for symlink entries not defined by module', - 'SYMLINKFILEPATHREQUIRED': 'symlink filepath argument must be a non-empty string value', - 'SYMLINKTARGETREQUIRED': 'symlink target argument must be a non-empty string value', - 'ENTRYNOTSUPPORTED': 'entry not supported' -}; - -function ArchiverError(code, data) { - Error.captureStackTrace(this, this.constructor); - //this.name = this.constructor.name; - this.message = ERROR_CODES[code] || code; - this.code = code; - this.data = data; -} - -util.inherits(ArchiverError, Error); - -exports = module.exports = ArchiverError; - -/***/ }), + Bottleneck.prototype.storeDefaults = { + maxConcurrent: null, + minTime: 0, + highWater: null, + strategy: Bottleneck.prototype.strategy.LEAK, + penalty: null, + reservoir: null, + reservoirRefreshInterval: null, + reservoirRefreshAmount: null, + reservoirIncreaseInterval: null, + reservoirIncreaseAmount: null, + reservoirIncreaseMaximum: null + }; -/***/ 99827: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + Bottleneck.prototype.localStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 250 + }; -/** - * JSON Format Plugin - * - * @module plugins/json - * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} - * @copyright (c) 2012-2014 Chris Talkington, contributors. - */ -var inherits = (__nccwpck_require__(73837).inherits); -var Transform = (__nccwpck_require__(51642).Transform); + Bottleneck.prototype.redisStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 5000, + clientTimeout: 10000, + Redis: null, + clientOptions: {}, + clusterNodes: null, + clearDatastore: false, + connection: null + }; -var crc32 = __nccwpck_require__(84794); -var util = __nccwpck_require__(82072); + Bottleneck.prototype.instanceDefaults = { + datastore: "local", + connection: null, + id: "", + rejectOnDrop: true, + trackDoneStatus: false, + Promise: Promise + }; -/** - * @constructor - * @param {(JsonOptions|TransformOptions)} options - */ -var Json = function(options) { - if (!(this instanceof Json)) { - return new Json(options); - } + Bottleneck.prototype.stopDefaults = { + enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", + dropWaitingJobs: true, + dropErrorMessage: "This limiter has been stopped." + }; - options = this.options = util.defaults(options, {}); + return Bottleneck; - Transform.call(this, options); + }).call(commonjsGlobal); - this.supports = { - directory: true, - symlink: true - }; + var Bottleneck_1 = Bottleneck; - this.files = []; -}; + var lib = Bottleneck_1; -inherits(Json, Transform); + return lib; -/** - * [_transform description] - * - * @private - * @param {Buffer} chunk - * @param {String} encoding - * @param {Function} callback - * @return void - */ -Json.prototype._transform = function(chunk, encoding, callback) { - callback(null, chunk); -}; +}))); -/** - * [_writeStringified description] - * - * @private - * @return void - */ -Json.prototype._writeStringified = function() { - var fileString = JSON.stringify(this.files); - this.write(fileString); -}; -/** - * [append description] - * - * @param {(Buffer|Stream)} source - * @param {EntryData} data - * @param {Function} callback - * @return void - */ -Json.prototype.append = function(source, data, callback) { - var self = this; +/***/ }), - data.crc32 = 0; +/***/ 33717: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function onend(err, sourceBuffer) { - if (err) { - callback(err); - return; - } +var balanced = __nccwpck_require__(9417); - data.size = sourceBuffer.length || 0; - data.crc32 = crc32.unsigned(sourceBuffer); +module.exports = expandTop; - self.files.push(data); +var escSlash = '\0SLASH'+Math.random()+'\0'; +var escOpen = '\0OPEN'+Math.random()+'\0'; +var escClose = '\0CLOSE'+Math.random()+'\0'; +var escComma = '\0COMMA'+Math.random()+'\0'; +var escPeriod = '\0PERIOD'+Math.random()+'\0'; - callback(null, data); - } +function numeric(str) { + return parseInt(str, 10) == str + ? parseInt(str, 10) + : str.charCodeAt(0); +} - if (data.sourceType === 'buffer') { - onend(null, source); - } else if (data.sourceType === 'stream') { - util.collectStream(source, onend); - } -}; +function escapeBraces(str) { + return str.split('\\\\').join(escSlash) + .split('\\{').join(escOpen) + .split('\\}').join(escClose) + .split('\\,').join(escComma) + .split('\\.').join(escPeriod); +} -/** - * [finalize description] - * - * @return void - */ -Json.prototype.finalize = function() { - this._writeStringified(); - this.end(); -}; +function unescapeBraces(str) { + return str.split(escSlash).join('\\') + .split(escOpen).join('{') + .split(escClose).join('}') + .split(escComma).join(',') + .split(escPeriod).join('.'); +} -module.exports = Json; -/** - * @typedef {Object} JsonOptions - * @global - */ +// Basically just str.split(","), but handling cases +// where we have nested braced sections, which should be +// treated as individual members, like {a,{b,c},d} +function parseCommaParts(str) { + if (!str) + return ['']; + var parts = []; + var m = balanced('{', '}', str); -/***/ }), + if (!m) + return str.split(','); -/***/ 33614: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var pre = m.pre; + var body = m.body; + var post = m.post; + var p = pre.split(','); -/** - * TAR Format Plugin - * - * @module plugins/tar - * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} - * @copyright (c) 2012-2014 Chris Talkington, contributors. - */ -var zlib = __nccwpck_require__(59796); + p[p.length-1] += '{' + body + '}'; + var postParts = parseCommaParts(post); + if (post.length) { + p[p.length-1] += postParts.shift(); + p.push.apply(p, postParts); + } -var engine = __nccwpck_require__(2283); -var util = __nccwpck_require__(82072); + parts.push.apply(parts, p); -/** - * @constructor - * @param {TarOptions} options - */ -var Tar = function(options) { - if (!(this instanceof Tar)) { - return new Tar(options); - } + return parts; +} - options = this.options = util.defaults(options, { - gzip: false - }); +function expandTop(str) { + if (!str) + return []; - if (typeof options.gzipOptions !== 'object') { - options.gzipOptions = {}; + // I don't know why Bash 4.3 does this, but it does. + // Anything starting with {} will have the first two bytes preserved + // but *only* at the top level, so {},a}b will not expand to anything, + // but a{},b}c will be expanded to [a}c,abc]. + // One could argue that this is a bug in Bash, but since the goal of + // this module is to match Bash's rules, we escape a leading {} + if (str.substr(0, 2) === '{}') { + str = '\\{\\}' + str.substr(2); } - this.supports = { - directory: true, - symlink: true - }; + return expand(escapeBraces(str), true).map(unescapeBraces); +} - this.engine = engine.pack(options); - this.compressor = false; +function embrace(str) { + return '{' + str + '}'; +} +function isPadded(el) { + return /^-?0\d/.test(el); +} - if (options.gzip) { - this.compressor = zlib.createGzip(options.gzipOptions); - this.compressor.on('error', this._onCompressorError.bind(this)); - } -}; +function lte(i, y) { + return i <= y; +} +function gte(i, y) { + return i >= y; +} -/** - * [_onCompressorError description] - * - * @private - * @param {Error} err - * @return void - */ -Tar.prototype._onCompressorError = function(err) { - this.engine.emit('error', err); -}; +function expand(str, isTop) { + var expansions = []; -/** - * [append description] - * - * @param {(Buffer|Stream)} source - * @param {TarEntryData} data - * @param {Function} callback - * @return void - */ -Tar.prototype.append = function(source, data, callback) { - var self = this; + var m = balanced('{', '}', str); + if (!m) return [str]; - data.mtime = data.date; + // no need to expand pre, since it is guaranteed to be free of brace-sets + var pre = m.pre; + var post = m.post.length + ? expand(m.post, false) + : ['']; - function append(err, sourceBuffer) { - if (err) { - callback(err); - return; + if (/\$$/.test(m.pre)) { + for (var k = 0; k < post.length; k++) { + var expansion = pre+ '{' + m.body + '}' + post[k]; + expansions.push(expansion); + } + } else { + var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); + var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); + var isSequence = isNumericSequence || isAlphaSequence; + var isOptions = m.body.indexOf(',') >= 0; + if (!isSequence && !isOptions) { + // {a},b} + if (m.post.match(/,.*\}/)) { + str = m.pre + '{' + m.body + escClose + m.post; + return expand(str); + } + return [str]; } - self.engine.entry(data, sourceBuffer, function(err) { - callback(err, data); - }); - } + var n; + if (isSequence) { + n = m.body.split(/\.\./); + } else { + n = parseCommaParts(m.body); + if (n.length === 1) { + // x{{a,b}}y ==> x{a}y x{b}y + n = expand(n[0], false).map(embrace); + if (n.length === 1) { + return post.map(function(p) { + return m.pre + n[0] + p; + }); + } + } + } - if (data.sourceType === 'buffer') { - append(null, source); - } else if (data.sourceType === 'stream' && data.stats) { - data.size = data.stats.size; + // at this point, n is the parts, and we know it's not a comma set + // with a single entry. + var N; - var entry = self.engine.entry(data, function(err) { - callback(err, data); - }); + if (isSequence) { + var x = numeric(n[0]); + var y = numeric(n[1]); + var width = Math.max(n[0].length, n[1].length) + var incr = n.length == 3 + ? Math.abs(numeric(n[2])) + : 1; + var test = lte; + var reverse = y < x; + if (reverse) { + incr *= -1; + test = gte; + } + var pad = n.some(isPadded); - source.pipe(entry); - } else if (data.sourceType === 'stream') { - util.collectStream(source, append); - } -}; + N = []; -/** - * [finalize description] - * - * @return void - */ -Tar.prototype.finalize = function() { - this.engine.finalize(); -}; + for (var i = x; test(i, y); i += incr) { + var c; + if (isAlphaSequence) { + c = String.fromCharCode(i); + if (c === '\\') + c = ''; + } else { + c = String(i); + if (pad) { + var need = width - c.length; + if (need > 0) { + var z = new Array(need + 1).join('0'); + if (i < 0) + c = '-' + z + c.slice(1); + else + c = z + c; + } + } + } + N.push(c); + } + } else { + N = []; -/** - * [on description] - * - * @return this.engine - */ -Tar.prototype.on = function() { - return this.engine.on.apply(this.engine, arguments); -}; + for (var j = 0; j < n.length; j++) { + N.push.apply(N, expand(n[j], false)); + } + } -/** - * [pipe description] - * - * @param {String} destination - * @param {Object} options - * @return this.engine - */ -Tar.prototype.pipe = function(destination, options) { - if (this.compressor) { - return this.engine.pipe.apply(this.engine, [this.compressor]).pipe(destination, options); - } else { - return this.engine.pipe.apply(this.engine, arguments); + for (var j = 0; j < N.length; j++) { + for (var k = 0; k < post.length; k++) { + var expansion = pre + N[j] + post[k]; + if (!isTop || isSequence || expansion) + expansions.push(expansion); + } + } } -}; -/** - * [unpipe description] - * - * @return this.engine - */ -Tar.prototype.unpipe = function() { - if (this.compressor) { - return this.compressor.unpipe.apply(this.compressor, arguments); - } else { - return this.engine.unpipe.apply(this.engine, arguments); - } -}; + return expansions; +} -module.exports = Tar; -/** - * @typedef {Object} TarOptions - * @global - * @property {Boolean} [gzip=false] Compress the tar archive using gzip. - * @property {Object} [gzipOptions] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} - * to control compression. - * @property {*} [*] See [tar-stream]{@link https://github.com/mafintosh/tar-stream} documentation for additional properties. - */ -/** - * @typedef {Object} TarEntryData - * @global - * @property {String} name Sets the entry name including internal path. - * @property {(String|Date)} [date=NOW()] Sets the entry date. - * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions. - * @property {String} [prefix] Sets a path prefix for the entry name. Useful - * when working with methods like `directory` or `glob`. - * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing - * for reduction of fs stat calls when stat data is already known. - */ +/***/ }), -/** - * TarStream Module - * @external TarStream - * @see {@link https://github.com/mafintosh/tar-stream} - */ +/***/ 51590: +/***/ ((module) => { +module.exports = Buffers; -/***/ }), +function Buffers (bufs) { + if (!(this instanceof Buffers)) return new Buffers(bufs); + this.buffers = bufs || []; + this.length = this.buffers.reduce(function (size, buf) { + return size + buf.length + }, 0); +} -/***/ 8987: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +Buffers.prototype.push = function () { + for (var i = 0; i < arguments.length; i++) { + if (!Buffer.isBuffer(arguments[i])) { + throw new TypeError('Tried to push a non-buffer'); + } + } + + for (var i = 0; i < arguments.length; i++) { + var buf = arguments[i]; + this.buffers.push(buf); + this.length += buf.length; + } + return this.length; +}; -/** - * ZIP Format Plugin - * - * @module plugins/zip - * @license [MIT]{@link https://github.com/archiverjs/node-archiver/blob/master/LICENSE} - * @copyright (c) 2012-2014 Chris Talkington, contributors. - */ -var engine = __nccwpck_require__(86454); -var util = __nccwpck_require__(82072); - -/** - * @constructor - * @param {ZipOptions} [options] - * @param {String} [options.comment] Sets the zip archive comment. - * @param {Boolean} [options.forceLocalTime=false] Forces the archive to contain local file times instead of UTC. - * @param {Boolean} [options.forceZip64=false] Forces the archive to contain ZIP64 headers. - * @param {Boolean} [options.namePrependSlash=false] Prepends a forward slash to archive file paths. - * @param {Boolean} [options.store=false] Sets the compression method to STORE. - * @param {Object} [options.zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} - */ -var Zip = function(options) { - if (!(this instanceof Zip)) { - return new Zip(options); - } - - options = this.options = util.defaults(options, { - comment: '', - forceUTC: false, - namePrependSlash: false, - store: false - }); - - this.supports = { - directory: true, - symlink: true - }; - - this.engine = new engine(options); -}; - -/** - * @param {(Buffer|Stream)} source - * @param {ZipEntryData} data - * @param {String} data.name Sets the entry name including internal path. - * @param {(String|Date)} [data.date=NOW()] Sets the entry date. - * @param {Number} [data.mode=D:0755/F:0644] Sets the entry permissions. - * @param {String} [data.prefix] Sets a path prefix for the entry name. Useful - * when working with methods like `directory` or `glob`. - * @param {fs.Stats} [data.stats] Sets the fs stat data for this entry allowing - * for reduction of fs stat calls when stat data is already known. - * @param {Boolean} [data.store=ZipOptions.store] Sets the compression method to STORE. - * @param {Function} callback - * @return void - */ -Zip.prototype.append = function(source, data, callback) { - this.engine.entry(source, data, callback); +Buffers.prototype.unshift = function () { + for (var i = 0; i < arguments.length; i++) { + if (!Buffer.isBuffer(arguments[i])) { + throw new TypeError('Tried to unshift a non-buffer'); + } + } + + for (var i = 0; i < arguments.length; i++) { + var buf = arguments[i]; + this.buffers.unshift(buf); + this.length += buf.length; + } + return this.length; }; -/** - * @return void - */ -Zip.prototype.finalize = function() { - this.engine.finalize(); +Buffers.prototype.copy = function (dst, dStart, start, end) { + return this.slice(start, end).copy(dst, dStart, 0, end - start); }; -/** - * @return this.engine - */ -Zip.prototype.on = function() { - return this.engine.on.apply(this.engine, arguments); +Buffers.prototype.splice = function (i, howMany) { + var buffers = this.buffers; + var index = i >= 0 ? i : this.length - i; + var reps = [].slice.call(arguments, 2); + + if (howMany === undefined) { + howMany = this.length - index; + } + else if (howMany > this.length - index) { + howMany = this.length - index; + } + + for (var i = 0; i < reps.length; i++) { + this.length += reps[i].length; + } + + var removed = new Buffers(); + var bytes = 0; + + var startBytes = 0; + for ( + var ii = 0; + ii < buffers.length && startBytes + buffers[ii].length < index; + ii ++ + ) { startBytes += buffers[ii].length } + + if (index - startBytes > 0) { + var start = index - startBytes; + + if (start + howMany < buffers[ii].length) { + removed.push(buffers[ii].slice(start, start + howMany)); + + var orig = buffers[ii]; + //var buf = new Buffer(orig.length - howMany); + var buf0 = new Buffer(start); + for (var i = 0; i < start; i++) { + buf0[i] = orig[i]; + } + + var buf1 = new Buffer(orig.length - start - howMany); + for (var i = start + howMany; i < orig.length; i++) { + buf1[ i - howMany - start ] = orig[i] + } + + if (reps.length > 0) { + var reps_ = reps.slice(); + reps_.unshift(buf0); + reps_.push(buf1); + buffers.splice.apply(buffers, [ ii, 1 ].concat(reps_)); + ii += reps_.length; + reps = []; + } + else { + buffers.splice(ii, 1, buf0, buf1); + //buffers[ii] = buf; + ii += 2; + } + } + else { + removed.push(buffers[ii].slice(start)); + buffers[ii] = buffers[ii].slice(0, start); + ii ++; + } + } + + if (reps.length > 0) { + buffers.splice.apply(buffers, [ ii, 0 ].concat(reps)); + ii += reps.length; + } + + while (removed.length < howMany) { + var buf = buffers[ii]; + var len = buf.length; + var take = Math.min(len, howMany - removed.length); + + if (take === len) { + removed.push(buf); + buffers.splice(ii, 1); + } + else { + removed.push(buf.slice(0, take)); + buffers[ii] = buffers[ii].slice(take); + } + } + + this.length -= removed.length; + + return removed; }; - -/** - * @return this.engine - */ -Zip.prototype.pipe = function() { - return this.engine.pipe.apply(this.engine, arguments); + +Buffers.prototype.slice = function (i, j) { + var buffers = this.buffers; + if (j === undefined) j = this.length; + if (i === undefined) i = 0; + + if (j > this.length) j = this.length; + + var startBytes = 0; + for ( + var si = 0; + si < buffers.length && startBytes + buffers[si].length <= i; + si ++ + ) { startBytes += buffers[si].length } + + var target = new Buffer(j - i); + + var ti = 0; + for (var ii = si; ti < j - i && ii < buffers.length; ii++) { + var len = buffers[ii].length; + + var start = ti === 0 ? i - startBytes : 0; + var end = ti + len >= j - i + ? Math.min(start + (j - i) - ti, len) + : len + ; + + buffers[ii].copy(target, ti, start, end); + ti += end - start; + } + + return target; }; -/** - * @return this.engine - */ -Zip.prototype.unpipe = function() { - return this.engine.unpipe.apply(this.engine, arguments); +Buffers.prototype.pos = function (i) { + if (i < 0 || i >= this.length) throw new Error('oob'); + var l = i, bi = 0, bu = null; + for (;;) { + bu = this.buffers[bi]; + if (l < bu.length) { + return {buf: bi, offset: l}; + } else { + l -= bu.length; + } + bi++; + } }; -module.exports = Zip; - -/** - * @typedef {Object} ZipOptions - * @global - * @property {String} [comment] Sets the zip archive comment. - * @property {Boolean} [forceLocalTime=false] Forces the archive to contain local file times instead of UTC. - * @property {Boolean} [forceZip64=false] Forces the archive to contain ZIP64 headers. - * @prpperty {Boolean} [namePrependSlash=false] Prepends a forward slash to archive file paths. - * @property {Boolean} [store=false] Sets the compression method to STORE. - * @property {Object} [zlib] Passed to [zlib]{@link https://nodejs.org/api/zlib.html#zlib_class_options} - * to control compression. - * @property {*} [*] See [zip-stream]{@link https://archiverjs.com/zip-stream/ZipStream.html} documentation for current list of properties. - */ - -/** - * @typedef {Object} ZipEntryData - * @global - * @property {String} name Sets the entry name including internal path. - * @property {(String|Date)} [date=NOW()] Sets the entry date. - * @property {Number} [mode=D:0755/F:0644] Sets the entry permissions. - * @property {Boolean} [namePrependSlash=ZipOptions.namePrependSlash] Prepends a forward slash to archive file paths. - * @property {String} [prefix] Sets a path prefix for the entry name. Useful - * when working with methods like `directory` or `glob`. - * @property {fs.Stats} [stats] Sets the fs stat data for this entry allowing - * for reduction of fs stat calls when stat data is already known. - * @property {Boolean} [store=ZipOptions.store] Sets the compression method to STORE. - */ - -/** - * ZipStream Module - * @external ZipStream - * @see {@link https://www.archiverjs.com/zip-stream/ZipStream.html} - */ - - -/***/ }), +Buffers.prototype.get = function get (i) { + var pos = this.pos(i); -/***/ 57888: -/***/ (function(__unused_webpack_module, exports) { + return this.buffers[pos.buf].get(pos.offset); +}; -(function (global, factory) { - true ? factory(exports) : - 0; -})(this, (function (exports) { 'use strict'; +Buffers.prototype.set = function set (i, b) { + var pos = this.pos(i); - /** - * Creates a continuation function with some arguments already applied. - * - * Useful as a shorthand when combined with other control flow functions. Any - * arguments passed to the returned function are added to the arguments - * originally passed to apply. - * - * @name apply - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {Function} fn - The function you want to eventually apply all - * arguments to. Invokes with (arguments...). - * @param {...*} arguments... - Any number of arguments to automatically apply - * when the continuation is called. - * @returns {Function} the partially-applied function - * @example - * - * // using apply - * async.parallel([ - * async.apply(fs.writeFile, 'testfile1', 'test1'), - * async.apply(fs.writeFile, 'testfile2', 'test2') - * ]); - * - * - * // the same process without using apply - * async.parallel([ - * function(callback) { - * fs.writeFile('testfile1', 'test1', callback); - * }, - * function(callback) { - * fs.writeFile('testfile2', 'test2', callback); - * } - * ]); - * - * // It's possible to pass any number of additional arguments when calling the - * // continuation: - * - * node> var fn = async.apply(sys.puts, 'one'); - * node> fn('two', 'three'); - * one - * two - * three - */ - function apply(fn, ...args) { - return (...callArgs) => fn(...args,...callArgs); - } + return this.buffers[pos.buf].set(pos.offset, b); +}; - function initialParams (fn) { - return function (...args/*, callback*/) { - var callback = args.pop(); - return fn.call(this, args, callback); - }; +Buffers.prototype.indexOf = function (needle, offset) { + if ("string" === typeof needle) { + needle = new Buffer(needle); + } else if (needle instanceof Buffer) { + // already a buffer + } else { + throw new Error('Invalid type for a search string'); } - /* istanbul ignore file */ - - var hasQueueMicrotask = typeof queueMicrotask === 'function' && queueMicrotask; - var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; - var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; - - function fallback(fn) { - setTimeout(fn, 0); + if (!needle.length) { + return 0; } - function wrap(defer) { - return (fn, ...args) => defer(() => fn(...args)); + if (!this.length) { + return -1; } - var _defer$1; + var i = 0, j = 0, match = 0, mstart, pos = 0; - if (hasQueueMicrotask) { - _defer$1 = queueMicrotask; - } else if (hasSetImmediate) { - _defer$1 = setImmediate; - } else if (hasNextTick) { - _defer$1 = process.nextTick; - } else { - _defer$1 = fallback; + // start search from a particular point in the virtual buffer + if (offset) { + var p = this.pos(offset); + i = p.buf; + j = p.offset; + pos = offset; } - var setImmediate$1 = wrap(_defer$1); + // for each character in virtual buffer + for (;;) { + while (j >= this.buffers[i].length) { + j = 0; + i++; - /** - * Take a sync function and make it async, passing its return value to a - * callback. This is useful for plugging sync functions into a waterfall, - * series, or other async functions. Any arguments passed to the generated - * function will be passed to the wrapped function (except for the final - * callback argument). Errors thrown will be passed to the callback. - * - * If the function passed to `asyncify` returns a Promise, that promises's - * resolved/rejected state will be used to call the callback, rather than simply - * the synchronous return value. - * - * This also means you can asyncify ES2017 `async` functions. - * - * @name asyncify - * @static - * @memberOf module:Utils - * @method - * @alias wrapSync - * @category Util - * @param {Function} func - The synchronous function, or Promise-returning - * function to convert to an {@link AsyncFunction}. - * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be - * invoked with `(args..., callback)`. - * @example - * - * // passing a regular synchronous function - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(JSON.parse), - * function (data, next) { - * // data is the result of parsing the text. - * // If there was a parsing error, it would have been caught. - * } - * ], callback); - * - * // passing a function returning a promise - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(function (contents) { - * return db.model.create(contents); - * }), - * function (model, next) { - * // `model` is the instantiated model object. - * // If there was an error, this function would be skipped. - * } - * ], callback); - * - * // es2017 example, though `asyncify` is not needed if your JS environment - * // supports async functions out of the box - * var q = async.queue(async.asyncify(async function(file) { - * var intermediateStep = await processFile(file); - * return await somePromise(intermediateStep) - * })); - * - * q.push(files); - */ - function asyncify(func) { - if (isAsync(func)) { - return function (...args/*, callback*/) { - const callback = args.pop(); - const promise = func.apply(this, args); - return handlePromise(promise, callback) + if (i >= this.buffers.length) { + // search string not found + return -1; } } - return initialParams(function (args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); + var char = this.buffers[i][j]; + + if (char == needle[match]) { + // keep track where match started + if (match == 0) { + mstart = { + i: i, + j: j, + pos: pos + }; } - // if result is Promise object - if (result && typeof result.then === 'function') { - return handlePromise(result, callback) - } else { - callback(null, result); + match++; + if (match == needle.length) { + // full match + return mstart.pos; } - }); - } + } else if (match != 0) { + // a partial match ended, go back to match starting position + // this will continue the search at the next character + i = mstart.i; + j = mstart.j; + pos = mstart.pos; + match = 0; + } - function handlePromise(promise, callback) { - return promise.then(value => { - invokeCallback(callback, null, value); - }, err => { - invokeCallback(callback, err && (err instanceof Error || err.message) ? err : new Error(err)); - }); + j++; + pos++; } +}; - function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (err) { - setImmediate$1(e => { throw e }, err); - } - } +Buffers.prototype.toBuffer = function() { + return this.slice(); +} - function isAsync(fn) { - return fn[Symbol.toStringTag] === 'AsyncFunction'; - } +Buffers.prototype.toString = function(encoding, start, end) { + return this.slice(start, end).toString(encoding); +} - function isAsyncGenerator(fn) { - return fn[Symbol.toStringTag] === 'AsyncGenerator'; - } - function isAsyncIterable(obj) { - return typeof obj[Symbol.asyncIterator] === 'function'; - } +/***/ }), - function wrapAsync(asyncFn) { - if (typeof asyncFn !== 'function') throw new Error('expected a function') - return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; - } +/***/ 46533: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // conditionally promisify a function. - // only return a promise if a callback is omitted - function awaitify (asyncFn, arity) { - if (!arity) arity = asyncFn.length; - if (!arity) throw new Error('arity is undefined') - function awaitable (...args) { - if (typeof args[arity - 1] === 'function') { - return asyncFn.apply(this, args) - } +var Traverse = __nccwpck_require__(8588); +var EventEmitter = (__nccwpck_require__(82361).EventEmitter); - return new Promise((resolve, reject) => { - args[arity - 1] = (err, ...cbArgs) => { - if (err) return reject(err) - resolve(cbArgs.length > 1 ? cbArgs : cbArgs[0]); - }; - asyncFn.apply(this, args); - }) - } +module.exports = Chainsaw; +function Chainsaw (builder) { + var saw = Chainsaw.saw(builder, {}); + var r = builder.call(saw.handlers, saw); + if (r !== undefined) saw.handlers = r; + saw.record(); + return saw.chain(); +}; - return awaitable - } +Chainsaw.light = function ChainsawLight (builder) { + var saw = Chainsaw.saw(builder, {}); + var r = builder.call(saw.handlers, saw); + if (r !== undefined) saw.handlers = r; + return saw.chain(); +}; - function applyEach$1 (eachfn) { - return function applyEach(fns, ...callArgs) { - const go = awaitify(function (callback) { - var that = this; - return eachfn(fns, (fn, cb) => { - wrapAsync(fn).apply(that, callArgs.concat(cb)); - }, callback); - }); - return go; - }; - } +Chainsaw.saw = function (builder, handlers) { + var saw = new EventEmitter; + saw.handlers = handlers; + saw.actions = []; - function _asyncMap(eachfn, arr, iteratee, callback) { - arr = arr || []; - var results = []; - var counter = 0; - var _iteratee = wrapAsync(iteratee); + saw.chain = function () { + var ch = Traverse(saw.handlers).map(function (node) { + if (this.isRoot) return node; + var ps = this.path; - return eachfn(arr, (value, _, iterCb) => { - var index = counter++; - _iteratee(value, (err, v) => { - results[index] = v; - iterCb(err); - }); - }, err => { - callback(err, results); + if (typeof node === 'function') { + this.update(function () { + saw.actions.push({ + path : ps, + args : [].slice.call(arguments) + }); + return ch; + }); + } }); - } - function isArrayLike(value) { - return value && - typeof value.length === 'number' && - value.length >= 0 && - value.length % 1 === 0; - } + process.nextTick(function () { + saw.emit('begin'); + saw.next(); + }); - // A temporary value used to identify if the loop should be broken. - // See #1064, #1293 - const breakLoop = {}; - var breakLoop$1 = breakLoop; + return ch; + }; - function once(fn) { - function wrapper (...args) { - if (fn === null) return; - var callFn = fn; - fn = null; - callFn.apply(this, args); - } - Object.assign(wrapper, fn); - return wrapper - } + saw.pop = function () { + return saw.actions.shift(); + }; - function getIterator (coll) { - return coll[Symbol.iterator] && coll[Symbol.iterator](); - } + saw.next = function () { + var action = saw.pop(); - function createArrayIterator(coll) { - var i = -1; - var len = coll.length; - return function next() { - return ++i < len ? {value: coll[i], key: i} : null; + if (!action) { + saw.emit('end'); } - } + else if (!action.trap) { + var node = saw.handlers; + action.path.forEach(function (key) { node = node[key] }); + node.apply(saw.handlers, action.args); + } + }; - function createES2015Iterator(iterator) { - var i = -1; - return function next() { - var item = iterator.next(); - if (item.done) - return null; - i++; - return {value: item.value, key: i}; + saw.nest = function (cb) { + var args = [].slice.call(arguments, 1); + var autonext = true; + + if (typeof cb === 'boolean') { + var autonext = cb; + cb = args.shift(); } - } - function createObjectIterator(obj) { - var okeys = obj ? Object.keys(obj) : []; - var i = -1; - var len = okeys.length; - return function next() { - var key = okeys[++i]; - if (key === '__proto__') { - return next(); - } - return i < len ? {value: obj[key], key} : null; - }; - } + var s = Chainsaw.saw(builder, {}); + var r = builder.call(s.handlers, s); - function createIterator(coll) { - if (isArrayLike(coll)) { - return createArrayIterator(coll); + if (r !== undefined) s.handlers = r; + + // If we are recording... + if ("undefined" !== typeof saw.step) { + // ... our children should, too + s.record(); } - var iterator = getIterator(coll); - return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); - } + cb.apply(s.chain(), args); + if (autonext !== false) s.on('end', saw.next); + }; - function onlyOnce(fn) { - return function (...args) { - if (fn === null) throw new Error("Callback was already called."); - var callFn = fn; - fn = null; - callFn.apply(this, args); + saw.record = function () { + upgradeChainsaw(saw); + }; + + ['trap', 'down', 'jump'].forEach(function (method) { + saw[method] = function () { + throw new Error("To use the trap, down and jump features, please "+ + "call record() first to start recording actions."); }; - } + }); - // for async generators - function asyncEachOfLimit(generator, limit, iteratee, callback) { - let done = false; - let canceled = false; - let awaiting = false; - let running = 0; - let idx = 0; + return saw; +}; - function replenish() { - //console.log('replenish') - if (running >= limit || awaiting || done) return - //console.log('replenish awaiting') - awaiting = true; - generator.next().then(({value, done: iterDone}) => { - //console.log('got value', value) - if (canceled || done) return - awaiting = false; - if (iterDone) { - done = true; - if (running <= 0) { - //console.log('done nextCb') - callback(null); - } - return; - } - running++; - iteratee(value, idx, iterateeCallback); - idx++; - replenish(); - }).catch(handleError); - } +function upgradeChainsaw(saw) { + saw.step = 0; - function iterateeCallback(err, result) { - //console.log('iterateeCallback') - running -= 1; - if (canceled) return - if (err) return handleError(err) + // override pop + saw.pop = function () { + return saw.actions[saw.step++]; + }; - if (err === false) { - done = true; - canceled = true; - return - } + saw.trap = function (name, cb) { + var ps = Array.isArray(name) ? name : [name]; + saw.actions.push({ + path : ps, + step : saw.step, + cb : cb, + trap : true + }); + }; - if (result === breakLoop$1 || (done && running <= 0)) { - done = true; - //console.log('done iterCb') - return callback(null); - } - replenish(); - } + saw.down = function (name) { + var ps = (Array.isArray(name) ? name : [name]).join('/'); + var i = saw.actions.slice(saw.step).map(function (x) { + if (x.trap && x.step <= saw.step) return false; + return x.path.join('/') == ps; + }).indexOf(true); - function handleError(err) { - if (canceled) return - awaiting = false; - done = true; - callback(err); + if (i >= 0) saw.step += i; + else saw.step = saw.actions.length; + + var act = saw.actions[saw.step - 1]; + if (act && act.trap) { + // It's a trap! + saw.step = act.step; + act.cb(); } + else saw.next(); + }; - replenish(); - } + saw.jump = function (step) { + saw.step = step; + saw.next(); + }; +}; - var eachOfLimit$2 = (limit) => { - return (obj, iteratee, callback) => { - callback = once(callback); - if (limit <= 0) { - throw new RangeError('concurrency limit cannot be less than 1') - } - if (!obj) { - return callback(null); - } - if (isAsyncGenerator(obj)) { - return asyncEachOfLimit(obj, limit, iteratee, callback) - } - if (isAsyncIterable(obj)) { - return asyncEachOfLimit(obj[Symbol.asyncIterator](), limit, iteratee, callback) - } - var nextElem = createIterator(obj); - var done = false; - var canceled = false; - var running = 0; - var looping = false; - function iterateeCallback(err, value) { - if (canceled) return - running -= 1; - if (err) { - done = true; - callback(err); - } - else if (err === false) { - done = true; - canceled = true; - } - else if (value === breakLoop$1 || (done && running <= 0)) { - done = true; - return callback(null); - } - else if (!looping) { - replenish(); - } - } +/***/ }), - function replenish () { - looping = true; - while (running < limit && !done) { - var elem = nextElem(); - if (elem === null) { - done = true; - if (running <= 0) { - callback(null); - } - return; - } - running += 1; - iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); - } - looping = false; - } +/***/ 85443: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - replenish(); - }; - }; +var util = __nccwpck_require__(73837); +var Stream = (__nccwpck_require__(12781).Stream); +var DelayedStream = __nccwpck_require__(18611); - /** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a - * time. - * - * @name eachOfLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfLimit - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. The `key` is the item's key, or index in the case of an - * array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @returns {Promise} a promise, if a callback is omitted - */ - function eachOfLimit(coll, limit, iteratee, callback) { - return eachOfLimit$2(limit)(coll, wrapAsync(iteratee), callback); - } +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; - var eachOfLimit$1 = awaitify(eachOfLimit, 4); + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; +} +util.inherits(CombinedStream, Stream); - // eachOf implementation optimized for array-likes - function eachOfArrayLike(coll, iteratee, callback) { - callback = once(callback); - var index = 0, - completed = 0, - {length} = coll, - canceled = false; - if (length === 0) { - callback(null); - } +CombinedStream.create = function(options) { + var combinedStream = new this(); - function iteratorCallback(err, value) { - if (err === false) { - canceled = true; - } - if (canceled === true) return - if (err) { - callback(err); - } else if ((++completed === length) || value === breakLoop$1) { - callback(null); - } - } + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } - for (; index < length; index++) { - iteratee(coll[index], index, onlyOnce(iteratorCallback)); - } + return combinedStream; +}; + +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; + +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; } - // a generic version of eachOf which can handle array, object, and iterator cases. - function eachOfGeneric (coll, iteratee, callback) { - return eachOfLimit$1(coll, Infinity, iteratee, callback); + this._handleErrors(stream); + + if (this.pauseStreams) { + stream.pause(); } + } - /** - * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument - * to the iteratee. - * - * @name eachOf - * @static - * @memberOf module:Collections - * @method - * @alias forEachOf - * @category Collection - * @see [async.each]{@link module:Collections.each} - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each - * item in `coll`. - * The `key` is the item's key, or index in the case of an array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @returns {Promise} a promise, if a callback is omitted - * @example - * - * // dev.json is a file containing a valid json object config for dev environment - * // dev.json is a file containing a valid json object config for test environment - * // prod.json is a file containing a valid json object config for prod environment - * // invalid.json is a file with a malformed json object - * - * let configs = {}; //global variable - * let validConfigFileMap = {dev: 'dev.json', test: 'test.json', prod: 'prod.json'}; - * let invalidConfigFileMap = {dev: 'dev.json', test: 'test.json', invalid: 'invalid.json'}; - * - * // asynchronous function that reads a json file and parses the contents as json object - * function parseFile(file, key, callback) { - * fs.readFile(file, "utf8", function(err, data) { - * if (err) return calback(err); - * try { - * configs[key] = JSON.parse(data); - * } catch (e) { - * return callback(e); - * } - * callback(); - * }); - * } - * - * // Using callbacks - * async.forEachOf(validConfigFileMap, parseFile, function (err) { - * if (err) { - * console.error(err); - * } else { - * console.log(configs); - * // configs is now a map of JSON data, e.g. - * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} - * } - * }); - * - * //Error handing - * async.forEachOf(invalidConfigFileMap, parseFile, function (err) { - * if (err) { - * console.error(err); - * // JSON parse error exception - * } else { - * console.log(configs); - * } - * }); - * - * // Using Promises - * async.forEachOf(validConfigFileMap, parseFile) - * .then( () => { - * console.log(configs); - * // configs is now a map of JSON data, e.g. - * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} - * }).catch( err => { - * console.error(err); - * }); - * - * //Error handing - * async.forEachOf(invalidConfigFileMap, parseFile) - * .then( () => { - * console.log(configs); - * }).catch( err => { - * console.error(err); - * // JSON parse error exception - * }); - * - * // Using async/await - * async () => { - * try { - * let result = await async.forEachOf(validConfigFileMap, parseFile); - * console.log(configs); - * // configs is now a map of JSON data, e.g. - * // { dev: //parsed dev.json, test: //parsed test.json, prod: //parsed prod.json} - * } - * catch (err) { - * console.log(err); - * } - * } - * - * //Error handing - * async () => { - * try { - * let result = await async.forEachOf(invalidConfigFileMap, parseFile); - * console.log(configs); - * } - * catch (err) { - * console.log(err); - * // JSON parse error exception - * } - * } - * - */ - function eachOf(coll, iteratee, callback) { - var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; - return eachOfImplementation(coll, wrapAsync(iteratee), callback); - } - - var eachOf$1 = awaitify(eachOf, 3); + this._streams.push(stream); + return this; +}; - /** - * Produces a new collection of values by mapping each value in `coll` through - * the `iteratee` function. The `iteratee` is called with an item from `coll` - * and a callback for when it has finished processing. Each of these callbacks - * takes 2 arguments: an `error`, and the transformed item from `coll`. If - * `iteratee` passes an error to its callback, the main `callback` (for the - * `map` function) is immediately called with the error. - * - * Note, that since this function applies the `iteratee` to each item in - * parallel, there is no guarantee that the `iteratee` functions will complete - * in order. However, the results array will be in the same order as the - * original `coll`. - * - * If `map` is passed an Object, the results will be an Array. The results - * will roughly be in the order of the original Objects' keys (but this can - * vary across JavaScript engines). - * - * @name map - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an Array of the - * transformed items from the `coll`. Invoked with (err, results). - * @returns {Promise} a promise, if no callback is passed - * @example - * - * // file1.txt is a file that is 1000 bytes in size - * // file2.txt is a file that is 2000 bytes in size - * // file3.txt is a file that is 3000 bytes in size - * // file4.txt does not exist - * - * const fileList = ['file1.txt','file2.txt','file3.txt']; - * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; - * - * // asynchronous function that returns the file size in bytes - * function getFileSizeInBytes(file, callback) { - * fs.stat(file, function(err, stat) { - * if (err) { - * return callback(err); - * } - * callback(null, stat.size); - * }); - * } - * - * // Using callbacks - * async.map(fileList, getFileSizeInBytes, function(err, results) { - * if (err) { - * console.log(err); - * } else { - * console.log(results); - * // results is now an array of the file size in bytes for each file, e.g. - * // [ 1000, 2000, 3000] - * } - * }); - * - * // Error Handling - * async.map(withMissingFileList, getFileSizeInBytes, function(err, results) { - * if (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * } else { - * console.log(results); - * } - * }); - * - * // Using Promises - * async.map(fileList, getFileSizeInBytes) - * .then( results => { - * console.log(results); - * // results is now an array of the file size in bytes for each file, e.g. - * // [ 1000, 2000, 3000] - * }).catch( err => { - * console.log(err); - * }); - * - * // Error Handling - * async.map(withMissingFileList, getFileSizeInBytes) - * .then( results => { - * console.log(results); - * }).catch( err => { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * }); - * - * // Using async/await - * async () => { - * try { - * let results = await async.map(fileList, getFileSizeInBytes); - * console.log(results); - * // results is now an array of the file size in bytes for each file, e.g. - * // [ 1000, 2000, 3000] - * } - * catch (err) { - * console.log(err); - * } - * } - * - * // Error Handling - * async () => { - * try { - * let results = await async.map(withMissingFileList, getFileSizeInBytes); - * console.log(results); - * } - * catch (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * } - * } - * - */ - function map (coll, iteratee, callback) { - return _asyncMap(eachOf$1, coll, iteratee, callback) - } - var map$1 = awaitify(map, 3); +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; - /** - * Applies the provided arguments to each function in the array, calling - * `callback` after all functions have completed. If you only provide the first - * argument, `fns`, then it will return a function which lets you pass in the - * arguments as if it were a single function call. If more arguments are - * provided, `callback` is required while `args` is still optional. The results - * for each of the applied async functions are passed to the final callback - * as an array. - * - * @name applyEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s - * to all call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {AsyncFunction} - Returns a function that takes no args other than - * an optional callback, that is the result of applying the `args` to each - * of the functions. - * @example - * - * const appliedFn = async.applyEach([enableSearch, updateSchema], 'bucket') - * - * appliedFn((err, results) => { - * // results[0] is the results for `enableSearch` - * // results[1] is the results for `updateSchema` - * }); - * - * // partial application example: - * async.each( - * buckets, - * async (bucket) => async.applyEach([enableSearch, updateSchema], bucket)(), - * callback - * ); - */ - var applyEach = applyEach$1(map$1); +CombinedStream.prototype._getNext = function() { + this._currentStream = null; - /** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. - * - * @name eachOfSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfSeries - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Invoked with (err). - * @returns {Promise} a promise, if a callback is omitted - */ - function eachOfSeries(coll, iteratee, callback) { - return eachOfLimit$1(coll, 1, iteratee, callback) - } - var eachOfSeries$1 = awaitify(eachOfSeries, 3); + if (this._insideLoop) { + this._pendingNext = true; + return; // defer call + } - /** - * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. - * - * @name mapSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - * @returns {Promise} a promise, if no callback is passed - */ - function mapSeries (coll, iteratee, callback) { - return _asyncMap(eachOfSeries$1, coll, iteratee, callback) - } - var mapSeries$1 = awaitify(mapSeries, 3); + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; + } +}; - /** - * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. - * - * @name applyEachSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.applyEach]{@link module:ControlFlow.applyEach} - * @category Control Flow - * @param {Array|Iterable|AsyncIterable|Object} fns - A collection of {@link AsyncFunction}s to all - * call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {AsyncFunction} - A function, that when called, is the result of - * appling the `args` to the list of functions. It takes no args, other than - * a callback. - */ - var applyEachSeries = applyEach$1(mapSeries$1); +CombinedStream.prototype._realGetNext = function() { + var stream = this._streams.shift(); - const PROMISE_SYMBOL = Symbol('promiseCallback'); - function promiseCallback () { - let resolve, reject; - function callback (err, ...args) { - if (err) return reject(err) - resolve(args.length > 1 ? args : args[0]); - } + if (typeof stream == 'undefined') { + this.end(); + return; + } - callback[PROMISE_SYMBOL] = new Promise((res, rej) => { - resolve = res, - reject = rej; - }); + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } - return callback + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); } - /** - * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on - * their requirements. Each function can optionally depend on other functions - * being completed first, and each function is run as soon as its requirements - * are satisfied. - * - * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence - * will stop. Further tasks will not execute (so any other functions depending - * on it will not run), and the main `callback` is immediately called with the - * error. - * - * {@link AsyncFunction}s also receive an object containing the results of functions which - * have completed so far as the first argument, if they have dependencies. If a - * task function has no dependencies, it will only be passed a callback. - * - * @name auto - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Object} tasks - An object. Each of its properties is either a - * function or an array of requirements, with the {@link AsyncFunction} itself the last item - * in the array. The object's key of a property serves as the name of the task - * defined by that property, i.e. can be used when specifying requirements for - * other tasks. The function receives one or two arguments: - * * a `results` object, containing the results of the previously executed - * functions, only passed if the task has any dependencies, - * * a `callback(err, result)` function, which must be called when finished, - * passing an `error` (which can be `null`) and the result of the function's - * execution. - * @param {number} [concurrency=Infinity] - An optional `integer` for - * determining the maximum number of tasks that can be run in parallel. By - * default, as many as possible. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback. Results are always returned; however, if an - * error occurs, no further `tasks` will be performed, and the results object - * will only contain partial results. Invoked with (err, results). - * @returns {Promise} a promise, if a callback is not passed - * @example - * - * //Using Callbacks - * async.auto({ - * get_data: function(callback) { - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: ['get_data', 'make_folder', function(results, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(results, callback) { - * // once the file is written let's email a link to it... - * callback(null, {'file':results.write_file, 'email':'user@example.com'}); - * }] - * }, function(err, results) { - * if (err) { - * console.log('err = ', err); - * } - * console.log('results = ', results); - * // results = { - * // get_data: ['data', 'converted to array'] - * // make_folder; 'folder', - * // write_file: 'filename' - * // email_link: { file: 'filename', email: 'user@example.com' } - * // } - * }); - * - * //Using Promises - * async.auto({ - * get_data: function(callback) { - * console.log('in get_data'); - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * console.log('in make_folder'); - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: ['get_data', 'make_folder', function(results, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(results, callback) { - * // once the file is written let's email a link to it... - * callback(null, {'file':results.write_file, 'email':'user@example.com'}); - * }] - * }).then(results => { - * console.log('results = ', results); - * // results = { - * // get_data: ['data', 'converted to array'] - * // make_folder; 'folder', - * // write_file: 'filename' - * // email_link: { file: 'filename', email: 'user@example.com' } - * // } - * }).catch(err => { - * console.log('err = ', err); - * }); - * - * //Using async/await - * async () => { - * try { - * let results = await async.auto({ - * get_data: function(callback) { - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: ['get_data', 'make_folder', function(results, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(results, callback) { - * // once the file is written let's email a link to it... - * callback(null, {'file':results.write_file, 'email':'user@example.com'}); - * }] - * }); - * console.log('results = ', results); - * // results = { - * // get_data: ['data', 'converted to array'] - * // make_folder; 'folder', - * // write_file: 'filename' - * // email_link: { file: 'filename', email: 'user@example.com' } - * // } - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function auto(tasks, concurrency, callback) { - if (typeof concurrency !== 'number') { - // concurrency is optional, shift the args. - callback = concurrency; - concurrency = null; - } - callback = once(callback || promiseCallback()); - var numTasks = Object.keys(tasks).length; - if (!numTasks) { - return callback(null); - } - if (!concurrency) { - concurrency = numTasks; - } + this._pipeNext(stream); + }.bind(this)); +}; - var results = {}; - var runningTasks = 0; - var canceled = false; - var hasError = false; +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; - var listeners = Object.create(null); + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } - var readyTasks = []; + var value = stream; + this.write(value); + this._getNext(); +}; - // for cycle detection: - var readyToCheck = []; // tasks that have been identified as reachable - // without the possibility of returning to an ancestor task - var uncheckedDependencies = {}; +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); +}; - Object.keys(tasks).forEach(key => { - var task = tasks[key]; - if (!Array.isArray(task)) { - // no dependencies - enqueueTask(key, [task]); - readyToCheck.push(key); - return; - } +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; - var dependencies = task.slice(0, task.length - 1); - var remainingDependencies = dependencies.length; - if (remainingDependencies === 0) { - enqueueTask(key, task); - readyToCheck.push(key); - return; - } - uncheckedDependencies[key] = remainingDependencies; - - dependencies.forEach(dependencyName => { - if (!tasks[dependencyName]) { - throw new Error('async.auto task `' + key + - '` has a non-existent dependency `' + - dependencyName + '` in ' + - dependencies.join(', ')); - } - addListener(dependencyName, () => { - remainingDependencies--; - if (remainingDependencies === 0) { - enqueueTask(key, task); - } - }); - }); - }); - - checkForDeadlocks(); - processQueue(); +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } - function enqueueTask(key, task) { - readyTasks.push(() => runTask(key, task)); - } + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); +}; - function processQueue() { - if (canceled) return - if (readyTasks.length === 0 && runningTasks === 0) { - return callback(null, results); - } - while(readyTasks.length && runningTasks < concurrency) { - var run = readyTasks.shift(); - run(); - } +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } - } + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); +}; - function addListener(taskName, fn) { - var taskListeners = listeners[taskName]; - if (!taskListeners) { - taskListeners = listeners[taskName] = []; - } +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; - taskListeners.push(fn); - } +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; - function taskComplete(taskName) { - var taskListeners = listeners[taskName] || []; - taskListeners.forEach(fn => fn()); - processQueue(); - } +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } - function runTask(key, task) { - if (hasError) return; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; - var taskCallback = onlyOnce((err, ...result) => { - runningTasks--; - if (err === false) { - canceled = true; - return - } - if (result.length < 2) { - [result] = result; - } - if (err) { - var safeResults = {}; - Object.keys(results).forEach(rkey => { - safeResults[rkey] = results[rkey]; - }); - safeResults[key] = result; - hasError = true; - listeners = Object.create(null); - if (canceled) return - callback(err, safeResults); - } else { - results[key] = result; - taskComplete(key); - } - }); +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; - runningTasks++; - var taskFn = wrapAsync(task[task.length - 1]); - if (task.length > 1) { - taskFn(results, taskCallback); - } else { - taskFn(taskCallback); - } - } + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; + } - function checkForDeadlocks() { - // Kahn's algorithm - // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm - // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html - var currentTask; - var counter = 0; - while (readyToCheck.length) { - currentTask = readyToCheck.pop(); - counter++; - getDependents(currentTask).forEach(dependent => { - if (--uncheckedDependencies[dependent] === 0) { - readyToCheck.push(dependent); - } - }); - } + self.dataSize += stream.dataSize; + }); - if (counter !== numTasks) { - throw new Error( - 'async.auto cannot execute tasks due to a recursive dependency' - ); - } - } + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } +}; - function getDependents(taskName) { - var result = []; - Object.keys(tasks).forEach(key => { - const task = tasks[key]; - if (Array.isArray(task) && task.indexOf(taskName) >= 0) { - result.push(key); - } - }); - return result; - } +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; - return callback[PROMISE_SYMBOL] - } - var FN_ARGS = /^(?:async\s+)?(?:function)?\s*\w*\s*\(\s*([^)]+)\s*\)(?:\s*{)/; - var ARROW_FN_ARGS = /^(?:async\s+)?\(?\s*([^)=]+)\s*\)?(?:\s*=>)/; - var FN_ARG_SPLIT = /,/; - var FN_ARG = /(=.+)?(\s*)$/; +/***/ }), - function stripComments(string) { - let stripped = ''; - let index = 0; - let endBlockComment = string.indexOf('*/'); - while (index < string.length) { - if (string[index] === '/' && string[index+1] === '/') { - // inline comment - let endIndex = string.indexOf('\n', index); - index = (endIndex === -1) ? string.length : endIndex; - } else if ((endBlockComment !== -1) && (string[index] === '/') && (string[index+1] === '*')) { - // block comment - let endIndex = string.indexOf('*/', index); - if (endIndex !== -1) { - index = endIndex + 2; - endBlockComment = string.indexOf('*/', index); - } else { - stripped += string[index]; - index++; - } - } else { - stripped += string[index]; - index++; - } - } - return stripped; - } +/***/ 92240: +/***/ ((module) => { - function parseParams(func) { - const src = stripComments(func.toString()); - let match = src.match(FN_ARGS); - if (!match) { - match = src.match(ARROW_FN_ARGS); - } - if (!match) throw new Error('could not parse args in autoInject\nSource:\n' + src) - let [, args] = match; - return args - .replace(/\s/g, '') - .split(FN_ARG_SPLIT) - .map((arg) => arg.replace(FN_ARG, '').trim()); - } +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +var ArchiveEntry = module.exports = function() {}; - /** - * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent - * tasks are specified as parameters to the function, after the usual callback - * parameter, with the parameter names matching the names of the tasks it - * depends on. This can provide even more readable task graphs which can be - * easier to maintain. - * - * If a final callback is specified, the task results are similarly injected, - * specified as named parameters after the initial error parameter. - * - * The autoInject function is purely syntactic sugar and its semantics are - * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. - * - * @name autoInject - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.auto]{@link module:ControlFlow.auto} - * @category Control Flow - * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of - * the form 'func([dependencies...], callback). The object's key of a property - * serves as the name of the task defined by that property, i.e. can be used - * when specifying requirements for other tasks. - * * The `callback` parameter is a `callback(err, result)` which must be called - * when finished, passing an `error` (which can be `null`) and the result of - * the function's execution. The remaining parameters name other tasks on - * which the task is dependent, and the results from those tasks are the - * arguments of those parameters. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback, and a `results` object with any completed - * task results, similar to `auto`. - * @returns {Promise} a promise, if no callback is passed - * @example - * - * // The example from `auto` can be rewritten as follows: - * async.autoInject({ - * get_data: function(callback) { - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: function(get_data, make_folder, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }, - * email_link: function(write_file, callback) { - * // once the file is written let's email a link to it... - * // write_file contains the filename returned by write_file. - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * } - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - * - * // If you are using a JS minifier that mangles parameter names, `autoInject` - * // will not work with plain functions, since the parameter names will be - * // collapsed to a single letter identifier. To work around this, you can - * // explicitly specify the names of the parameters your task function needs - * // in an array, similar to Angular.js dependency injection. - * - * // This still has an advantage over plain `auto`, since the results a task - * // depends on are still spread into arguments. - * async.autoInject({ - * //... - * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(write_file, callback) { - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * }] - * //... - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - */ - function autoInject(tasks, callback) { - var newTasks = {}; +ArchiveEntry.prototype.getName = function() {}; - Object.keys(tasks).forEach(key => { - var taskFn = tasks[key]; - var params; - var fnIsAsync = isAsync(taskFn); - var hasNoDeps = - (!fnIsAsync && taskFn.length === 1) || - (fnIsAsync && taskFn.length === 0); +ArchiveEntry.prototype.getSize = function() {}; - if (Array.isArray(taskFn)) { - params = [...taskFn]; - taskFn = params.pop(); +ArchiveEntry.prototype.getLastModifiedDate = function() {}; - newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); - } else if (hasNoDeps) { - // no dependencies, use the function as-is - newTasks[key] = taskFn; - } else { - params = parseParams(taskFn); - if ((taskFn.length === 0 && !fnIsAsync) && params.length === 0) { - throw new Error("autoInject task functions require explicit parameters."); - } +ArchiveEntry.prototype.isDirectory = function() {}; - // remove callback param - if (!fnIsAsync) params.pop(); +/***/ }), - newTasks[key] = params.concat(newTask); - } +/***/ 36728: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function newTask(results, taskCb) { - var newArgs = params.map(name => results[name]); - newArgs.push(taskCb); - wrapAsync(taskFn)(...newArgs); - } - }); +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +var inherits = (__nccwpck_require__(73837).inherits); +var isStream = __nccwpck_require__(41554); +var Transform = (__nccwpck_require__(45193).Transform); - return auto(newTasks, callback); - } +var ArchiveEntry = __nccwpck_require__(92240); +var util = __nccwpck_require__(95208); - // Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation - // used for queues. This implementation assumes that the node provided by the user can be modified - // to adjust the next and last properties. We implement only the minimal functionality - // for queue support. - class DLL { - constructor() { - this.head = this.tail = null; - this.length = 0; - } +var ArchiveOutputStream = module.exports = function(options) { + if (!(this instanceof ArchiveOutputStream)) { + return new ArchiveOutputStream(options); + } - removeLink(node) { - if (node.prev) node.prev.next = node.next; - else this.head = node.next; - if (node.next) node.next.prev = node.prev; - else this.tail = node.prev; + Transform.call(this, options); - node.prev = node.next = null; - this.length -= 1; - return node; - } + this.offset = 0; + this._archive = { + finish: false, + finished: false, + processing: false + }; +}; - empty () { - while(this.head) this.shift(); - return this; - } +inherits(ArchiveOutputStream, Transform); - insertAfter(node, newNode) { - newNode.prev = node; - newNode.next = node.next; - if (node.next) node.next.prev = newNode; - else this.tail = newNode; - node.next = newNode; - this.length += 1; - } +ArchiveOutputStream.prototype._appendBuffer = function(zae, source, callback) { + // scaffold only +}; - insertBefore(node, newNode) { - newNode.prev = node.prev; - newNode.next = node; - if (node.prev) node.prev.next = newNode; - else this.head = newNode; - node.prev = newNode; - this.length += 1; - } +ArchiveOutputStream.prototype._appendStream = function(zae, source, callback) { + // scaffold only +}; - unshift(node) { - if (this.head) this.insertBefore(this.head, node); - else setInitial(this, node); - } +ArchiveOutputStream.prototype._emitErrorCallback = function(err) { + if (err) { + this.emit('error', err); + } +}; - push(node) { - if (this.tail) this.insertAfter(this.tail, node); - else setInitial(this, node); - } +ArchiveOutputStream.prototype._finish = function(ae) { + // scaffold only +}; - shift() { - return this.head && this.removeLink(this.head); - } +ArchiveOutputStream.prototype._normalizeEntry = function(ae) { + // scaffold only +}; - pop() { - return this.tail && this.removeLink(this.tail); - } +ArchiveOutputStream.prototype._transform = function(chunk, encoding, callback) { + callback(null, chunk); +}; - toArray() { - return [...this] - } +ArchiveOutputStream.prototype.entry = function(ae, source, callback) { + source = source || null; - *[Symbol.iterator] () { - var cur = this.head; - while (cur) { - yield cur.data; - cur = cur.next; - } - } + if (typeof callback !== 'function') { + callback = this._emitErrorCallback.bind(this); + } - remove (testFn) { - var curr = this.head; - while(curr) { - var {next} = curr; - if (testFn(curr)) { - this.removeLink(curr); - } - curr = next; - } - return this; - } - } + if (!(ae instanceof ArchiveEntry)) { + callback(new Error('not a valid instance of ArchiveEntry')); + return; + } - function setInitial(dll, node) { - dll.length = 1; - dll.head = dll.tail = node; - } + if (this._archive.finish || this._archive.finished) { + callback(new Error('unacceptable entry after finish')); + return; + } - function queue$1(worker, concurrency, payload) { - if (concurrency == null) { - concurrency = 1; - } - else if(concurrency === 0) { - throw new RangeError('Concurrency must not be zero'); - } + if (this._archive.processing) { + callback(new Error('already processing an entry')); + return; + } - var _worker = wrapAsync(worker); - var numRunning = 0; - var workersList = []; - const events = { - error: [], - drain: [], - saturated: [], - unsaturated: [], - empty: [] - }; + this._archive.processing = true; + this._normalizeEntry(ae); + this._entry = ae; - function on (event, handler) { - events[event].push(handler); - } + source = util.normalizeInputSource(source); - function once (event, handler) { - const handleAndRemove = (...args) => { - off(event, handleAndRemove); - handler(...args); - }; - events[event].push(handleAndRemove); - } + if (Buffer.isBuffer(source)) { + this._appendBuffer(ae, source, callback); + } else if (isStream(source)) { + this._appendStream(ae, source, callback); + } else { + this._archive.processing = false; + callback(new Error('input source must be valid Stream or Buffer instance')); + return; + } - function off (event, handler) { - if (!event) return Object.keys(events).forEach(ev => events[ev] = []) - if (!handler) return events[event] = [] - events[event] = events[event].filter(ev => ev !== handler); - } + return this; +}; - function trigger (event, ...args) { - events[event].forEach(handler => handler(...args)); - } +ArchiveOutputStream.prototype.finish = function() { + if (this._archive.processing) { + this._archive.finish = true; + return; + } - var processingScheduled = false; - function _insert(data, insertAtFront, rejectOnError, callback) { - if (callback != null && typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; + this._finish(); +}; - var res, rej; - function promiseCallback (err, ...args) { - // we don't care about the error, let the global error handler - // deal with it - if (err) return rejectOnError ? rej(err) : res() - if (args.length <= 1) return res(args[0]) - res(args); - } +ArchiveOutputStream.prototype.getBytesWritten = function() { + return this.offset; +}; - var item = q._createTaskItem( - data, - rejectOnError ? promiseCallback : - (callback || promiseCallback) - ); +ArchiveOutputStream.prototype.write = function(chunk, cb) { + if (chunk) { + this.offset += chunk.length; + } - if (insertAtFront) { - q._tasks.unshift(item); - } else { - q._tasks.push(item); - } + return Transform.prototype.write.call(this, chunk, cb); +}; - if (!processingScheduled) { - processingScheduled = true; - setImmediate$1(() => { - processingScheduled = false; - q.process(); - }); - } +/***/ }), - if (rejectOnError || !callback) { - return new Promise((resolve, reject) => { - res = resolve; - rej = reject; - }) - } - } +/***/ 11704: +/***/ ((module) => { - function _createCB(tasks) { - return function (err, ...args) { - numRunning -= 1; +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +module.exports = { + WORD: 4, + DWORD: 8, + EMPTY: Buffer.alloc(0), - for (var i = 0, l = tasks.length; i < l; i++) { - var task = tasks[i]; + SHORT: 2, + SHORT_MASK: 0xffff, + SHORT_SHIFT: 16, + SHORT_ZERO: Buffer.from(Array(2)), + LONG: 4, + LONG_ZERO: Buffer.from(Array(4)), - var index = workersList.indexOf(task); - if (index === 0) { - workersList.shift(); - } else if (index > 0) { - workersList.splice(index, 1); - } + MIN_VERSION_INITIAL: 10, + MIN_VERSION_DATA_DESCRIPTOR: 20, + MIN_VERSION_ZIP64: 45, + VERSION_MADEBY: 45, - task.callback(err, ...args); + METHOD_STORED: 0, + METHOD_DEFLATED: 8, - if (err != null) { - trigger('error', err, task.data); - } - } + PLATFORM_UNIX: 3, + PLATFORM_FAT: 0, - if (numRunning <= (q.concurrency - q.buffer) ) { - trigger('unsaturated'); - } + SIG_LFH: 0x04034b50, + SIG_DD: 0x08074b50, + SIG_CFH: 0x02014b50, + SIG_EOCD: 0x06054b50, + SIG_ZIP64_EOCD: 0x06064B50, + SIG_ZIP64_EOCD_LOC: 0x07064B50, - if (q.idle()) { - trigger('drain'); - } - q.process(); - }; - } + ZIP64_MAGIC_SHORT: 0xffff, + ZIP64_MAGIC: 0xffffffff, + ZIP64_EXTRA_ID: 0x0001, - function _maybeDrain(data) { - if (data.length === 0 && q.idle()) { - // call drain immediately if there are no tasks - setImmediate$1(() => trigger('drain')); - return true - } - return false - } + ZLIB_NO_COMPRESSION: 0, + ZLIB_BEST_SPEED: 1, + ZLIB_BEST_COMPRESSION: 9, + ZLIB_DEFAULT_COMPRESSION: -1, - const eventMethod = (name) => (handler) => { - if (!handler) { - return new Promise((resolve, reject) => { - once(name, (err, data) => { - if (err) return reject(err) - resolve(data); - }); - }) - } - off(name); - on(name, handler); + MODE_MASK: 0xFFF, + DEFAULT_FILE_MODE: 33188, // 010644 = -rw-r--r-- = S_IFREG | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH + DEFAULT_DIR_MODE: 16877, // 040755 = drwxr-xr-x = S_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH - }; + EXT_FILE_ATTR_DIR: 1106051088, // 010173200020 = drwxr-xr-x = (((S_IFDIR | 0755) << 16) | S_DOS_D) + EXT_FILE_ATTR_FILE: 2175008800, // 020151000040 = -rw-r--r-- = (((S_IFREG | 0644) << 16) | S_DOS_A) >>> 0 - var isProcessing = false; - var q = { - _tasks: new DLL(), - _createTaskItem (data, callback) { - return { - data, - callback - }; - }, - *[Symbol.iterator] () { - yield* q._tasks[Symbol.iterator](); - }, - concurrency, - payload, - buffer: concurrency / 4, - started: false, - paused: false, - push (data, callback) { - if (Array.isArray(data)) { - if (_maybeDrain(data)) return - return data.map(datum => _insert(datum, false, false, callback)) - } - return _insert(data, false, false, callback); - }, - pushAsync (data, callback) { - if (Array.isArray(data)) { - if (_maybeDrain(data)) return - return data.map(datum => _insert(datum, false, true, callback)) - } - return _insert(data, false, true, callback); - }, - kill () { - off(); - q._tasks.empty(); - }, - unshift (data, callback) { - if (Array.isArray(data)) { - if (_maybeDrain(data)) return - return data.map(datum => _insert(datum, true, false, callback)) - } - return _insert(data, true, false, callback); - }, - unshiftAsync (data, callback) { - if (Array.isArray(data)) { - if (_maybeDrain(data)) return - return data.map(datum => _insert(datum, true, true, callback)) - } - return _insert(data, true, true, callback); - }, - remove (testFn) { - q._tasks.remove(testFn); - }, - process () { - // Avoid trying to start too many processing operations. This can occur - // when callbacks resolve synchronously (#1267). - if (isProcessing) { - return; - } - isProcessing = true; - while(!q.paused && numRunning < q.concurrency && q._tasks.length){ - var tasks = [], data = []; - var l = q._tasks.length; - if (q.payload) l = Math.min(l, q.payload); - for (var i = 0; i < l; i++) { - var node = q._tasks.shift(); - tasks.push(node); - workersList.push(node); - data.push(node.data); - } + // Unix file types + S_IFMT: 61440, // 0170000 type of file mask + S_IFIFO: 4096, // 010000 named pipe (fifo) + S_IFCHR: 8192, // 020000 character special + S_IFDIR: 16384, // 040000 directory + S_IFBLK: 24576, // 060000 block special + S_IFREG: 32768, // 0100000 regular + S_IFLNK: 40960, // 0120000 symbolic link + S_IFSOCK: 49152, // 0140000 socket - numRunning += 1; + // DOS file type flags + S_DOS_A: 32, // 040 Archive + S_DOS_D: 16, // 020 Directory + S_DOS_V: 8, // 010 Volume + S_DOS_S: 4, // 04 System + S_DOS_H: 2, // 02 Hidden + S_DOS_R: 1 // 01 Read Only +}; - if (q._tasks.length === 0) { - trigger('empty'); - } - if (numRunning === q.concurrency) { - trigger('saturated'); - } +/***/ }), - var cb = onlyOnce(_createCB(tasks)); - _worker(data, cb); - } - isProcessing = false; - }, - length () { - return q._tasks.length; - }, - running () { - return numRunning; - }, - workersList () { - return workersList; - }, - idle() { - return q._tasks.length + numRunning === 0; - }, - pause () { - q.paused = true; - }, - resume () { - if (q.paused === false) { return; } - q.paused = false; - setImmediate$1(q.process); - } - }; - // define these as fixed properties, so people get useful errors when updating - Object.defineProperties(q, { - saturated: { - writable: false, - value: eventMethod('saturated') - }, - unsaturated: { - writable: false, - value: eventMethod('unsaturated') - }, - empty: { - writable: false, - value: eventMethod('empty') - }, - drain: { - writable: false, - value: eventMethod('drain') - }, - error: { - writable: false, - value: eventMethod('error') - }, - }); - return q; - } +/***/ 63229: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +var zipUtil = __nccwpck_require__(68682); + +var DATA_DESCRIPTOR_FLAG = 1 << 3; +var ENCRYPTION_FLAG = 1 << 0; +var NUMBER_OF_SHANNON_FANO_TREES_FLAG = 1 << 2; +var SLIDING_DICTIONARY_SIZE_FLAG = 1 << 1; +var STRONG_ENCRYPTION_FLAG = 1 << 6; +var UFT8_NAMES_FLAG = 1 << 11; + +var GeneralPurposeBit = module.exports = function() { + if (!(this instanceof GeneralPurposeBit)) { + return new GeneralPurposeBit(); + } + + this.descriptor = false; + this.encryption = false; + this.utf8 = false; + this.numberOfShannonFanoTrees = 0; + this.strongEncryption = false; + this.slidingDictionarySize = 0; + + return this; +}; + +GeneralPurposeBit.prototype.encode = function() { + return zipUtil.getShortBytes( + (this.descriptor ? DATA_DESCRIPTOR_FLAG : 0) | + (this.utf8 ? UFT8_NAMES_FLAG : 0) | + (this.encryption ? ENCRYPTION_FLAG : 0) | + (this.strongEncryption ? STRONG_ENCRYPTION_FLAG : 0) + ); +}; + +GeneralPurposeBit.prototype.parse = function(buf, offset) { + var flag = zipUtil.getShortBytesValue(buf, offset); + var gbp = new GeneralPurposeBit(); + + gbp.useDataDescriptor((flag & DATA_DESCRIPTOR_FLAG) !== 0); + gbp.useUTF8ForNames((flag & UFT8_NAMES_FLAG) !== 0); + gbp.useStrongEncryption((flag & STRONG_ENCRYPTION_FLAG) !== 0); + gbp.useEncryption((flag & ENCRYPTION_FLAG) !== 0); + gbp.setSlidingDictionarySize((flag & SLIDING_DICTIONARY_SIZE_FLAG) !== 0 ? 8192 : 4096); + gbp.setNumberOfShannonFanoTrees((flag & NUMBER_OF_SHANNON_FANO_TREES_FLAG) !== 0 ? 3 : 2); + + return gbp; +}; + +GeneralPurposeBit.prototype.setNumberOfShannonFanoTrees = function(n) { + this.numberOfShannonFanoTrees = n; +}; + +GeneralPurposeBit.prototype.getNumberOfShannonFanoTrees = function() { + return this.numberOfShannonFanoTrees; +}; + +GeneralPurposeBit.prototype.setSlidingDictionarySize = function(n) { + this.slidingDictionarySize = n; +}; + +GeneralPurposeBit.prototype.getSlidingDictionarySize = function() { + return this.slidingDictionarySize; +}; + +GeneralPurposeBit.prototype.useDataDescriptor = function(b) { + this.descriptor = b; +}; + +GeneralPurposeBit.prototype.usesDataDescriptor = function() { + return this.descriptor; +}; + +GeneralPurposeBit.prototype.useEncryption = function(b) { + this.encryption = b; +}; + +GeneralPurposeBit.prototype.usesEncryption = function() { + return this.encryption; +}; + +GeneralPurposeBit.prototype.useStrongEncryption = function(b) { + this.strongEncryption = b; +}; + +GeneralPurposeBit.prototype.usesStrongEncryption = function() { + return this.strongEncryption; +}; + +GeneralPurposeBit.prototype.useUTF8ForNames = function(b) { + this.utf8 = b; +}; + +GeneralPurposeBit.prototype.usesUTF8ForNames = function() { + return this.utf8; +}; + +/***/ }), + +/***/ 70713: +/***/ ((module) => { +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +module.exports = { /** - * Creates a `cargo` object with the specified payload. Tasks added to the - * cargo will be processed altogether (up to the `payload` limit). If the - * `worker` is in progress, the task is queued until it becomes available. Once - * the `worker` has completed some tasks, each callback of those tasks is - * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) - * for how `cargo` and `queue` work. - * - * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers - * at a time, cargo passes an array of tasks to a single worker, repeating - * when the worker is finished. - * - * @name cargo - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An asynchronous function for processing an array - * of queued tasks. Invoked with `(tasks, callback)`. - * @param {number} [payload=Infinity] - An optional `integer` for determining - * how many tasks should be processed per round; if omitted, the default is - * unlimited. - * @returns {module:ControlFlow.QueueObject} A cargo object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the cargo and inner queue. - * @example - * - * // create a cargo object with payload 2 - * var cargo = async.cargo(function(tasks, callback) { - * for (var i=0; i { - * console.log(result); - * // 6000 - * // which is the sum of the file sizes of the three files - * }).catch( err => { - * console.log(err); - * }); - * - * // Error Handling - * async.reduce(withMissingFileList, 0, getFileSizeInBytes) - * .then( result => { - * console.log(result); - * }).catch( err => { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * }); - * - * // Using async/await - * async () => { - * try { - * let result = await async.reduce(fileList, 0, getFileSizeInBytes); - * console.log(result); - * // 6000 - * // which is the sum of the file sizes of the three files - * } - * catch (err) { - * console.log(err); - * } - * } - * - * // Error Handling - * async () => { - * try { - * let result = await async.reduce(withMissingFileList, 0, getFileSizeInBytes); - * console.log(result); - * } - * catch (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * } - * } - * + * Indicates symbolic links. */ - function reduce(coll, memo, iteratee, callback) { - callback = once(callback); - var _iteratee = wrapAsync(iteratee); - return eachOfSeries$1(coll, (x, i, iterCb) => { - _iteratee(memo, x, (err, v) => { - memo = v; - iterCb(err); - }); - }, err => callback(err, memo)); - } - var reduce$1 = awaitify(reduce, 4); + LINK_FLAG: 40960, // 0120000 /** - * Version of the compose function that is more natural to read. Each function - * consumes the return value of the previous function. It is the equivalent of - * [compose]{@link module:ControlFlow.compose} with the arguments reversed. - * - * Each function is executed with the `this` binding of the composed function. - * - * @name seq - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.compose]{@link module:ControlFlow.compose} - * @category Control Flow - * @param {...AsyncFunction} functions - the asynchronous functions to compose - * @returns {Function} a function that composes the `functions` in order - * @example - * - * // Requires lodash (or underscore), express3 and dresende's orm2. - * // Part of an app, that fetches cats of the logged user. - * // This example uses `seq` function to avoid overnesting and error - * // handling clutter. - * app.get('/cats', function(request, response) { - * var User = request.models.User; - * async.seq( - * User.get.bind(User), // 'User.get' has signature (id, callback(err, data)) - * function(user, fn) { - * user.getCats(fn); // 'getCats' has signature (callback(err, data)) - * } - * )(req.session.user_id, function (err, cats) { - * if (err) { - * console.error(err); - * response.json({ status: 'error', message: err.message }); - * } else { - * response.json({ status: 'ok', message: 'Cats found', data: cats }); - * } - * }); - * }); + * Indicates plain files. */ - function seq(...functions) { - var _functions = functions.map(wrapAsync); - return function (...args) { - var that = this; - - var cb = args[args.length - 1]; - if (typeof cb == 'function') { - args.pop(); - } else { - cb = promiseCallback(); - } - - reduce$1(_functions, args, (newargs, fn, iterCb) => { - fn.apply(that, newargs.concat((err, ...nextargs) => { - iterCb(err, nextargs); - })); - }, - (err, results) => cb(err, ...results)); - - return cb[PROMISE_SYMBOL] - }; - } + FILE_FLAG: 32768, // 0100000 /** - * Creates a function which is a composition of the passed asynchronous - * functions. Each function consumes the return value of the function that - * follows. Composing functions `f()`, `g()`, and `h()` would produce the result - * of `f(g(h()))`, only this version uses callbacks to obtain the return values. - * - * If the last argument to the composed function is not a function, a promise - * is returned when you call it. - * - * Each function is executed with the `this` binding of the composed function. - * - * @name compose - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {...AsyncFunction} functions - the asynchronous functions to compose - * @returns {Function} an asynchronous function that is the composed - * asynchronous `functions` - * @example - * - * function add1(n, callback) { - * setTimeout(function () { - * callback(null, n + 1); - * }, 10); - * } - * - * function mul3(n, callback) { - * setTimeout(function () { - * callback(null, n * 3); - * }, 10); - * } - * - * var add1mul3 = async.compose(mul3, add1); - * add1mul3(4, function (err, result) { - * // result now equals 15 - * }); + * Indicates directories. */ - function compose(...args) { - return seq(...args.reverse()); - } + DIR_FLAG: 16384, // 040000 - /** - * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. - * - * @name mapLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - * @returns {Promise} a promise, if no callback is passed - */ - function mapLimit (coll, limit, iteratee, callback) { - return _asyncMap(eachOfLimit$2(limit), coll, iteratee, callback) - } - var mapLimit$1 = awaitify(mapLimit, 4); + // ---------------------------------------------------------- + // somewhat arbitrary choices that are quite common for shared + // installations + // ----------------------------------------------------------- /** - * The same as [`concat`]{@link module:Collections.concat} but runs a maximum of `limit` async operations at a time. - * - * @name concatLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @alias flatMapLimit - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - * @returns A Promise, if no callback is passed + * Default permissions for symbolic links. */ - function concatLimit(coll, limit, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - return mapLimit$1(coll, limit, (val, iterCb) => { - _iteratee(val, (err, ...args) => { - if (err) return iterCb(err); - return iterCb(err, args); - }); - }, (err, mapResults) => { - var result = []; - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - result = result.concat(...mapResults[i]); - } - } - - return callback(err, result); - }); - } - var concatLimit$1 = awaitify(concatLimit, 4); + DEFAULT_LINK_PERM: 511, // 0777 /** - * Applies `iteratee` to each item in `coll`, concatenating the results. Returns - * the concatenated list. The `iteratee`s are called in parallel, and the - * results are concatenated as they return. The results array will be returned in - * the original order of `coll` passed to the `iteratee` function. - * - * @name concat - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @alias flatMap - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`, - * which should use an array as its result. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - * @returns A Promise, if no callback is passed - * @example - * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * // dir4 does not exist - * - * let directoryList = ['dir1','dir2','dir3']; - * let withMissingDirectoryList = ['dir1','dir2','dir3', 'dir4']; - * - * // Using callbacks - * async.concat(directoryList, fs.readdir, function(err, results) { - * if (err) { - * console.log(err); - * } else { - * console.log(results); - * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] - * } - * }); - * - * // Error Handling - * async.concat(withMissingDirectoryList, fs.readdir, function(err, results) { - * if (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * // since dir4 does not exist - * } else { - * console.log(results); - * } - * }); - * - * // Using Promises - * async.concat(directoryList, fs.readdir) - * .then(results => { - * console.log(results); - * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] - * }).catch(err => { - * console.log(err); - * }); - * - * // Error Handling - * async.concat(withMissingDirectoryList, fs.readdir) - * .then(results => { - * console.log(results); - * }).catch(err => { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * // since dir4 does not exist - * }); - * - * // Using async/await - * async () => { - * try { - * let results = await async.concat(directoryList, fs.readdir); - * console.log(results); - * // [ 'file1.txt', 'file2.txt', 'file3.txt', 'file4.txt', file5.txt ] - * } catch (err) { - * console.log(err); - * } - * } - * - * // Error Handling - * async () => { - * try { - * let results = await async.concat(withMissingDirectoryList, fs.readdir); - * console.log(results); - * } catch (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * // since dir4 does not exist - * } - * } - * + * Default permissions for directories. */ - function concat(coll, iteratee, callback) { - return concatLimit$1(coll, Infinity, iteratee, callback) - } - var concat$1 = awaitify(concat, 3); + DEFAULT_DIR_PERM: 493, // 0755 /** - * The same as [`concat`]{@link module:Collections.concat} but runs only a single async operation at a time. - * - * @name concatSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.concat]{@link module:Collections.concat} - * @category Collection - * @alias flatMapSeries - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each item in `coll`. - * The iteratee should complete with an array an array of results. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is an array - * containing the concatenated results of the `iteratee` function. Invoked with - * (err, results). - * @returns A Promise, if no callback is passed + * Default permissions for plain files. */ - function concatSeries(coll, iteratee, callback) { - return concatLimit$1(coll, 1, iteratee, callback) - } - var concatSeries$1 = awaitify(concatSeries, 3); + DEFAULT_FILE_PERM: 420 // 0644 +}; - /** - * Returns a function that when called, calls-back with the values provided. - * Useful as the first function in a [`waterfall`]{@link module:ControlFlow.waterfall}, or for plugging values in to - * [`auto`]{@link module:ControlFlow.auto}. - * - * @name constant - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {...*} arguments... - Any number of arguments to automatically invoke - * callback with. - * @returns {AsyncFunction} Returns a function that when invoked, automatically - * invokes the callback with the previous given arguments. - * @example - * - * async.waterfall([ - * async.constant(42), - * function (value, next) { - * // value === 42 - * }, - * //... - * ], callback); - * - * async.waterfall([ - * async.constant(filename, "utf8"), - * fs.readFile, - * function (fileData, next) { - * //... - * } - * //... - * ], callback); - * - * async.auto({ - * hostname: async.constant("https://server.net/"), - * port: findFreePort, - * launchServer: ["hostname", "port", function (options, cb) { - * startServer(options, cb); - * }], - * //... - * }, callback); - */ - function constant$1(...args) { - return function (...ignoredArgs/*, callback*/) { - var callback = ignoredArgs.pop(); - return callback(null, ...args); - }; - } +/***/ }), - function _createTester(check, getResult) { - return (eachfn, arr, _iteratee, cb) => { - var testPassed = false; - var testResult; - const iteratee = wrapAsync(_iteratee); - eachfn(arr, (value, _, callback) => { - iteratee(value, (err, result) => { - if (err || err === false) return callback(err); +/***/ 68682: +/***/ ((module) => { - if (check(result) && !testResult) { - testPassed = true; - testResult = getResult(true, value); - return callback(null, breakLoop$1); - } - callback(); - }); - }, err => { - if (err) return cb(err); - cb(null, testPassed ? testResult : getResult(false)); - }); - }; - } +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +var util = module.exports = {}; - /** - * Returns the first value in `coll` that passes an async truth test. The - * `iteratee` is applied in parallel, meaning the first iteratee to return - * `true` will fire the detect `callback` with that result. That means the - * result might not be the first item in the original `coll` (in terms of order) - * that passes the test. +util.dateToDos = function(d, forceLocalTime) { + forceLocalTime = forceLocalTime || false; - * If order within the original `coll` is important, then look at - * [`detectSeries`]{@link module:Collections.detectSeries}. - * - * @name detect - * @static - * @memberOf module:Collections - * @method - * @alias find - * @category Collections - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @returns {Promise} a promise, if a callback is omitted - * @example - * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * - * // asynchronous function that checks if a file exists - * function fileExists(file, callback) { - * fs.access(file, fs.constants.F_OK, (err) => { - * callback(null, !err); - * }); - * } - * - * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists, - * function(err, result) { - * console.log(result); - * // dir1/file1.txt - * // result now equals the first file in the list that exists - * } - *); - * - * // Using Promises - * async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists) - * .then(result => { - * console.log(result); - * // dir1/file1.txt - * // result now equals the first file in the list that exists - * }).catch(err => { - * console.log(err); - * }); - * - * // Using async/await - * async () => { - * try { - * let result = await async.detect(['file3.txt','file2.txt','dir1/file1.txt'], fileExists); - * console.log(result); - * // dir1/file1.txt - * // result now equals the file in the list that exists - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function detect(coll, iteratee, callback) { - return _createTester(bool => bool, (res, item) => item)(eachOf$1, coll, iteratee, callback) - } - var detect$1 = awaitify(detect, 3); + var year = forceLocalTime ? d.getFullYear() : d.getUTCFullYear(); - /** - * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a - * time. - * - * @name detectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findLimit - * @category Collections - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @returns {Promise} a promise, if a callback is omitted - */ - function detectLimit(coll, limit, iteratee, callback) { - return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(limit), coll, iteratee, callback) - } - var detectLimit$1 = awaitify(detectLimit, 4); + if (year < 1980) { + return 2162688; // 1980-1-1 00:00:00 + } else if (year >= 2044) { + return 2141175677; // 2043-12-31 23:59:58 + } - /** - * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. - * - * @name detectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findSeries - * @category Collections - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @returns {Promise} a promise, if a callback is omitted - */ - function detectSeries(coll, iteratee, callback) { - return _createTester(bool => bool, (res, item) => item)(eachOfLimit$2(1), coll, iteratee, callback) - } + var val = { + year: year, + month: forceLocalTime ? d.getMonth() : d.getUTCMonth(), + date: forceLocalTime ? d.getDate() : d.getUTCDate(), + hours: forceLocalTime ? d.getHours() : d.getUTCHours(), + minutes: forceLocalTime ? d.getMinutes() : d.getUTCMinutes(), + seconds: forceLocalTime ? d.getSeconds() : d.getUTCSeconds() + }; - var detectSeries$1 = awaitify(detectSeries, 3); + return ((val.year - 1980) << 25) | ((val.month + 1) << 21) | (val.date << 16) | + (val.hours << 11) | (val.minutes << 5) | (val.seconds / 2); +}; - function consoleFunc(name) { - return (fn, ...args) => wrapAsync(fn)(...args, (err, ...resultArgs) => { - /* istanbul ignore else */ - if (typeof console === 'object') { - /* istanbul ignore else */ - if (err) { - /* istanbul ignore else */ - if (console.error) { - console.error(err); - } - } else if (console[name]) { /* istanbul ignore else */ - resultArgs.forEach(x => console[name](x)); - } - } - }) - } +util.dosToDate = function(dos) { + return new Date(((dos >> 25) & 0x7f) + 1980, ((dos >> 21) & 0x0f) - 1, (dos >> 16) & 0x1f, (dos >> 11) & 0x1f, (dos >> 5) & 0x3f, (dos & 0x1f) << 1); +}; - /** - * Logs the result of an [`async` function]{@link AsyncFunction} to the - * `console` using `console.dir` to display the properties of the resulting object. - * Only works in Node.js or in browsers that support `console.dir` and - * `console.error` (such as FF and Chrome). - * If multiple arguments are returned from the async function, - * `console.dir` is called on each argument in order. - * - * @name dir - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, {hello: name}); - * }, 1000); - * }; - * - * // in the node repl - * node> async.dir(hello, 'world'); - * {hello: 'world'} - */ - var dir = consoleFunc('dir'); +util.fromDosTime = function(buf) { + return util.dosToDate(buf.readUInt32LE(0)); +}; - /** - * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in - * the order of operations, the arguments `test` and `iteratee` are switched. - * - * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. - * - * @name doWhilst - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - A function which is called each time `test` - * passes. Invoked with (callback). - * @param {AsyncFunction} test - asynchronous truth test to perform after each - * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the - * non-error args from the previous callback of `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. - * `callback` will be passed an error and any arguments passed to the final - * `iteratee`'s callback. Invoked with (err, [results]); - * @returns {Promise} a promise, if no callback is passed - */ - function doWhilst(iteratee, test, callback) { - callback = onlyOnce(callback); - var _fn = wrapAsync(iteratee); - var _test = wrapAsync(test); - var results; +util.getEightBytes = function(v) { + var buf = Buffer.alloc(8); + buf.writeUInt32LE(v % 0x0100000000, 0); + buf.writeUInt32LE((v / 0x0100000000) | 0, 4); - function next(err, ...args) { - if (err) return callback(err); - if (err === false) return; - results = args; - _test(...args, check); - } + return buf; +}; - function check(err, truth) { - if (err) return callback(err); - if (err === false) return; - if (!truth) return callback(null, ...results); - _fn(next); - } +util.getShortBytes = function(v) { + var buf = Buffer.alloc(2); + buf.writeUInt16LE((v & 0xFFFF) >>> 0, 0); - return check(null, true); - } + return buf; +}; - var doWhilst$1 = awaitify(doWhilst, 3); +util.getShortBytesValue = function(buf, offset) { + return buf.readUInt16LE(offset); +}; - /** - * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the - * argument ordering differs from `until`. - * - * @name doUntil - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {AsyncFunction} test - asynchronous truth test to perform after each - * execution of `iteratee`. Invoked with (...args, callback), where `...args` are the - * non-error args from the previous callback of `iteratee` - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns {Promise} a promise, if no callback is passed - */ - function doUntil(iteratee, test, callback) { - const _test = wrapAsync(test); - return doWhilst$1(iteratee, (...args) => { - const cb = args.pop(); - _test(...args, (err, truth) => cb (err, !truth)); - }, callback); - } +util.getLongBytes = function(v) { + var buf = Buffer.alloc(4); + buf.writeUInt32LE((v & 0xFFFFFFFF) >>> 0, 0); - function _withoutIndex(iteratee) { - return (value, index, callback) => iteratee(value, callback); - } + return buf; +}; - /** - * Applies the function `iteratee` to each item in `coll`, in parallel. - * The `iteratee` is called with an item from the list, and a callback for when - * it has finished. If the `iteratee` passes an error to its `callback`, the - * main `callback` (for the `each` function) is immediately called with the - * error. - * - * Note, that since this function applies `iteratee` to each item in parallel, - * there is no guarantee that the iteratee functions will complete in order. - * - * @name each - * @static - * @memberOf module:Collections - * @method - * @alias forEach - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to - * each item in `coll`. Invoked with (item, callback). - * The array index is not passed to the iteratee. - * If you need the index, use `eachOf`. - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @returns {Promise} a promise, if a callback is omitted - * @example - * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * // dir4 does not exist - * - * const fileList = [ 'dir1/file2.txt', 'dir2/file3.txt', 'dir/file5.txt']; - * const withMissingFileList = ['dir1/file1.txt', 'dir4/file2.txt']; - * - * // asynchronous function that deletes a file - * const deleteFile = function(file, callback) { - * fs.unlink(file, callback); - * }; - * - * // Using callbacks - * async.each(fileList, deleteFile, function(err) { - * if( err ) { - * console.log(err); - * } else { - * console.log('All files have been deleted successfully'); - * } - * }); - * - * // Error Handling - * async.each(withMissingFileList, deleteFile, function(err){ - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * // since dir4/file2.txt does not exist - * // dir1/file1.txt could have been deleted - * }); - * - * // Using Promises - * async.each(fileList, deleteFile) - * .then( () => { - * console.log('All files have been deleted successfully'); - * }).catch( err => { - * console.log(err); - * }); - * - * // Error Handling - * async.each(fileList, deleteFile) - * .then( () => { - * console.log('All files have been deleted successfully'); - * }).catch( err => { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * // since dir4/file2.txt does not exist - * // dir1/file1.txt could have been deleted - * }); - * - * // Using async/await - * async () => { - * try { - * await async.each(files, deleteFile); - * } - * catch (err) { - * console.log(err); - * } - * } - * - * // Error Handling - * async () => { - * try { - * await async.each(withMissingFileList, deleteFile); - * } - * catch (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * // since dir4/file2.txt does not exist - * // dir1/file1.txt could have been deleted - * } - * } - * - */ - function eachLimit$2(coll, iteratee, callback) { - return eachOf$1(coll, _withoutIndex(wrapAsync(iteratee)), callback); - } +util.getLongBytesValue = function(buf, offset) { + return buf.readUInt32LE(offset); +}; - var each = awaitify(eachLimit$2, 3); +util.toDosTime = function(d) { + return util.getLongBytes(util.dateToDos(d)); +}; - /** - * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. - * - * @name eachLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachLimit - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfLimit`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @returns {Promise} a promise, if a callback is omitted - */ - function eachLimit(coll, limit, iteratee, callback) { - return eachOfLimit$2(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); - } - var eachLimit$1 = awaitify(eachLimit, 4); +/***/ }), - /** - * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. - * - * Note, that unlike [`each`]{@link module:Collections.each}, this function applies iteratee to each item - * in series and therefore the iteratee functions will complete in order. +/***/ 3179: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - * @name eachSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachSeries - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfSeries`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @returns {Promise} a promise, if a callback is omitted - */ - function eachSeries(coll, iteratee, callback) { - return eachLimit$1(coll, 1, iteratee, callback) - } - var eachSeries$1 = awaitify(eachSeries, 3); +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +var inherits = (__nccwpck_require__(73837).inherits); +var normalizePath = __nccwpck_require__(55388); - /** - * Wrap an async function and ensure it calls its callback on a later tick of - * the event loop. If the function already calls its callback on a next tick, - * no extra deferral is added. This is useful for preventing stack overflows - * (`RangeError: Maximum call stack size exceeded`) and generally keeping - * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) - * contained. ES2017 `async` functions are returned as-is -- they are immune - * to Zalgo's corrupting influences, as they always resolve on a later tick. - * - * @name ensureAsync - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - an async function, one that expects a node-style - * callback as its last argument. - * @returns {AsyncFunction} Returns a wrapped function with the exact same call - * signature as the function passed in. - * @example - * - * function sometimesAsync(arg, callback) { - * if (cache[arg]) { - * return callback(null, cache[arg]); // this would be synchronous!! - * } else { - * doSomeIO(arg, callback); // this IO would be asynchronous - * } - * } - * - * // this has a risk of stack overflows if many results are cached in a row - * async.mapSeries(args, sometimesAsync, done); - * - * // this will defer sometimesAsync's callback if necessary, - * // preventing stack overflows - * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); - */ - function ensureAsync(fn) { - if (isAsync(fn)) return fn; - return function (...args/*, callback*/) { - var callback = args.pop(); - var sync = true; - args.push((...innerArgs) => { - if (sync) { - setImmediate$1(() => callback(...innerArgs)); - } else { - callback(...innerArgs); - } - }); - fn.apply(this, args); - sync = false; - }; - } +var ArchiveEntry = __nccwpck_require__(92240); +var GeneralPurposeBit = __nccwpck_require__(63229); +var UnixStat = __nccwpck_require__(70713); - /** - * Returns `true` if every element in `coll` satisfies an async test. If any - * iteratee call returns `false`, the main `callback` is immediately called. - * - * @name every - * @static - * @memberOf module:Collections - * @method - * @alias all - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @returns {Promise} a promise, if no callback provided - * @example - * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * // dir4 does not exist - * - * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file5.txt']; - * const withMissingFileList = ['file1.txt','file2.txt','file4.txt']; - * - * // asynchronous function that checks if a file exists - * function fileExists(file, callback) { - * fs.access(file, fs.constants.F_OK, (err) => { - * callback(null, !err); - * }); - * } - * - * // Using callbacks - * async.every(fileList, fileExists, function(err, result) { - * console.log(result); - * // true - * // result is true since every file exists - * }); - * - * async.every(withMissingFileList, fileExists, function(err, result) { - * console.log(result); - * // false - * // result is false since NOT every file exists - * }); - * - * // Using Promises - * async.every(fileList, fileExists) - * .then( result => { - * console.log(result); - * // true - * // result is true since every file exists - * }).catch( err => { - * console.log(err); - * }); - * - * async.every(withMissingFileList, fileExists) - * .then( result => { - * console.log(result); - * // false - * // result is false since NOT every file exists - * }).catch( err => { - * console.log(err); - * }); - * - * // Using async/await - * async () => { - * try { - * let result = await async.every(fileList, fileExists); - * console.log(result); - * // true - * // result is true since every file exists - * } - * catch (err) { - * console.log(err); - * } - * } - * - * async () => { - * try { - * let result = await async.every(withMissingFileList, fileExists); - * console.log(result); - * // false - * // result is false since NOT every file exists - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function every(coll, iteratee, callback) { - return _createTester(bool => !bool, res => !res)(eachOf$1, coll, iteratee, callback) - } - var every$1 = awaitify(every, 3); +var constants = __nccwpck_require__(11704); +var zipUtil = __nccwpck_require__(68682); - /** - * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. - * - * @name everyLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allLimit - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @returns {Promise} a promise, if no callback provided - */ - function everyLimit(coll, limit, iteratee, callback) { - return _createTester(bool => !bool, res => !res)(eachOfLimit$2(limit), coll, iteratee, callback) - } - var everyLimit$1 = awaitify(everyLimit, 4); +var ZipArchiveEntry = module.exports = function(name) { + if (!(this instanceof ZipArchiveEntry)) { + return new ZipArchiveEntry(name); + } - /** - * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. - * - * @name everySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allSeries - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in series. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @returns {Promise} a promise, if no callback provided - */ - function everySeries(coll, iteratee, callback) { - return _createTester(bool => !bool, res => !res)(eachOfSeries$1, coll, iteratee, callback) - } - var everySeries$1 = awaitify(everySeries, 3); + ArchiveEntry.call(this); - function filterArray(eachfn, arr, iteratee, callback) { - var truthValues = new Array(arr.length); - eachfn(arr, (x, index, iterCb) => { - iteratee(x, (err, v) => { - truthValues[index] = !!v; - iterCb(err); - }); - }, err => { - if (err) return callback(err); - var results = []; - for (var i = 0; i < arr.length; i++) { - if (truthValues[i]) results.push(arr[i]); - } - callback(null, results); - }); - } + this.platform = constants.PLATFORM_FAT; + this.method = -1; - function filterGeneric(eachfn, coll, iteratee, callback) { - var results = []; - eachfn(coll, (x, index, iterCb) => { - iteratee(x, (err, v) => { - if (err) return iterCb(err); - if (v) { - results.push({index, value: x}); - } - iterCb(err); - }); - }, err => { - if (err) return callback(err); - callback(null, results - .sort((a, b) => a.index - b.index) - .map(v => v.value)); - }); - } + this.name = null; + this.size = 0; + this.csize = 0; + this.gpb = new GeneralPurposeBit(); + this.crc = 0; + this.time = -1; - function _filter(eachfn, coll, iteratee, callback) { - var filter = isArrayLike(coll) ? filterArray : filterGeneric; - return filter(eachfn, coll, wrapAsync(iteratee), callback); - } + this.minver = constants.MIN_VERSION_INITIAL; + this.mode = -1; + this.extra = null; + this.exattr = 0; + this.inattr = 0; + this.comment = null; - /** - * Returns a new array of all the values in `coll` which pass an async truth - * test. This operation is performed in parallel, but the results array will be - * in the same order as the original. - * - * @name filter - * @static - * @memberOf module:Collections - * @method - * @alias select - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @returns {Promise} a promise, if no callback provided - * @example - * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * - * const files = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; - * - * // asynchronous function that checks if a file exists - * function fileExists(file, callback) { - * fs.access(file, fs.constants.F_OK, (err) => { - * callback(null, !err); - * }); - * } - * - * // Using callbacks - * async.filter(files, fileExists, function(err, results) { - * if(err) { - * console.log(err); - * } else { - * console.log(results); - * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] - * // results is now an array of the existing files - * } - * }); - * - * // Using Promises - * async.filter(files, fileExists) - * .then(results => { - * console.log(results); - * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] - * // results is now an array of the existing files - * }).catch(err => { - * console.log(err); - * }); - * - * // Using async/await - * async () => { - * try { - * let results = await async.filter(files, fileExists); - * console.log(results); - * // [ 'dir1/file1.txt', 'dir2/file3.txt' ] - * // results is now an array of the existing files - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function filter (coll, iteratee, callback) { - return _filter(eachOf$1, coll, iteratee, callback) - } - var filter$1 = awaitify(filter, 3); + if (name) { + this.setName(name); + } +}; - /** - * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a - * time. - * - * @name filterLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectLimit - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @returns {Promise} a promise, if no callback provided - */ - function filterLimit (coll, limit, iteratee, callback) { - return _filter(eachOfLimit$2(limit), coll, iteratee, callback) - } - var filterLimit$1 = awaitify(filterLimit, 4); +inherits(ZipArchiveEntry, ArchiveEntry); - /** - * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. - * - * @name filterSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectSeries - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results) - * @returns {Promise} a promise, if no callback provided - */ - function filterSeries (coll, iteratee, callback) { - return _filter(eachOfSeries$1, coll, iteratee, callback) - } - var filterSeries$1 = awaitify(filterSeries, 3); +/** + * Returns the extra fields related to the entry. + * + * @returns {Buffer} + */ +ZipArchiveEntry.prototype.getCentralDirectoryExtra = function() { + return this.getExtra(); +}; - /** - * Calls the asynchronous function `fn` with a callback parameter that allows it - * to call itself again, in series, indefinitely. +/** + * Returns the comment set for the entry. + * + * @returns {string} + */ +ZipArchiveEntry.prototype.getComment = function() { + return this.comment !== null ? this.comment : ''; +}; - * If an error is passed to the callback then `errback` is called with the - * error, and execution stops, otherwise it will never be called. - * - * @name forever - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} fn - an async function to call repeatedly. - * Invoked with (next). - * @param {Function} [errback] - when `fn` passes an error to it's callback, - * this function will be called, and execution stops. Invoked with (err). - * @returns {Promise} a promise that rejects if an error occurs and an errback - * is not passed - * @example - * - * async.forever( - * function(next) { - * // next is suitable for passing to things that need a callback(err [, whatever]); - * // it will result in this function being called again. - * }, - * function(err) { - * // if next is called with a value in its first parameter, it will appear - * // in here as 'err', and execution will stop. - * } - * ); - */ - function forever(fn, errback) { - var done = onlyOnce(errback); - var task = wrapAsync(ensureAsync(fn)); +/** + * Returns the compressed size of the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getCompressedSize = function() { + return this.csize; +}; - function next(err) { - if (err) return done(err); - if (err === false) return; - task(next); - } - return next(); - } - var forever$1 = awaitify(forever, 2); +/** + * Returns the CRC32 digest for the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getCrc = function() { + return this.crc; +}; - /** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. - * - * @name groupByLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - * @returns {Promise} a promise, if no callback is passed - */ - function groupByLimit(coll, limit, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - return mapLimit$1(coll, limit, (val, iterCb) => { - _iteratee(val, (err, key) => { - if (err) return iterCb(err); - return iterCb(err, {key, val}); - }); - }, (err, mapResults) => { - var result = {}; - // from MDN, handle object having an `hasOwnProperty` prop - var {hasOwnProperty} = Object.prototype; +/** + * Returns the external file attributes for the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getExternalAttributes = function() { + return this.exattr; +}; - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - var {key} = mapResults[i]; - var {val} = mapResults[i]; +/** + * Returns the extra fields related to the entry. + * + * @returns {Buffer} + */ +ZipArchiveEntry.prototype.getExtra = function() { + return this.extra !== null ? this.extra : constants.EMPTY; +}; - if (hasOwnProperty.call(result, key)) { - result[key].push(val); - } else { - result[key] = [val]; - } - } - } +/** + * Returns the general purpose bits related to the entry. + * + * @returns {GeneralPurposeBit} + */ +ZipArchiveEntry.prototype.getGeneralPurposeBit = function() { + return this.gpb; +}; - return callback(err, result); - }); - } +/** + * Returns the internal file attributes for the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getInternalAttributes = function() { + return this.inattr; +}; - var groupByLimit$1 = awaitify(groupByLimit, 4); +/** + * Returns the last modified date of the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getLastModifiedDate = function() { + return this.getTime(); +}; - /** - * Returns a new object, where each value corresponds to an array of items, from - * `coll`, that returned the corresponding key. That is, the keys of the object - * correspond to the values passed to the `iteratee` callback. - * - * Note: Since this function applies the `iteratee` to each item in parallel, - * there is no guarantee that the `iteratee` functions will complete in order. - * However, the values for each key in the `result` will be in the same order as - * the original `coll`. For Objects, the values will roughly be in the order of - * the original Objects' keys (but this can vary across JavaScript engines). - * - * @name groupBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - * @returns {Promise} a promise, if no callback is passed - * @example - * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * // dir4 does not exist - * - * const files = ['dir1/file1.txt','dir2','dir4'] - * - * // asynchronous function that detects file type as none, file, or directory - * function detectFile(file, callback) { - * fs.stat(file, function(err, stat) { - * if (err) { - * return callback(null, 'none'); - * } - * callback(null, stat.isDirectory() ? 'directory' : 'file'); - * }); - * } - * - * //Using callbacks - * async.groupBy(files, detectFile, function(err, result) { - * if(err) { - * console.log(err); - * } else { - * console.log(result); - * // { - * // file: [ 'dir1/file1.txt' ], - * // none: [ 'dir4' ], - * // directory: [ 'dir2'] - * // } - * // result is object containing the files grouped by type - * } - * }); - * - * // Using Promises - * async.groupBy(files, detectFile) - * .then( result => { - * console.log(result); - * // { - * // file: [ 'dir1/file1.txt' ], - * // none: [ 'dir4' ], - * // directory: [ 'dir2'] - * // } - * // result is object containing the files grouped by type - * }).catch( err => { - * console.log(err); - * }); - * - * // Using async/await - * async () => { - * try { - * let result = await async.groupBy(files, detectFile); - * console.log(result); - * // { - * // file: [ 'dir1/file1.txt' ], - * // none: [ 'dir4' ], - * // directory: [ 'dir2'] - * // } - * // result is object containing the files grouped by type - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function groupBy (coll, iteratee, callback) { - return groupByLimit$1(coll, Infinity, iteratee, callback) - } - - /** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. - * - * @name groupBySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whose - * properties are arrays of values which returned the corresponding key. - * @returns {Promise} a promise, if no callback is passed - */ - function groupBySeries (coll, iteratee, callback) { - return groupByLimit$1(coll, 1, iteratee, callback) - } +/** + * Returns the extra fields related to the entry. + * + * @returns {Buffer} + */ +ZipArchiveEntry.prototype.getLocalFileDataExtra = function() { + return this.getExtra(); +}; - /** - * Logs the result of an `async` function to the `console`. Only works in - * Node.js or in browsers that support `console.log` and `console.error` (such - * as FF and Chrome). If multiple arguments are returned from the async - * function, `console.log` is called on each argument in order. - * - * @name log - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, 'hello ' + name); - * }, 1000); - * }; - * - * // in the node repl - * node> async.log(hello, 'world'); - * 'hello world' - */ - var log = consoleFunc('log'); +/** + * Returns the compression method used on the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getMethod = function() { + return this.method; +}; - /** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a - * time. - * - * @name mapValuesLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - * @returns {Promise} a promise, if no callback is passed - */ - function mapValuesLimit(obj, limit, iteratee, callback) { - callback = once(callback); - var newObj = {}; - var _iteratee = wrapAsync(iteratee); - return eachOfLimit$2(limit)(obj, (val, key, next) => { - _iteratee(val, key, (err, result) => { - if (err) return next(err); - newObj[key] = result; - next(err); - }); - }, err => callback(err, newObj)); - } +/** + * Returns the filename of the entry. + * + * @returns {string} + */ +ZipArchiveEntry.prototype.getName = function() { + return this.name; +}; - var mapValuesLimit$1 = awaitify(mapValuesLimit, 4); +/** + * Returns the platform on which the entry was made. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getPlatform = function() { + return this.platform; +}; - /** - * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. - * - * Produces a new Object by mapping each value of `obj` through the `iteratee` - * function. The `iteratee` is called each `value` and `key` from `obj` and a - * callback for when it has finished processing. Each of these callbacks takes - * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` - * passes an error to its callback, the main `callback` (for the `mapValues` - * function) is immediately called with the error. - * - * Note, the order of the keys in the result is not guaranteed. The keys will - * be roughly in the order they complete, (but this is very engine-specific) - * - * @name mapValues - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - * @returns {Promise} a promise, if no callback is passed - * @example - * - * // file1.txt is a file that is 1000 bytes in size - * // file2.txt is a file that is 2000 bytes in size - * // file3.txt is a file that is 3000 bytes in size - * // file4.txt does not exist - * - * const fileMap = { - * f1: 'file1.txt', - * f2: 'file2.txt', - * f3: 'file3.txt' - * }; - * - * const withMissingFileMap = { - * f1: 'file1.txt', - * f2: 'file2.txt', - * f3: 'file4.txt' - * }; - * - * // asynchronous function that returns the file size in bytes - * function getFileSizeInBytes(file, key, callback) { - * fs.stat(file, function(err, stat) { - * if (err) { - * return callback(err); - * } - * callback(null, stat.size); - * }); - * } - * - * // Using callbacks - * async.mapValues(fileMap, getFileSizeInBytes, function(err, result) { - * if (err) { - * console.log(err); - * } else { - * console.log(result); - * // result is now a map of file size in bytes for each file, e.g. - * // { - * // f1: 1000, - * // f2: 2000, - * // f3: 3000 - * // } - * } - * }); - * - * // Error handling - * async.mapValues(withMissingFileMap, getFileSizeInBytes, function(err, result) { - * if (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * } else { - * console.log(result); - * } - * }); - * - * // Using Promises - * async.mapValues(fileMap, getFileSizeInBytes) - * .then( result => { - * console.log(result); - * // result is now a map of file size in bytes for each file, e.g. - * // { - * // f1: 1000, - * // f2: 2000, - * // f3: 3000 - * // } - * }).catch (err => { - * console.log(err); - * }); - * - * // Error Handling - * async.mapValues(withMissingFileMap, getFileSizeInBytes) - * .then( result => { - * console.log(result); - * }).catch (err => { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * }); - * - * // Using async/await - * async () => { - * try { - * let result = await async.mapValues(fileMap, getFileSizeInBytes); - * console.log(result); - * // result is now a map of file size in bytes for each file, e.g. - * // { - * // f1: 1000, - * // f2: 2000, - * // f3: 3000 - * // } - * } - * catch (err) { - * console.log(err); - * } - * } - * - * // Error Handling - * async () => { - * try { - * let result = await async.mapValues(withMissingFileMap, getFileSizeInBytes); - * console.log(result); - * } - * catch (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * } - * } - * - */ - function mapValues(obj, iteratee, callback) { - return mapValuesLimit$1(obj, Infinity, iteratee, callback) - } +/** + * Returns the size of the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getSize = function() { + return this.size; +}; - /** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. - * - * @name mapValuesSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - * @returns {Promise} a promise, if no callback is passed - */ - function mapValuesSeries(obj, iteratee, callback) { - return mapValuesLimit$1(obj, 1, iteratee, callback) - } +/** + * Returns a date object representing the last modified date of the entry. + * + * @returns {number|Date} + */ +ZipArchiveEntry.prototype.getTime = function() { + return this.time !== -1 ? zipUtil.dosToDate(this.time) : -1; +}; - /** - * Caches the results of an async function. When creating a hash to store - * function results against, the callback is omitted from the hash and an - * optional hash function can be used. - * - * **Note: if the async function errs, the result will not be cached and - * subsequent calls will call the wrapped function.** - * - * If no hash function is specified, the first argument is used as a hash key, - * which may work reasonably if it is a string or a data type that converts to a - * distinct string. Note that objects and arrays will not behave reasonably. - * Neither will cases where the other arguments are significant. In such cases, - * specify your own hash function. - * - * The cache of results is exposed as the `memo` property of the function - * returned by `memoize`. - * - * @name memoize - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function to proxy and cache results from. - * @param {Function} hasher - An optional function for generating a custom hash - * for storing results. It has all the arguments applied to it apart from the - * callback, and must be synchronous. - * @returns {AsyncFunction} a memoized version of `fn` - * @example - * - * var slow_fn = function(name, callback) { - * // do something - * callback(null, result); - * }; - * var fn = async.memoize(slow_fn); - * - * // fn can now be used as if it were slow_fn - * fn('some name', function() { - * // callback - * }); - */ - function memoize(fn, hasher = v => v) { - var memo = Object.create(null); - var queues = Object.create(null); - var _fn = wrapAsync(fn); - var memoized = initialParams((args, callback) => { - var key = hasher(...args); - if (key in memo) { - setImmediate$1(() => callback(null, ...memo[key])); - } else if (key in queues) { - queues[key].push(callback); - } else { - queues[key] = [callback]; - _fn(...args, (err, ...resultArgs) => { - // #1465 don't memoize if an error occurred - if (!err) { - memo[key] = resultArgs; - } - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i](err, ...resultArgs); - } - }); - } - }); - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; - } +/** + * Returns the DOS timestamp for the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getTimeDos = function() { + return this.time !== -1 ? this.time : 0; +}; - /* istanbul ignore file */ +/** + * Returns the UNIX file permissions for the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getUnixMode = function() { + return this.platform !== constants.PLATFORM_UNIX ? 0 : ((this.getExternalAttributes() >> constants.SHORT_SHIFT) & constants.SHORT_MASK); +}; - /** - * Calls `callback` on a later loop around the event loop. In Node.js this just - * calls `process.nextTick`. In the browser it will use `setImmediate` if - * available, otherwise `setTimeout(callback, 0)`, which means other higher - * priority events may precede the execution of `callback`. - * - * This is used internally for browser-compatibility purposes. - * - * @name nextTick - * @static - * @memberOf module:Utils - * @method - * @see [async.setImmediate]{@link module:Utils.setImmediate} - * @category Util - * @param {Function} callback - The function to call on a later loop around - * the event loop. Invoked with (args...). - * @param {...*} args... - any number of additional arguments to pass to the - * callback on the next tick. - * @example - * - * var call_order = []; - * async.nextTick(function() { - * call_order.push('two'); - * // call_order now equals ['one','two'] - * }); - * call_order.push('one'); - * - * async.setImmediate(function (a, b, c) { - * // a, b, and c equal 1, 2, and 3 - * }, 1, 2, 3); - */ - var _defer; +/** + * Returns the version of ZIP needed to extract the entry. + * + * @returns {number} + */ +ZipArchiveEntry.prototype.getVersionNeededToExtract = function() { + return this.minver; +}; - if (hasNextTick) { - _defer = process.nextTick; - } else if (hasSetImmediate) { - _defer = setImmediate; - } else { - _defer = fallback; - } - - var nextTick = wrap(_defer); +/** + * Sets the comment of the entry. + * + * @param comment + */ +ZipArchiveEntry.prototype.setComment = function(comment) { + if (Buffer.byteLength(comment) !== comment.length) { + this.getGeneralPurposeBit().useUTF8ForNames(true); + } - var _parallel = awaitify((eachfn, tasks, callback) => { - var results = isArrayLike(tasks) ? [] : {}; + this.comment = comment; +}; - eachfn(tasks, (task, key, taskCb) => { - wrapAsync(task)((err, ...result) => { - if (result.length < 2) { - [result] = result; - } - results[key] = result; - taskCb(err); - }); - }, err => callback(err, results)); - }, 3); +/** + * Sets the compressed size of the entry. + * + * @param size + */ +ZipArchiveEntry.prototype.setCompressedSize = function(size) { + if (size < 0) { + throw new Error('invalid entry compressed size'); + } - /** - * Run the `tasks` collection of functions in parallel, without waiting until - * the previous function has completed. If any of the functions pass an error to - * its callback, the main `callback` is immediately called with the value of the - * error. Once the `tasks` have completed, the results are passed to the final - * `callback` as an array. - * - * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about - * parallel execution of code. If your tasks do not use any timers or perform - * any I/O, they will actually be executed in series. Any synchronous setup - * sections for each task will happen one after the other. JavaScript remains - * single-threaded. - * - * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the - * execution of other tasks when a task fails. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.parallel}. - * - * @name parallel - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - * @returns {Promise} a promise, if a callback is not passed - * - * @example - * - * //Using Callbacks - * async.parallel([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], function(err, results) { - * console.log(results); - * // results is equal to ['one','two'] even though - * // the second function had a shorter timeout. - * }); - * - * // an example using an object instead of an array - * async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * console.log(results); - * // results is equal to: { one: 1, two: 2 } - * }); - * - * //Using Promises - * async.parallel([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]).then(results => { - * console.log(results); - * // results is equal to ['one','two'] even though - * // the second function had a shorter timeout. - * }).catch(err => { - * console.log(err); - * }); - * - * // an example using an object instead of an array - * async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }).then(results => { - * console.log(results); - * // results is equal to: { one: 1, two: 2 } - * }).catch(err => { - * console.log(err); - * }); - * - * //Using async/await - * async () => { - * try { - * let results = await async.parallel([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]); - * console.log(results); - * // results is equal to ['one','two'] even though - * // the second function had a shorter timeout. - * } - * catch (err) { - * console.log(err); - * } - * } - * - * // an example using an object instead of an array - * async () => { - * try { - * let results = await async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }); - * console.log(results); - * // results is equal to: { one: 1, two: 2 } - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function parallel(tasks, callback) { - return _parallel(eachOf$1, tasks, callback); - } + this.csize = size; +}; - /** - * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a - * time. - * - * @name parallelLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.parallel]{@link module:ControlFlow.parallel} - * @category Control Flow - * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - * @returns {Promise} a promise, if a callback is not passed - */ - function parallelLimit(tasks, limit, callback) { - return _parallel(eachOfLimit$2(limit), tasks, callback); - } +/** + * Sets the checksum of the entry. + * + * @param crc + */ +ZipArchiveEntry.prototype.setCrc = function(crc) { + if (crc < 0) { + throw new Error('invalid entry crc32'); + } - /** - * A queue of tasks for the worker function to complete. - * @typedef {Iterable} QueueObject - * @memberOf module:ControlFlow - * @property {Function} length - a function returning the number of items - * waiting to be processed. Invoke with `queue.length()`. - * @property {boolean} started - a boolean indicating whether or not any - * items have been pushed and processed by the queue. - * @property {Function} running - a function returning the number of items - * currently being processed. Invoke with `queue.running()`. - * @property {Function} workersList - a function returning the array of items - * currently being processed. Invoke with `queue.workersList()`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke with `queue.idle()`. - * @property {number} concurrency - an integer for determining how many `worker` - * functions should be run in parallel. This property can be changed after a - * `queue` is created to alter the concurrency on-the-fly. - * @property {number} payload - an integer that specifies how many items are - * passed to the worker function at a time. only applies if this is a - * [cargo]{@link module:ControlFlow.cargo} object - * @property {AsyncFunction} push - add a new task to the `queue`. Calls `callback` - * once the `worker` has finished processing the task. Instead of a single task, - * a `tasks` array can be submitted. The respective callback is used for every - * task in the list. Invoke with `queue.push(task, [callback])`, - * @property {AsyncFunction} unshift - add a new task to the front of the `queue`. - * Invoke with `queue.unshift(task, [callback])`. - * @property {AsyncFunction} pushAsync - the same as `q.push`, except this returns - * a promise that rejects if an error occurs. - * @property {AsyncFunction} unshiftAsync - the same as `q.unshift`, except this returns - * a promise that rejects if an error occurs. - * @property {Function} remove - remove items from the queue that match a test - * function. The test function will be passed an object with a `data` property, - * and a `priority` property, if this is a - * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. - * Invoked with `queue.remove(testFn)`, where `testFn` is of the form - * `function ({data, priority}) {}` and returns a Boolean. - * @property {Function} saturated - a function that sets a callback that is - * called when the number of running workers hits the `concurrency` limit, and - * further tasks will be queued. If the callback is omitted, `q.saturated()` - * returns a promise for the next occurrence. - * @property {Function} unsaturated - a function that sets a callback that is - * called when the number of running workers is less than the `concurrency` & - * `buffer` limits, and further tasks will not be queued. If the callback is - * omitted, `q.unsaturated()` returns a promise for the next occurrence. - * @property {number} buffer - A minimum threshold buffer in order to say that - * the `queue` is `unsaturated`. - * @property {Function} empty - a function that sets a callback that is called - * when the last item from the `queue` is given to a `worker`. If the callback - * is omitted, `q.empty()` returns a promise for the next occurrence. - * @property {Function} drain - a function that sets a callback that is called - * when the last item from the `queue` has returned from the `worker`. If the - * callback is omitted, `q.drain()` returns a promise for the next occurrence. - * @property {Function} error - a function that sets a callback that is called - * when a task errors. Has the signature `function(error, task)`. If the - * callback is omitted, `error()` returns a promise that rejects on the next - * error. - * @property {boolean} paused - a boolean for determining whether the queue is - * in a paused state. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke with `queue.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke with `queue.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. No more tasks - * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. - * - * @example - * const q = async.queue(worker, 2) - * q.push(item1) - * q.push(item2) - * q.push(item3) - * // queues are iterable, spread into an array to inspect - * const items = [...q] // [item1, item2, item3] - * // or use for of - * for (let item of q) { - * console.log(item) - * } - * - * q.drain(() => { - * console.log('all done') - * }) - * // or - * await q.drain() - */ + this.crc = crc; +}; - /** - * Creates a `queue` object with the specified `concurrency`. Tasks added to the - * `queue` are processed in parallel (up to the `concurrency` limit). If all - * `worker`s are in progress, the task is queued until one becomes available. - * Once a `worker` completes a `task`, that `task`'s callback is called. - * - * @name queue - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. Invoked with (task, callback). - * @param {number} [concurrency=1] - An `integer` for determining how many - * `worker` functions should be run in parallel. If omitted, the concurrency - * defaults to `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can be - * attached as certain properties to listen for specific events during the - * lifecycle of the queue. - * @example - * - * // create a queue object with concurrency 2 - * var q = async.queue(function(task, callback) { - * console.log('hello ' + task.name); - * callback(); - * }, 2); - * - * // assign a callback - * q.drain(function() { - * console.log('all items have been processed'); - * }); - * // or await the end - * await q.drain() - * - * // assign an error callback - * q.error(function(err, task) { - * console.error('task experienced an error'); - * }); - * - * // add some items to the queue - * q.push({name: 'foo'}, function(err) { - * console.log('finished processing foo'); - * }); - * // callback is optional - * q.push({name: 'bar'}); - * - * // add some items to the queue (batch-wise) - * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { - * console.log('finished processing item'); - * }); - * - * // add some items to the front of the queue - * q.unshift({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - */ - function queue (worker, concurrency) { - var _worker = wrapAsync(worker); - return queue$1((items, cb) => { - _worker(items[0], cb); - }, concurrency, 1); - } +/** + * Sets the external file attributes of the entry. + * + * @param attr + */ +ZipArchiveEntry.prototype.setExternalAttributes = function(attr) { + this.exattr = attr >>> 0; +}; - // Binary min-heap implementation used for priority queue. - // Implementation is stable, i.e. push time is considered for equal priorities - class Heap { - constructor() { - this.heap = []; - this.pushCount = Number.MIN_SAFE_INTEGER; - } +/** + * Sets the extra fields related to the entry. + * + * @param extra + */ +ZipArchiveEntry.prototype.setExtra = function(extra) { + this.extra = extra; +}; - get length() { - return this.heap.length; - } +/** + * Sets the general purpose bits related to the entry. + * + * @param gpb + */ +ZipArchiveEntry.prototype.setGeneralPurposeBit = function(gpb) { + if (!(gpb instanceof GeneralPurposeBit)) { + throw new Error('invalid entry GeneralPurposeBit'); + } - empty () { - this.heap = []; - return this; - } + this.gpb = gpb; +}; - percUp(index) { - let p; +/** + * Sets the internal file attributes of the entry. + * + * @param attr + */ +ZipArchiveEntry.prototype.setInternalAttributes = function(attr) { + this.inattr = attr; +}; - while (index > 0 && smaller(this.heap[index], this.heap[p=parent(index)])) { - let t = this.heap[index]; - this.heap[index] = this.heap[p]; - this.heap[p] = t; +/** + * Sets the compression method of the entry. + * + * @param method + */ +ZipArchiveEntry.prototype.setMethod = function(method) { + if (method < 0) { + throw new Error('invalid entry compression method'); + } - index = p; - } - } + this.method = method; +}; - percDown(index) { - let l; +/** + * Sets the name of the entry. + * + * @param name + * @param prependSlash + */ +ZipArchiveEntry.prototype.setName = function(name, prependSlash = false) { + name = normalizePath(name, false) + .replace(/^\w+:/, '') + .replace(/^(\.\.\/|\/)+/, ''); - while ((l=leftChi(index)) < this.heap.length) { - if (l+1 < this.heap.length && smaller(this.heap[l+1], this.heap[l])) { - l = l+1; - } + if (prependSlash) { + name = `/${name}`; + } - if (smaller(this.heap[index], this.heap[l])) { - break; - } + if (Buffer.byteLength(name) !== name.length) { + this.getGeneralPurposeBit().useUTF8ForNames(true); + } - let t = this.heap[index]; - this.heap[index] = this.heap[l]; - this.heap[l] = t; + this.name = name; +}; - index = l; - } - } +/** + * Sets the platform on which the entry was made. + * + * @param platform + */ +ZipArchiveEntry.prototype.setPlatform = function(platform) { + this.platform = platform; +}; - push(node) { - node.pushCount = ++this.pushCount; - this.heap.push(node); - this.percUp(this.heap.length-1); - } +/** + * Sets the size of the entry. + * + * @param size + */ +ZipArchiveEntry.prototype.setSize = function(size) { + if (size < 0) { + throw new Error('invalid entry size'); + } - unshift(node) { - return this.heap.push(node); - } + this.size = size; +}; - shift() { - let [top] = this.heap; +/** + * Sets the time of the entry. + * + * @param time + * @param forceLocalTime + */ +ZipArchiveEntry.prototype.setTime = function(time, forceLocalTime) { + if (!(time instanceof Date)) { + throw new Error('invalid entry time'); + } - this.heap[0] = this.heap[this.heap.length-1]; - this.heap.pop(); - this.percDown(0); + this.time = zipUtil.dateToDos(time, forceLocalTime); +}; - return top; - } +/** + * Sets the UNIX file permissions for the entry. + * + * @param mode + */ +ZipArchiveEntry.prototype.setUnixMode = function(mode) { + mode |= this.isDirectory() ? constants.S_IFDIR : constants.S_IFREG; - toArray() { - return [...this]; - } + var extattr = 0; + extattr |= (mode << constants.SHORT_SHIFT) | (this.isDirectory() ? constants.S_DOS_D : constants.S_DOS_A); - *[Symbol.iterator] () { - for (let i = 0; i < this.heap.length; i++) { - yield this.heap[i].data; - } - } + this.setExternalAttributes(extattr); + this.mode = mode & constants.MODE_MASK; + this.platform = constants.PLATFORM_UNIX; +}; - remove (testFn) { - let j = 0; - for (let i = 0; i < this.heap.length; i++) { - if (!testFn(this.heap[i])) { - this.heap[j] = this.heap[i]; - j++; - } - } +/** + * Sets the version of ZIP needed to extract this entry. + * + * @param minver + */ +ZipArchiveEntry.prototype.setVersionNeededToExtract = function(minver) { + this.minver = minver; +}; - this.heap.splice(j); +/** + * Returns true if this entry represents a directory. + * + * @returns {boolean} + */ +ZipArchiveEntry.prototype.isDirectory = function() { + return this.getName().slice(-1) === '/'; +}; - for (let i = parent(this.heap.length-1); i >= 0; i--) { - this.percDown(i); - } +/** + * Returns true if this entry represents a unix symlink, + * in which case the entry's content contains the target path + * for the symlink. + * + * @returns {boolean} + */ +ZipArchiveEntry.prototype.isUnixSymlink = function() { + return (this.getUnixMode() & UnixStat.FILE_TYPE_FLAG) === UnixStat.LINK_FLAG; +}; - return this; - } - } +/** + * Returns true if this entry is using the ZIP64 extension of ZIP. + * + * @returns {boolean} + */ +ZipArchiveEntry.prototype.isZip64 = function() { + return this.csize > constants.ZIP64_MAGIC || this.size > constants.ZIP64_MAGIC; +}; - function leftChi(i) { - return (i<<1)+1; - } - function parent(i) { - return ((i+1)>>1)-1; - } +/***/ }), - function smaller(x, y) { - if (x.priority !== y.priority) { - return x.priority < y.priority; - } - else { - return x.pushCount < y.pushCount; - } - } +/***/ 44432: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and - * completed in ascending priority order. - * - * @name priorityQueue - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. - * Invoked with (task, callback). - * @param {number} concurrency - An `integer` for determining how many `worker` - * functions should be run in parallel. If omitted, the concurrency defaults to - * `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are three - * differences between `queue` and `priorityQueue` objects: - * * `push(task, priority, [callback])` - `priority` should be a number. If an - * array of `tasks` is given, all tasks will be assigned the same priority. - * * `pushAsync(task, priority, [callback])` - the same as `priorityQueue.push`, - * except this returns a promise that rejects if an error occurs. - * * The `unshift` and `unshiftAsync` methods were removed. - */ - function priorityQueue(worker, concurrency) { - // Start with a normal queue - var q = queue(worker, concurrency); +/** + * node-compress-commons + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT + */ +var inherits = (__nccwpck_require__(73837).inherits); +var crc32 = __nccwpck_require__(83201); +var {CRC32Stream} = __nccwpck_require__(5101); +var {DeflateCRC32Stream} = __nccwpck_require__(5101); - var { - push, - pushAsync - } = q; +var ArchiveOutputStream = __nccwpck_require__(36728); +var ZipArchiveEntry = __nccwpck_require__(3179); +var GeneralPurposeBit = __nccwpck_require__(63229); - q._tasks = new Heap(); - q._createTaskItem = ({data, priority}, callback) => { - return { - data, - priority, - callback - }; - }; +var constants = __nccwpck_require__(11704); +var util = __nccwpck_require__(95208); +var zipUtil = __nccwpck_require__(68682); - function createDataItems(tasks, priority) { - if (!Array.isArray(tasks)) { - return {data: tasks, priority}; - } - return tasks.map(data => { return {data, priority}; }); - } +var ZipArchiveOutputStream = module.exports = function(options) { + if (!(this instanceof ZipArchiveOutputStream)) { + return new ZipArchiveOutputStream(options); + } - // Override push to accept second parameter representing priority - q.push = function(data, priority = 0, callback) { - return push(createDataItems(data, priority), callback); - }; + options = this.options = this._defaults(options); - q.pushAsync = function(data, priority = 0, callback) { - return pushAsync(createDataItems(data, priority), callback); - }; + ArchiveOutputStream.call(this, options); - // Remove unshift functions - delete q.unshift; - delete q.unshiftAsync; + this._entry = null; + this._entries = []; + this._archive = { + centralLength: 0, + centralOffset: 0, + comment: '', + finish: false, + finished: false, + processing: false, + forceZip64: options.forceZip64, + forceLocalTime: options.forceLocalTime + }; +}; - return q; - } +inherits(ZipArchiveOutputStream, ArchiveOutputStream); - /** - * Runs the `tasks` array of functions in parallel, without waiting until the - * previous function has completed. Once any of the `tasks` complete or pass an - * error to its callback, the main `callback` is immediately called. It's - * equivalent to `Promise.race()`. - * - * @name race - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} - * to run. Each function can complete with an optional `result` value. - * @param {Function} callback - A callback to run once any of the functions have - * completed. This function gets an error or result from the first function that - * completed. Invoked with (err, result). - * @returns {Promise} a promise, if a callback is omitted - * @example - * - * async.race([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // main callback - * function(err, result) { - * // the result will be equal to 'two' as it finishes earlier - * }); - */ - function race(tasks, callback) { - callback = once(callback); - if (!Array.isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); - if (!tasks.length) return callback(); - for (var i = 0, l = tasks.length; i < l; i++) { - wrapAsync(tasks[i])(callback); - } - } +ZipArchiveOutputStream.prototype._afterAppend = function(ae) { + this._entries.push(ae); - var race$1 = awaitify(race, 2); + if (ae.getGeneralPurposeBit().usesDataDescriptor()) { + this._writeDataDescriptor(ae); + } - /** - * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. - * - * @name reduceRight - * @static - * @memberOf module:Collections - * @method - * @see [async.reduce]{@link module:Collections.reduce} - * @alias foldr - * @category Collection - * @param {Array} array - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee completes with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - * @returns {Promise} a promise, if no callback is passed - */ - function reduceRight (array, memo, iteratee, callback) { - var reversed = [...array].reverse(); - return reduce$1(reversed, memo, iteratee, callback); - } + this._archive.processing = false; + this._entry = null; - /** - * Wraps the async function in another function that always completes with a - * result object, even when it errors. - * - * The result object has either the property `error` or `value`. - * - * @name reflect - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function you want to wrap - * @returns {Function} - A function that always passes null to it's callback as - * the error. The second argument to the callback will be an `object` with - * either an `error` or a `value` property. - * @example - * - * async.parallel([ - * async.reflect(function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }), - * async.reflect(function(callback) { - * // do some more stuff but error ... - * callback('bad stuff happened'); - * }), - * async.reflect(function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * }) - * ], - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = 'bad stuff happened' - * // results[2].value = 'two' - * }); - */ - function reflect(fn) { - var _fn = wrapAsync(fn); - return initialParams(function reflectOn(args, reflectCallback) { - args.push((error, ...cbArgs) => { - let retVal = {}; - if (error) { - retVal.error = error; - } - if (cbArgs.length > 0){ - var value = cbArgs; - if (cbArgs.length <= 1) { - [value] = cbArgs; - } - retVal.value = value; - } - reflectCallback(null, retVal); - }); + if (this._archive.finish && !this._archive.finished) { + this._finish(); + } +}; - return _fn.apply(this, args); - }); - } +ZipArchiveOutputStream.prototype._appendBuffer = function(ae, source, callback) { + if (source.length === 0) { + ae.setMethod(constants.METHOD_STORED); + } - /** - * A helper function that wraps an array or an object of functions with `reflect`. - * - * @name reflectAll - * @static - * @memberOf module:Utils - * @method - * @see [async.reflect]{@link module:Utils.reflect} - * @category Util - * @param {Array|Object|Iterable} tasks - The collection of - * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. - * @returns {Array} Returns an array of async functions, each wrapped in - * `async.reflect` - * @example - * - * let tasks = [ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * // do some more stuff but error ... - * callback(new Error('bad stuff happened')); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = Error('bad stuff happened') - * // results[2].value = 'two' - * }); - * - * // an example using an object instead of an array - * let tasks = { - * one: function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * two: function(callback) { - * callback('two'); - * }, - * three: function(callback) { - * setTimeout(function() { - * callback(null, 'three'); - * }, 100); - * } - * }; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results.one.value = 'one' - * // results.two.error = 'two' - * // results.three.value = 'three' - * }); - */ - function reflectAll(tasks) { - var results; - if (Array.isArray(tasks)) { - results = tasks.map(reflect); - } else { - results = {}; - Object.keys(tasks).forEach(key => { - results[key] = reflect.call(this, tasks[key]); - }); - } - return results; - } + var method = ae.getMethod(); - function reject$2(eachfn, arr, _iteratee, callback) { - const iteratee = wrapAsync(_iteratee); - return _filter(eachfn, arr, (value, cb) => { - iteratee(value, (err, v) => { - cb(err, !v); - }); - }, callback); - } + if (method === constants.METHOD_STORED) { + ae.setSize(source.length); + ae.setCompressedSize(source.length); + ae.setCrc(crc32.buf(source) >>> 0); + } - /** - * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. - * - * @name reject - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @returns {Promise} a promise, if no callback is passed - * @example - * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * - * const fileList = ['dir1/file1.txt','dir2/file3.txt','dir3/file6.txt']; - * - * // asynchronous function that checks if a file exists - * function fileExists(file, callback) { - * fs.access(file, fs.constants.F_OK, (err) => { - * callback(null, !err); - * }); - * } - * - * // Using callbacks - * async.reject(fileList, fileExists, function(err, results) { - * // [ 'dir3/file6.txt' ] - * // results now equals an array of the non-existing files - * }); - * - * // Using Promises - * async.reject(fileList, fileExists) - * .then( results => { - * console.log(results); - * // [ 'dir3/file6.txt' ] - * // results now equals an array of the non-existing files - * }).catch( err => { - * console.log(err); - * }); - * - * // Using async/await - * async () => { - * try { - * let results = await async.reject(fileList, fileExists); - * console.log(results); - * // [ 'dir3/file6.txt' ] - * // results now equals an array of the non-existing files - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function reject (coll, iteratee, callback) { - return reject$2(eachOf$1, coll, iteratee, callback) - } - var reject$1 = awaitify(reject, 3); + this._writeLocalFileHeader(ae); - /** - * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a - * time. - * - * @name rejectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @returns {Promise} a promise, if no callback is passed - */ - function rejectLimit (coll, limit, iteratee, callback) { - return reject$2(eachOfLimit$2(limit), coll, iteratee, callback) - } - var rejectLimit$1 = awaitify(rejectLimit, 4); + if (method === constants.METHOD_STORED) { + this.write(source); + this._afterAppend(ae); + callback(null, ae); + return; + } else if (method === constants.METHOD_DEFLATED) { + this._smartStream(ae, callback).end(source); + return; + } else { + callback(new Error('compression method ' + method + ' not implemented')); + return; + } +}; - /** - * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. - * - * @name rejectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @returns {Promise} a promise, if no callback is passed - */ - function rejectSeries (coll, iteratee, callback) { - return reject$2(eachOfSeries$1, coll, iteratee, callback) - } - var rejectSeries$1 = awaitify(rejectSeries, 3); +ZipArchiveOutputStream.prototype._appendStream = function(ae, source, callback) { + ae.getGeneralPurposeBit().useDataDescriptor(true); + ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR); - function constant(value) { - return function () { - return value; - } - } + this._writeLocalFileHeader(ae); - /** - * Attempts to get a successful response from `task` no more than `times` times - * before returning an error. If the task is successful, the `callback` will be - * passed the result of the successful task. If all attempts fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name retry - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @see [async.retryable]{@link module:ControlFlow.retryable} - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an - * object with `times` and `interval` or a number. - * * `times` - The number of attempts to make before giving up. The default - * is `5`. - * * `interval` - The time to wait between retries, in milliseconds. The - * default is `0`. The interval may also be specified as a function of the - * retry count (see example). - * * `errorFilter` - An optional synchronous function that is invoked on - * erroneous result. If it returns `true` the retry attempts will continue; - * if the function returns `false` the retry flow is aborted with the current - * attempt's error and result being returned to the final callback. - * Invoked with (err). - * * If `opts` is a number, the number specifies the number of times to retry, - * with the default interval of `0`. - * @param {AsyncFunction} task - An async function to retry. - * Invoked with (callback). - * @param {Function} [callback] - An optional callback which is called when the - * task has succeeded, or after the final failed attempt. It receives the `err` - * and `result` arguments of the last attempt at completing the `task`. Invoked - * with (err, results). - * @returns {Promise} a promise if no callback provided - * - * @example - * - * // The `retry` function can be used as a stand-alone control flow by passing - * // a callback, as shown below: - * - * // try calling apiMethod 3 times - * async.retry(3, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 3 times, waiting 200 ms between each retry - * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 10 times with exponential backoff - * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) - * async.retry({ - * times: 10, - * interval: function(retryCount) { - * return 50 * Math.pow(2, retryCount); - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod the default 5 times no delay between each retry - * async.retry(apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod only when error condition satisfies, all other - * // errors will abort the retry control flow and return to final callback - * async.retry({ - * errorFilter: function(err) { - * return err.message === 'Temporary error'; // only retry on a specific error - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // to retry individual methods that are not as reliable within other - * // control flow functions, use the `retryable` wrapper: - * async.auto({ - * users: api.getUsers.bind(api), - * payments: async.retryable(3, api.getPayments.bind(api)) - * }, function(err, results) { - * // do something with the results - * }); - * - */ - const DEFAULT_TIMES = 5; - const DEFAULT_INTERVAL = 0; + var smart = this._smartStream(ae, callback); + source.once('error', function(err) { + smart.emit('error', err); + smart.end(); + }) + source.pipe(smart); +}; - function retry(opts, task, callback) { - var options = { - times: DEFAULT_TIMES, - intervalFunc: constant(DEFAULT_INTERVAL) - }; +ZipArchiveOutputStream.prototype._defaults = function(o) { + if (typeof o !== 'object') { + o = {}; + } - if (arguments.length < 3 && typeof opts === 'function') { - callback = task || promiseCallback(); - task = opts; - } else { - parseTimes(options, opts); - callback = callback || promiseCallback(); - } + if (typeof o.zlib !== 'object') { + o.zlib = {}; + } - if (typeof task !== 'function') { - throw new Error("Invalid arguments for async.retry"); - } + if (typeof o.zlib.level !== 'number') { + o.zlib.level = constants.ZLIB_BEST_SPEED; + } - var _task = wrapAsync(task); + o.forceZip64 = !!o.forceZip64; + o.forceLocalTime = !!o.forceLocalTime; - var attempt = 1; - function retryAttempt() { - _task((err, ...args) => { - if (err === false) return - if (err && attempt++ < options.times && - (typeof options.errorFilter != 'function' || - options.errorFilter(err))) { - setTimeout(retryAttempt, options.intervalFunc(attempt - 1)); - } else { - callback(err, ...args); - } - }); - } + return o; +}; - retryAttempt(); - return callback[PROMISE_SYMBOL] - } +ZipArchiveOutputStream.prototype._finish = function() { + this._archive.centralOffset = this.offset; - function parseTimes(acc, t) { - if (typeof t === 'object') { - acc.times = +t.times || DEFAULT_TIMES; + this._entries.forEach(function(ae) { + this._writeCentralFileHeader(ae); + }.bind(this)); - acc.intervalFunc = typeof t.interval === 'function' ? - t.interval : - constant(+t.interval || DEFAULT_INTERVAL); + this._archive.centralLength = this.offset - this._archive.centralOffset; - acc.errorFilter = t.errorFilter; - } else if (typeof t === 'number' || typeof t === 'string') { - acc.times = +t || DEFAULT_TIMES; - } else { - throw new Error("Invalid arguments for async.retry"); - } - } + if (this.isZip64()) { + this._writeCentralDirectoryZip64(); + } - /** - * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method - * wraps a task and makes it retryable, rather than immediately calling it - * with retries. - * - * @name retryable - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.retry]{@link module:ControlFlow.retry} - * @category Control Flow - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional - * options, exactly the same as from `retry`, except for a `opts.arity` that - * is the arity of the `task` function, defaulting to `task.length` - * @param {AsyncFunction} task - the asynchronous function to wrap. - * This function will be passed any arguments passed to the returned wrapper. - * Invoked with (...args, callback). - * @returns {AsyncFunction} The wrapped function, which when invoked, will - * retry on an error, based on the parameters specified in `opts`. - * This function will accept the same parameters as `task`. - * @example - * - * async.auto({ - * dep1: async.retryable(3, getFromFlakyService), - * process: ["dep1", async.retryable(3, function (results, cb) { - * maybeProcessData(results.dep1, cb); - * })] - * }, callback); - */ - function retryable (opts, task) { - if (!task) { - task = opts; - opts = null; - } - let arity = (opts && opts.arity) || task.length; - if (isAsync(task)) { - arity += 1; - } - var _task = wrapAsync(task); - return initialParams((args, callback) => { - if (args.length < arity - 1 || callback == null) { - args.push(callback); - callback = promiseCallback(); - } - function taskFn(cb) { - _task(...args, cb); - } + this._writeCentralDirectoryEnd(); - if (opts) retry(opts, taskFn, callback); - else retry(taskFn, callback); + this._archive.processing = false; + this._archive.finish = true; + this._archive.finished = true; + this.end(); +}; - return callback[PROMISE_SYMBOL] - }); - } +ZipArchiveOutputStream.prototype._normalizeEntry = function(ae) { + if (ae.getMethod() === -1) { + ae.setMethod(constants.METHOD_DEFLATED); + } - /** - * Run the functions in the `tasks` collection in series, each one running once - * the previous function has completed. If any functions in the series pass an - * error to its callback, no more functions are run, and `callback` is - * immediately called with the value of the error. Otherwise, `callback` - * receives an array of results when `tasks` have completed. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function, and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.series}. - * - * **Note** that while many implementations preserve the order of object - * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) - * explicitly states that - * - * > The mechanics and order of enumerating the properties is not specified. - * - * So if you rely on the order in which your series of functions are executed, - * and want this to work on all platforms, consider using an array. - * - * @name series - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing - * [async functions]{@link AsyncFunction} to run in series. - * Each function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This function gets a results array (or object) - * containing all the result arguments passed to the `task` callbacks. Invoked - * with (err, result). - * @return {Promise} a promise, if no callback is passed - * @example - * - * //Using Callbacks - * async.series([ - * function(callback) { - * setTimeout(function() { - * // do some async task - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * // then do another async task - * callback(null, 'two'); - * }, 100); - * } - * ], function(err, results) { - * console.log(results); - * // results is equal to ['one','two'] - * }); - * - * // an example using objects instead of arrays - * async.series({ - * one: function(callback) { - * setTimeout(function() { - * // do some async task - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * // then do another async task - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * console.log(results); - * // results is equal to: { one: 1, two: 2 } - * }); - * - * //Using Promises - * async.series([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]).then(results => { - * console.log(results); - * // results is equal to ['one','two'] - * }).catch(err => { - * console.log(err); - * }); - * - * // an example using an object instead of an array - * async.series({ - * one: function(callback) { - * setTimeout(function() { - * // do some async task - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * // then do another async task - * callback(null, 2); - * }, 100); - * } - * }).then(results => { - * console.log(results); - * // results is equal to: { one: 1, two: 2 } - * }).catch(err => { - * console.log(err); - * }); - * - * //Using async/await - * async () => { - * try { - * let results = await async.series([ - * function(callback) { - * setTimeout(function() { - * // do some async task - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * // then do another async task - * callback(null, 'two'); - * }, 100); - * } - * ]); - * console.log(results); - * // results is equal to ['one','two'] - * } - * catch (err) { - * console.log(err); - * } - * } - * - * // an example using an object instead of an array - * async () => { - * try { - * let results = await async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * // do some async task - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * // then do another async task - * callback(null, 2); - * }, 100); - * } - * }); - * console.log(results); - * // results is equal to: { one: 1, two: 2 } - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function series(tasks, callback) { - return _parallel(eachOfSeries$1, tasks, callback); - } + if (ae.getMethod() === constants.METHOD_DEFLATED) { + ae.getGeneralPurposeBit().useDataDescriptor(true); + ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR); + } - /** - * Returns `true` if at least one element in the `coll` satisfies an async test. - * If any iteratee call returns `true`, the main `callback` is immediately - * called. - * - * @name some - * @static - * @memberOf module:Collections - * @method - * @alias any - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @returns {Promise} a promise, if no callback provided - * @example - * - * // dir1 is a directory that contains file1.txt, file2.txt - * // dir2 is a directory that contains file3.txt, file4.txt - * // dir3 is a directory that contains file5.txt - * // dir4 does not exist - * - * // asynchronous function that checks if a file exists - * function fileExists(file, callback) { - * fs.access(file, fs.constants.F_OK, (err) => { - * callback(null, !err); - * }); - * } - * - * // Using callbacks - * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists, - * function(err, result) { - * console.log(result); - * // true - * // result is true since some file in the list exists - * } - *); - * - * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists, - * function(err, result) { - * console.log(result); - * // false - * // result is false since none of the files exists - * } - *); - * - * // Using Promises - * async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists) - * .then( result => { - * console.log(result); - * // true - * // result is true since some file in the list exists - * }).catch( err => { - * console.log(err); - * }); - * - * async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists) - * .then( result => { - * console.log(result); - * // false - * // result is false since none of the files exists - * }).catch( err => { - * console.log(err); - * }); - * - * // Using async/await - * async () => { - * try { - * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir3/file5.txt'], fileExists); - * console.log(result); - * // true - * // result is true since some file in the list exists - * } - * catch (err) { - * console.log(err); - * } - * } - * - * async () => { - * try { - * let result = await async.some(['dir1/missing.txt','dir2/missing.txt','dir4/missing.txt'], fileExists); - * console.log(result); - * // false - * // result is false since none of the files exists - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function some(coll, iteratee, callback) { - return _createTester(Boolean, res => res)(eachOf$1, coll, iteratee, callback) - } - var some$1 = awaitify(some, 3); + if (ae.getTime() === -1) { + ae.setTime(new Date(), this._archive.forceLocalTime); + } - /** - * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. - * - * @name someLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anyLimit - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @returns {Promise} a promise, if no callback provided - */ - function someLimit(coll, limit, iteratee, callback) { - return _createTester(Boolean, res => res)(eachOfLimit$2(limit), coll, iteratee, callback) - } - var someLimit$1 = awaitify(someLimit, 4); + ae._offsets = { + file: 0, + data: 0, + contents: 0, + }; +}; - /** - * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. - * - * @name someSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anySeries - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in series. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @returns {Promise} a promise, if no callback provided - */ - function someSeries(coll, iteratee, callback) { - return _createTester(Boolean, res => res)(eachOfSeries$1, coll, iteratee, callback) - } - var someSeries$1 = awaitify(someSeries, 3); +ZipArchiveOutputStream.prototype._smartStream = function(ae, callback) { + var deflate = ae.getMethod() === constants.METHOD_DEFLATED; + var process = deflate ? new DeflateCRC32Stream(this.options.zlib) : new CRC32Stream(); + var error = null; - /** - * Sorts a list by the results of running each `coll` value through an async - * `iteratee`. - * - * @name sortBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a value to use as the sort criteria as - * its `result`. - * Invoked with (item, callback). - * @param {Function} callback - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is the items - * from the original `coll` sorted by the values returned by the `iteratee` - * calls. Invoked with (err, results). - * @returns {Promise} a promise, if no callback passed - * @example - * - * // bigfile.txt is a file that is 251100 bytes in size - * // mediumfile.txt is a file that is 11000 bytes in size - * // smallfile.txt is a file that is 121 bytes in size - * - * // asynchronous function that returns the file size in bytes - * function getFileSizeInBytes(file, callback) { - * fs.stat(file, function(err, stat) { - * if (err) { - * return callback(err); - * } - * callback(null, stat.size); - * }); - * } - * - * // Using callbacks - * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes, - * function(err, results) { - * if (err) { - * console.log(err); - * } else { - * console.log(results); - * // results is now the original array of files sorted by - * // file size (ascending by default), e.g. - * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] - * } - * } - * ); - * - * // By modifying the callback parameter the - * // sorting order can be influenced: - * - * // ascending order - * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], function(file, callback) { - * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { - * if (getFileSizeErr) return callback(getFileSizeErr); - * callback(null, fileSize); - * }); - * }, function(err, results) { - * if (err) { - * console.log(err); - * } else { - * console.log(results); - * // results is now the original array of files sorted by - * // file size (ascending by default), e.g. - * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] - * } - * } - * ); - * - * // descending order - * async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], function(file, callback) { - * getFileSizeInBytes(file, function(getFileSizeErr, fileSize) { - * if (getFileSizeErr) { - * return callback(getFileSizeErr); - * } - * callback(null, fileSize * -1); - * }); - * }, function(err, results) { - * if (err) { - * console.log(err); - * } else { - * console.log(results); - * // results is now the original array of files sorted by - * // file size (ascending by default), e.g. - * // [ 'bigfile.txt', 'mediumfile.txt', 'smallfile.txt'] - * } - * } - * ); - * - * // Error handling - * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes, - * function(err, results) { - * if (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * } else { - * console.log(results); - * } - * } - * ); - * - * // Using Promises - * async.sortBy(['mediumfile.txt','smallfile.txt','bigfile.txt'], getFileSizeInBytes) - * .then( results => { - * console.log(results); - * // results is now the original array of files sorted by - * // file size (ascending by default), e.g. - * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] - * }).catch( err => { - * console.log(err); - * }); - * - * // Error handling - * async.sortBy(['mediumfile.txt','smallfile.txt','missingfile.txt'], getFileSizeInBytes) - * .then( results => { - * console.log(results); - * }).catch( err => { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * }); - * - * // Using async/await - * (async () => { - * try { - * let results = await async.sortBy(['bigfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); - * console.log(results); - * // results is now the original array of files sorted by - * // file size (ascending by default), e.g. - * // [ 'smallfile.txt', 'mediumfile.txt', 'bigfile.txt'] - * } - * catch (err) { - * console.log(err); - * } - * })(); - * - * // Error handling - * async () => { - * try { - * let results = await async.sortBy(['missingfile.txt','mediumfile.txt','smallfile.txt'], getFileSizeInBytes); - * console.log(results); - * } - * catch (err) { - * console.log(err); - * // [ Error: ENOENT: no such file or directory ] - * } - * } - * - */ - function sortBy (coll, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - return map$1(coll, (x, iterCb) => { - _iteratee(x, (err, criteria) => { - if (err) return iterCb(err); - iterCb(err, {value: x, criteria}); - }); - }, (err, results) => { - if (err) return callback(err); - callback(null, results.sort(comparator).map(v => v.value)); - }); + function handleStuff() { + var digest = process.digest().readUInt32BE(0); + ae.setCrc(digest); + ae.setSize(process.size()); + ae.setCompressedSize(process.size(true)); + this._afterAppend(ae); + callback(error, ae); + } - function comparator(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - } - } - var sortBy$1 = awaitify(sortBy, 3); + process.once('end', handleStuff.bind(this)); + process.once('error', function(err) { + error = err; + }); - /** - * Sets a time limit on an asynchronous function. If the function does not call - * its callback within the specified milliseconds, it will be called with a - * timeout error. The code property for the error object will be `'ETIMEDOUT'`. - * - * @name timeout - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} asyncFn - The async function to limit in time. - * @param {number} milliseconds - The specified time limit. - * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) - * to timeout Error for more information.. - * @returns {AsyncFunction} Returns a wrapped function that can be used with any - * of the control flow functions. - * Invoke this function with the same parameters as you would `asyncFunc`. - * @example - * - * function myFunction(foo, callback) { - * doAsyncTask(foo, function(err, data) { - * // handle errors - * if (err) return callback(err); - * - * // do some stuff ... - * - * // return processed data - * return callback(null, data); - * }); - * } - * - * var wrapped = async.timeout(myFunction, 1000); - * - * // call `wrapped` as you would `myFunction` - * wrapped({ bar: 'bar' }, function(err, data) { - * // if `myFunction` takes < 1000 ms to execute, `err` - * // and `data` will have their expected values - * - * // else `err` will be an Error with the code 'ETIMEDOUT' - * }); - */ - function timeout(asyncFn, milliseconds, info) { - var fn = wrapAsync(asyncFn); + process.pipe(this, { end: false }); - return initialParams((args, callback) => { - var timedOut = false; - var timer; + return process; +}; - function timeoutCallback() { - var name = asyncFn.name || 'anonymous'; - var error = new Error('Callback function "' + name + '" timed out.'); - error.code = 'ETIMEDOUT'; - if (info) { - error.info = info; - } - timedOut = true; - callback(error); - } +ZipArchiveOutputStream.prototype._writeCentralDirectoryEnd = function() { + var records = this._entries.length; + var size = this._archive.centralLength; + var offset = this._archive.centralOffset; - args.push((...cbArgs) => { - if (!timedOut) { - callback(...cbArgs); - clearTimeout(timer); - } - }); + if (this.isZip64()) { + records = constants.ZIP64_MAGIC_SHORT; + size = constants.ZIP64_MAGIC; + offset = constants.ZIP64_MAGIC; + } - // setup timer and call original function - timer = setTimeout(timeoutCallback, milliseconds); - fn(...args); - }); - } + // signature + this.write(zipUtil.getLongBytes(constants.SIG_EOCD)); - function range(size) { - var result = Array(size); - while (size--) { - result[size] = size; - } - return result; - } + // disk numbers + this.write(constants.SHORT_ZERO); + this.write(constants.SHORT_ZERO); - /** - * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a - * time. - * - * @name timesLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} count - The number of times to run the function. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see [async.map]{@link module:Collections.map}. - * @returns {Promise} a promise, if no callback is provided - */ - function timesLimit(count, limit, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - return mapLimit$1(range(count), limit, _iteratee, callback); - } + // number of entries + this.write(zipUtil.getShortBytes(records)); + this.write(zipUtil.getShortBytes(records)); - /** - * Calls the `iteratee` function `n` times, and accumulates results in the same - * manner you would use with [map]{@link module:Collections.map}. - * - * @name times - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.map]{@link module:Collections.map} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - * @returns {Promise} a promise, if no callback is provided - * @example - * - * // Pretend this is some complicated async factory - * var createUser = function(id, callback) { - * callback(null, { - * id: 'user' + id - * }); - * }; - * - * // generate 5 users - * async.times(5, function(n, next) { - * createUser(n, function(err, user) { - * next(err, user); - * }); - * }, function(err, users) { - * // we should now have 5 users - * }); - */ - function times (n, iteratee, callback) { - return timesLimit(n, Infinity, iteratee, callback) - } + // length and location of CD + this.write(zipUtil.getLongBytes(size)); + this.write(zipUtil.getLongBytes(offset)); - /** - * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. - * - * @name timesSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - * @returns {Promise} a promise, if no callback is provided - */ - function timesSeries (n, iteratee, callback) { - return timesLimit(n, 1, iteratee, callback) - } + // archive comment + var comment = this.getComment(); + var commentLength = Buffer.byteLength(comment); + this.write(zipUtil.getShortBytes(commentLength)); + this.write(comment); +}; - /** - * A relative of `reduce`. Takes an Object or Array, and iterates over each - * element in parallel, each step potentially mutating an `accumulator` value. - * The type of the accumulator defaults to the type of collection passed in. - * - * @name transform - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|AsyncIterable|Object} coll - A collection to iterate over. - * @param {*} [accumulator] - The initial state of the transform. If omitted, - * it will default to an empty Object or Array, depending on the type of `coll` - * @param {AsyncFunction} iteratee - A function applied to each item in the - * collection that potentially modifies the accumulator. - * Invoked with (accumulator, item, key, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the transformed accumulator. - * Invoked with (err, result). - * @returns {Promise} a promise, if no callback provided - * @example - * - * // file1.txt is a file that is 1000 bytes in size - * // file2.txt is a file that is 2000 bytes in size - * // file3.txt is a file that is 3000 bytes in size - * - * // helper function that returns human-readable size format from bytes - * function formatBytes(bytes, decimals = 2) { - * // implementation not included for brevity - * return humanReadbleFilesize; - * } - * - * const fileList = ['file1.txt','file2.txt','file3.txt']; - * - * // asynchronous function that returns the file size, transformed to human-readable format - * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. - * function transformFileSize(acc, value, key, callback) { - * fs.stat(value, function(err, stat) { - * if (err) { - * return callback(err); - * } - * acc[key] = formatBytes(stat.size); - * callback(null); - * }); - * } - * - * // Using callbacks - * async.transform(fileList, transformFileSize, function(err, result) { - * if(err) { - * console.log(err); - * } else { - * console.log(result); - * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] - * } - * }); - * - * // Using Promises - * async.transform(fileList, transformFileSize) - * .then(result => { - * console.log(result); - * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] - * }).catch(err => { - * console.log(err); - * }); - * - * // Using async/await - * (async () => { - * try { - * let result = await async.transform(fileList, transformFileSize); - * console.log(result); - * // [ '1000 Bytes', '1.95 KB', '2.93 KB' ] - * } - * catch (err) { - * console.log(err); - * } - * })(); - * - * @example - * - * // file1.txt is a file that is 1000 bytes in size - * // file2.txt is a file that is 2000 bytes in size - * // file3.txt is a file that is 3000 bytes in size - * - * // helper function that returns human-readable size format from bytes - * function formatBytes(bytes, decimals = 2) { - * // implementation not included for brevity - * return humanReadbleFilesize; - * } - * - * const fileMap = { f1: 'file1.txt', f2: 'file2.txt', f3: 'file3.txt' }; - * - * // asynchronous function that returns the file size, transformed to human-readable format - * // e.g. 1024 bytes = 1KB, 1234 bytes = 1.21 KB, 1048576 bytes = 1MB, etc. - * function transformFileSize(acc, value, key, callback) { - * fs.stat(value, function(err, stat) { - * if (err) { - * return callback(err); - * } - * acc[key] = formatBytes(stat.size); - * callback(null); - * }); - * } - * - * // Using callbacks - * async.transform(fileMap, transformFileSize, function(err, result) { - * if(err) { - * console.log(err); - * } else { - * console.log(result); - * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } - * } - * }); - * - * // Using Promises - * async.transform(fileMap, transformFileSize) - * .then(result => { - * console.log(result); - * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } - * }).catch(err => { - * console.log(err); - * }); - * - * // Using async/await - * async () => { - * try { - * let result = await async.transform(fileMap, transformFileSize); - * console.log(result); - * // { f1: '1000 Bytes', f2: '1.95 KB', f3: '2.93 KB' } - * } - * catch (err) { - * console.log(err); - * } - * } - * - */ - function transform (coll, accumulator, iteratee, callback) { - if (arguments.length <= 3 && typeof accumulator === 'function') { - callback = iteratee; - iteratee = accumulator; - accumulator = Array.isArray(coll) ? [] : {}; - } - callback = once(callback || promiseCallback()); - var _iteratee = wrapAsync(iteratee); +ZipArchiveOutputStream.prototype._writeCentralDirectoryZip64 = function() { + // signature + this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD)); - eachOf$1(coll, (v, k, cb) => { - _iteratee(accumulator, v, k, cb); - }, err => callback(err, accumulator)); - return callback[PROMISE_SYMBOL] - } + // size of the ZIP64 EOCD record + this.write(zipUtil.getEightBytes(44)); - /** - * It runs each task in series but stops whenever any of the functions were - * successful. If one of the tasks were successful, the `callback` will be - * passed the result of the successful task. If all tasks fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name tryEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|AsyncIterable|Object} tasks - A collection containing functions to - * run, each function is passed a `callback(err, result)` it must call on - * completion with an error `err` (which can be `null`) and an optional `result` - * value. - * @param {Function} [callback] - An optional callback which is called when one - * of the tasks has succeeded, or all have failed. It receives the `err` and - * `result` arguments of the last attempt at completing the `task`. Invoked with - * (err, results). - * @returns {Promise} a promise, if no callback is passed - * @example - * async.tryEach([ - * function getDataFromFirstWebsite(callback) { - * // Try getting the data from the first website - * callback(err, data); - * }, - * function getDataFromSecondWebsite(callback) { - * // First website failed, - * // Try getting the data from the backup website - * callback(err, data); - * } - * ], - * // optional callback - * function(err, results) { - * Now do something with the data. - * }); - * - */ - function tryEach(tasks, callback) { - var error = null; - var result; - return eachSeries$1(tasks, (task, taskCb) => { - wrapAsync(task)((err, ...args) => { - if (err === false) return taskCb(err); + // version made by + this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64)); - if (args.length < 2) { - [result] = args; - } else { - result = args; - } - error = err; - taskCb(err ? null : {}); - }); - }, () => callback(error, result)); - } + // version to extract + this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64)); - var tryEach$1 = awaitify(tryEach); + // disk numbers + this.write(constants.LONG_ZERO); + this.write(constants.LONG_ZERO); - /** - * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, - * unmemoized form. Handy for testing. - * - * @name unmemoize - * @static - * @memberOf module:Utils - * @method - * @see [async.memoize]{@link module:Utils.memoize} - * @category Util - * @param {AsyncFunction} fn - the memoized function - * @returns {AsyncFunction} a function that calls the original unmemoized function - */ - function unmemoize(fn) { - return (...args) => { - return (fn.unmemoized || fn)(...args); - }; - } + // number of entries + this.write(zipUtil.getEightBytes(this._entries.length)); + this.write(zipUtil.getEightBytes(this._entries.length)); - /** - * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. - * - * @name whilst - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `iteratee`. Invoked with (callback). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns {Promise} a promise, if no callback is passed - * @example - * - * var count = 0; - * async.whilst( - * function test(cb) { cb(null, count < 5); }, - * function iter(callback) { - * count++; - * setTimeout(function() { - * callback(null, count); - * }, 1000); - * }, - * function (err, n) { - * // 5 seconds have passed, n = 5 - * } - * ); - */ - function whilst(test, iteratee, callback) { - callback = onlyOnce(callback); - var _fn = wrapAsync(iteratee); - var _test = wrapAsync(test); - var results = []; + // length and location of CD + this.write(zipUtil.getEightBytes(this._archive.centralLength)); + this.write(zipUtil.getEightBytes(this._archive.centralOffset)); - function next(err, ...rest) { - if (err) return callback(err); - results = rest; - if (err === false) return; - _test(check); - } + // extensible data sector + // not implemented at this time - function check(err, truth) { - if (err) return callback(err); - if (err === false) return; - if (!truth) return callback(null, ...results); - _fn(next); - } + // end of central directory locator + this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD_LOC)); - return _test(check); - } - var whilst$1 = awaitify(whilst, 3); + // disk number holding the ZIP64 EOCD record + this.write(constants.LONG_ZERO); - /** - * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. `callback` will be passed an error and any - * arguments passed to the final `iteratee`'s callback. - * - * The inverse of [whilst]{@link module:ControlFlow.whilst}. - * - * @name until - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `iteratee`. Invoked with (callback). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns {Promise} a promise, if a callback is not passed - * - * @example - * const results = [] - * let finished = false - * async.until(function test(cb) { - * cb(null, finished) - * }, function iter(next) { - * fetchPage(url, (err, body) => { - * if (err) return next(err) - * results = results.concat(body.objects) - * finished = !!body.next - * next(err) - * }) - * }, function done (err) { - * // all pages have been fetched - * }) - */ - function until(test, iteratee, callback) { - const _test = wrapAsync(test); - return whilst$1((cb) => _test((err, truth) => cb (err, !truth)), iteratee, callback); - } + // relative offset of the ZIP64 EOCD record + this.write(zipUtil.getEightBytes(this._archive.centralOffset + this._archive.centralLength)); - /** - * Runs the `tasks` array of functions in series, each passing their results to - * the next in the array. However, if any of the `tasks` pass an error to their - * own callback, the next function is not executed, and the main `callback` is - * immediately called with the error. - * - * @name waterfall - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} - * to run. - * Each function should complete with any number of `result` values. - * The `result` values will be passed as arguments, in order, to the next task. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This will be passed the results of the last task's - * callback. Invoked with (err, [results]). - * @returns {Promise} a promise, if a callback is omitted - * @example - * - * async.waterfall([ - * function(callback) { - * callback(null, 'one', 'two'); - * }, - * function(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * }, - * function(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - * ], function (err, result) { - * // result now equals 'done' - * }); - * - * // Or, with named functions: - * async.waterfall([ - * myFirstFunction, - * mySecondFunction, - * myLastFunction, - * ], function (err, result) { - * // result now equals 'done' - * }); - * function myFirstFunction(callback) { - * callback(null, 'one', 'two'); - * } - * function mySecondFunction(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * } - * function myLastFunction(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - */ - function waterfall (tasks, callback) { - callback = once(callback); - if (!Array.isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); - if (!tasks.length) return callback(); - var taskIndex = 0; + // total number of disks + this.write(zipUtil.getLongBytes(1)); +}; - function nextTask(args) { - var task = wrapAsync(tasks[taskIndex++]); - task(...args, onlyOnce(next)); - } +ZipArchiveOutputStream.prototype._writeCentralFileHeader = function(ae) { + var gpb = ae.getGeneralPurposeBit(); + var method = ae.getMethod(); + var fileOffset = ae._offsets.file; - function next(err, ...args) { - if (err === false) return - if (err || taskIndex === tasks.length) { - return callback(err, ...args); - } - nextTask(args); - } + var size = ae.getSize(); + var compressedSize = ae.getCompressedSize(); - nextTask([]); - } + if (ae.isZip64() || fileOffset > constants.ZIP64_MAGIC) { + size = constants.ZIP64_MAGIC; + compressedSize = constants.ZIP64_MAGIC; + fileOffset = constants.ZIP64_MAGIC; - var waterfall$1 = awaitify(waterfall); + ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64); - /** - * An "async function" in the context of Async is an asynchronous function with - * a variable number of parameters, with the final parameter being a callback. - * (`function (arg1, arg2, ..., callback) {}`) - * The final callback is of the form `callback(err, results...)`, which must be - * called once the function is completed. The callback should be called with a - * Error as its first argument to signal that an error occurred. - * Otherwise, if no error occurred, it should be called with `null` as the first - * argument, and any additional `result` arguments that may apply, to signal - * successful completion. - * The callback must be called exactly once, ideally on a later tick of the - * JavaScript event loop. - * - * This type of function is also referred to as a "Node-style async function", - * or a "continuation passing-style function" (CPS). Most of the methods of this - * library are themselves CPS/Node-style async functions, or functions that - * return CPS/Node-style async functions. - * - * Wherever we accept a Node-style async function, we also directly accept an - * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. - * In this case, the `async` function will not be passed a final callback - * argument, and any thrown error will be used as the `err` argument of the - * implicit callback, and the return value will be used as the `result` value. - * (i.e. a `rejected` of the returned Promise becomes the `err` callback - * argument, and a `resolved` value becomes the `result`.) - * - * Note, due to JavaScript limitations, we can only detect native `async` - * functions and not transpilied implementations. - * Your environment must have `async`/`await` support for this to work. - * (e.g. Node > v7.6, or a recent version of a modern browser). - * If you are using `async` functions through a transpiler (e.g. Babel), you - * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, - * because the `async function` will be compiled to an ordinary function that - * returns a promise. - * - * @typedef {Function} AsyncFunction - * @static - */ + var extraBuf = Buffer.concat([ + zipUtil.getShortBytes(constants.ZIP64_EXTRA_ID), + zipUtil.getShortBytes(24), + zipUtil.getEightBytes(ae.getSize()), + zipUtil.getEightBytes(ae.getCompressedSize()), + zipUtil.getEightBytes(ae._offsets.file) + ], 28); + ae.setExtra(extraBuf); + } - var index = { - apply, - applyEach, - applyEachSeries, - asyncify, - auto, - autoInject, - cargo: cargo$1, - cargoQueue: cargo, - compose, - concat: concat$1, - concatLimit: concatLimit$1, - concatSeries: concatSeries$1, - constant: constant$1, - detect: detect$1, - detectLimit: detectLimit$1, - detectSeries: detectSeries$1, - dir, - doUntil, - doWhilst: doWhilst$1, - each, - eachLimit: eachLimit$1, - eachOf: eachOf$1, - eachOfLimit: eachOfLimit$1, - eachOfSeries: eachOfSeries$1, - eachSeries: eachSeries$1, - ensureAsync, - every: every$1, - everyLimit: everyLimit$1, - everySeries: everySeries$1, - filter: filter$1, - filterLimit: filterLimit$1, - filterSeries: filterSeries$1, - forever: forever$1, - groupBy, - groupByLimit: groupByLimit$1, - groupBySeries, - log, - map: map$1, - mapLimit: mapLimit$1, - mapSeries: mapSeries$1, - mapValues, - mapValuesLimit: mapValuesLimit$1, - mapValuesSeries, - memoize, - nextTick, - parallel, - parallelLimit, - priorityQueue, - queue, - race: race$1, - reduce: reduce$1, - reduceRight, - reflect, - reflectAll, - reject: reject$1, - rejectLimit: rejectLimit$1, - rejectSeries: rejectSeries$1, - retry, - retryable, - seq, - series, - setImmediate: setImmediate$1, - some: some$1, - someLimit: someLimit$1, - someSeries: someSeries$1, - sortBy: sortBy$1, - timeout, - times, - timesLimit, - timesSeries, - transform, - tryEach: tryEach$1, - unmemoize, - until, - waterfall: waterfall$1, - whilst: whilst$1, + // signature + this.write(zipUtil.getLongBytes(constants.SIG_CFH)); - // aliases - all: every$1, - allLimit: everyLimit$1, - allSeries: everySeries$1, - any: some$1, - anyLimit: someLimit$1, - anySeries: someSeries$1, - find: detect$1, - findLimit: detectLimit$1, - findSeries: detectSeries$1, - flatMap: concat$1, - flatMapLimit: concatLimit$1, - flatMapSeries: concatSeries$1, - forEach: each, - forEachSeries: eachSeries$1, - forEachLimit: eachLimit$1, - forEachOf: eachOf$1, - forEachOfSeries: eachOfSeries$1, - forEachOfLimit: eachOfLimit$1, - inject: reduce$1, - foldl: reduce$1, - foldr: reduceRight, - select: filter$1, - selectLimit: filterLimit$1, - selectSeries: filterSeries$1, - wrapSync: asyncify, - during: whilst$1, - doDuring: doWhilst$1 - }; - - exports.all = every$1; - exports.allLimit = everyLimit$1; - exports.allSeries = everySeries$1; - exports.any = some$1; - exports.anyLimit = someLimit$1; - exports.anySeries = someSeries$1; - exports.apply = apply; - exports.applyEach = applyEach; - exports.applyEachSeries = applyEachSeries; - exports.asyncify = asyncify; - exports.auto = auto; - exports.autoInject = autoInject; - exports.cargo = cargo$1; - exports.cargoQueue = cargo; - exports.compose = compose; - exports.concat = concat$1; - exports.concatLimit = concatLimit$1; - exports.concatSeries = concatSeries$1; - exports.constant = constant$1; - exports.default = index; - exports.detect = detect$1; - exports.detectLimit = detectLimit$1; - exports.detectSeries = detectSeries$1; - exports.dir = dir; - exports.doDuring = doWhilst$1; - exports.doUntil = doUntil; - exports.doWhilst = doWhilst$1; - exports.during = whilst$1; - exports.each = each; - exports.eachLimit = eachLimit$1; - exports.eachOf = eachOf$1; - exports.eachOfLimit = eachOfLimit$1; - exports.eachOfSeries = eachOfSeries$1; - exports.eachSeries = eachSeries$1; - exports.ensureAsync = ensureAsync; - exports.every = every$1; - exports.everyLimit = everyLimit$1; - exports.everySeries = everySeries$1; - exports.filter = filter$1; - exports.filterLimit = filterLimit$1; - exports.filterSeries = filterSeries$1; - exports.find = detect$1; - exports.findLimit = detectLimit$1; - exports.findSeries = detectSeries$1; - exports.flatMap = concat$1; - exports.flatMapLimit = concatLimit$1; - exports.flatMapSeries = concatSeries$1; - exports.foldl = reduce$1; - exports.foldr = reduceRight; - exports.forEach = each; - exports.forEachLimit = eachLimit$1; - exports.forEachOf = eachOf$1; - exports.forEachOfLimit = eachOfLimit$1; - exports.forEachOfSeries = eachOfSeries$1; - exports.forEachSeries = eachSeries$1; - exports.forever = forever$1; - exports.groupBy = groupBy; - exports.groupByLimit = groupByLimit$1; - exports.groupBySeries = groupBySeries; - exports.inject = reduce$1; - exports.log = log; - exports.map = map$1; - exports.mapLimit = mapLimit$1; - exports.mapSeries = mapSeries$1; - exports.mapValues = mapValues; - exports.mapValuesLimit = mapValuesLimit$1; - exports.mapValuesSeries = mapValuesSeries; - exports.memoize = memoize; - exports.nextTick = nextTick; - exports.parallel = parallel; - exports.parallelLimit = parallelLimit; - exports.priorityQueue = priorityQueue; - exports.queue = queue; - exports.race = race$1; - exports.reduce = reduce$1; - exports.reduceRight = reduceRight; - exports.reflect = reflect; - exports.reflectAll = reflectAll; - exports.reject = reject$1; - exports.rejectLimit = rejectLimit$1; - exports.rejectSeries = rejectSeries$1; - exports.retry = retry; - exports.retryable = retryable; - exports.select = filter$1; - exports.selectLimit = filterLimit$1; - exports.selectSeries = filterSeries$1; - exports.seq = seq; - exports.series = series; - exports.setImmediate = setImmediate$1; - exports.some = some$1; - exports.someLimit = someLimit$1; - exports.someSeries = someSeries$1; - exports.sortBy = sortBy$1; - exports.timeout = timeout; - exports.times = times; - exports.timesLimit = timesLimit; - exports.timesSeries = timesSeries; - exports.transform = transform; - exports.tryEach = tryEach$1; - exports.unmemoize = unmemoize; - exports.until = until; - exports.waterfall = waterfall$1; - exports.whilst = whilst$1; - exports.wrapSync = asyncify; - - Object.defineProperty(exports, '__esModule', { value: true }); - -})); + // version made by + this.write(zipUtil.getShortBytes((ae.getPlatform() << 8) | constants.VERSION_MADEBY)); + // version to extract and general bit flag + this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract())); + this.write(gpb.encode()); -/***/ }), + // compression method + this.write(zipUtil.getShortBytes(method)); -/***/ 14812: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // datetime + this.write(zipUtil.getLongBytes(ae.getTimeDos())); -module.exports = -{ - parallel : __nccwpck_require__(8210), - serial : __nccwpck_require__(50445), - serialOrdered : __nccwpck_require__(3578) -}; + // crc32 checksum + this.write(zipUtil.getLongBytes(ae.getCrc())); + // sizes + this.write(zipUtil.getLongBytes(compressedSize)); + this.write(zipUtil.getLongBytes(size)); -/***/ }), + var name = ae.getName(); + var comment = ae.getComment(); + var extra = ae.getCentralDirectoryExtra(); -/***/ 1700: -/***/ ((module) => { + if (gpb.usesUTF8ForNames()) { + name = Buffer.from(name); + comment = Buffer.from(comment); + } -// API -module.exports = abort; + // name length + this.write(zipUtil.getShortBytes(name.length)); -/** - * Aborts leftover active jobs - * - * @param {object} state - current state object - */ -function abort(state) -{ - Object.keys(state.jobs).forEach(clean.bind(state)); + // extra length + this.write(zipUtil.getShortBytes(extra.length)); - // reset leftover jobs - state.jobs = {}; -} + // comments length + this.write(zipUtil.getShortBytes(comment.length)); -/** - * Cleans up leftover job by invoking abort function for the provided job id - * - * @this state - * @param {string|number} key - job id to abort - */ -function clean(key) -{ - if (typeof this.jobs[key] == 'function') - { - this.jobs[key](); - } -} + // disk number start + this.write(constants.SHORT_ZERO); + // internal attributes + this.write(zipUtil.getShortBytes(ae.getInternalAttributes())); -/***/ }), + // external attributes + this.write(zipUtil.getLongBytes(ae.getExternalAttributes())); -/***/ 72794: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // relative offset of LFH + this.write(zipUtil.getLongBytes(fileOffset)); -var defer = __nccwpck_require__(15295); + // name + this.write(name); -// API -module.exports = async; + // extra + this.write(extra); -/** - * Runs provided callback asynchronously - * even if callback itself is not - * - * @param {function} callback - callback to invoke - * @returns {function} - augmented callback - */ -function async(callback) -{ - var isAsync = false; + // comment + this.write(comment); +}; - // check if async happened - defer(function() { isAsync = true; }); +ZipArchiveOutputStream.prototype._writeDataDescriptor = function(ae) { + // signature + this.write(zipUtil.getLongBytes(constants.SIG_DD)); - return function async_callback(err, result) - { - if (isAsync) - { - callback(err, result); - } - else - { - defer(function nextTick_callback() - { - callback(err, result); - }); - } - }; -} + // crc32 checksum + this.write(zipUtil.getLongBytes(ae.getCrc())); + // sizes + if (ae.isZip64()) { + this.write(zipUtil.getEightBytes(ae.getCompressedSize())); + this.write(zipUtil.getEightBytes(ae.getSize())); + } else { + this.write(zipUtil.getLongBytes(ae.getCompressedSize())); + this.write(zipUtil.getLongBytes(ae.getSize())); + } +}; -/***/ }), +ZipArchiveOutputStream.prototype._writeLocalFileHeader = function(ae) { + var gpb = ae.getGeneralPurposeBit(); + var method = ae.getMethod(); + var name = ae.getName(); + var extra = ae.getLocalFileDataExtra(); -/***/ 15295: -/***/ ((module) => { + if (ae.isZip64()) { + gpb.useDataDescriptor(true); + ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64); + } -module.exports = defer; + if (gpb.usesUTF8ForNames()) { + name = Buffer.from(name); + } -/** - * Runs provided function on next iteration of the event loop - * - * @param {function} fn - function to run - */ -function defer(fn) -{ - var nextTick = typeof setImmediate == 'function' - ? setImmediate - : ( - typeof process == 'object' && typeof process.nextTick == 'function' - ? process.nextTick - : null - ); + ae._offsets.file = this.offset; - if (nextTick) - { - nextTick(fn); - } - else - { - setTimeout(fn, 0); - } -} + // signature + this.write(zipUtil.getLongBytes(constants.SIG_LFH)); + // version to extract and general bit flag + this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract())); + this.write(gpb.encode()); -/***/ }), + // compression method + this.write(zipUtil.getShortBytes(method)); -/***/ 9023: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // datetime + this.write(zipUtil.getLongBytes(ae.getTimeDos())); -var async = __nccwpck_require__(72794) - , abort = __nccwpck_require__(1700) - ; + ae._offsets.data = this.offset; -// API -module.exports = iterate; + // crc32 checksum and sizes + if (gpb.usesDataDescriptor()) { + this.write(constants.LONG_ZERO); + this.write(constants.LONG_ZERO); + this.write(constants.LONG_ZERO); + } else { + this.write(zipUtil.getLongBytes(ae.getCrc())); + this.write(zipUtil.getLongBytes(ae.getCompressedSize())); + this.write(zipUtil.getLongBytes(ae.getSize())); + } -/** - * Iterates over each job object - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {object} state - current job status - * @param {function} callback - invoked when all elements processed - */ -function iterate(list, iterator, state, callback) -{ - // store current index - var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; + // name length + this.write(zipUtil.getShortBytes(name.length)); - state.jobs[key] = runJob(iterator, key, list[key], function(error, output) - { - // don't repeat yourself - // skip secondary callbacks - if (!(key in state.jobs)) - { - return; - } + // extra length + this.write(zipUtil.getShortBytes(extra.length)); - // clean up jobs - delete state.jobs[key]; + // name + this.write(name); - if (error) - { - // don't process rest of the results - // stop still active jobs - // and reset the list - abort(state); - } - else - { - state.results[key] = output; - } + // extra + this.write(extra); - // return salvaged results - callback(error, state.results); - }); -} + ae._offsets.contents = this.offset; +}; -/** - * Runs iterator over provided job element - * - * @param {function} iterator - iterator to invoke - * @param {string|number} key - key/index of the element in the list of jobs - * @param {mixed} item - job description - * @param {function} callback - invoked after iterator is done with the job - * @returns {function|mixed} - job abort function or something else - */ -function runJob(iterator, key, item, callback) -{ - var aborter; +ZipArchiveOutputStream.prototype.getComment = function(comment) { + return this._archive.comment !== null ? this._archive.comment : ''; +}; - // allow shortcut if iterator expects only two arguments - if (iterator.length == 2) - { - aborter = iterator(item, async(callback)); - } - // otherwise go with full three arguments - else - { - aborter = iterator(item, key, async(callback)); - } +ZipArchiveOutputStream.prototype.isZip64 = function() { + return this._archive.forceZip64 || this._entries.length > constants.ZIP64_MAGIC_SHORT || this._archive.centralLength > constants.ZIP64_MAGIC || this._archive.centralOffset > constants.ZIP64_MAGIC; +}; - return aborter; -} +ZipArchiveOutputStream.prototype.setComment = function(comment) { + this._archive.comment = comment; +}; /***/ }), -/***/ 42474: -/***/ ((module) => { - -// API -module.exports = state; +/***/ 25445: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { /** - * Creates initial state object - * for iteration over list + * node-compress-commons * - * @param {array|object} list - list to iterate over - * @param {function|null} sortMethod - function to use for keys sort, - * or `null` to keep them as is - * @returns {object} - initial state object + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT */ -function state(list, sortMethod) -{ - var isNamedList = !Array.isArray(list) - , initState = - { - index : 0, - keyedList: isNamedList || sortMethod ? Object.keys(list) : null, - jobs : {}, - results : isNamedList ? {} : [], - size : isNamedList ? Object.keys(list).length : list.length - } - ; - - if (sortMethod) - { - // sort array keys based on it's values - // sort object's keys just on own merit - initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) - { - return sortMethod(list[a], list[b]); - }); - } - - return initState; -} - +module.exports = { + ArchiveEntry: __nccwpck_require__(92240), + ZipArchiveEntry: __nccwpck_require__(3179), + ArchiveOutputStream: __nccwpck_require__(36728), + ZipArchiveOutputStream: __nccwpck_require__(44432) +}; /***/ }), -/***/ 37942: +/***/ 95208: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var abort = __nccwpck_require__(1700) - , async = __nccwpck_require__(72794) - ; - -// API -module.exports = terminator; - /** - * Terminates jobs in the attached state context + * node-compress-commons * - * @this AsyncKitState# - * @param {function} callback - final callback to invoke after termination + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT */ -function terminator(callback) -{ - if (!Object.keys(this.jobs).length) - { - return; - } +var Stream = (__nccwpck_require__(12781).Stream); +var PassThrough = (__nccwpck_require__(45193).PassThrough); +var isStream = __nccwpck_require__(41554); - // fast forward iteration index - this.index = this.size; +var util = module.exports = {}; - // abort jobs - abort(this); +util.normalizeInputSource = function(source) { + if (source === null) { + return Buffer.alloc(0); + } else if (typeof source === 'string') { + return Buffer.from(source); + } else if (isStream(source) && !source._readableState) { + var normalized = new PassThrough(); + source.pipe(normalized); - // send back results we have so far - async(callback)(null, this.results); -} + return normalized; + } + return source; +}; /***/ }), -/***/ 8210: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var iterate = __nccwpck_require__(9023) - , initState = __nccwpck_require__(42474) - , terminator = __nccwpck_require__(37942) - ; - -// Public API -module.exports = parallel; +/***/ 86891: +/***/ ((module) => { -/** - * Runs iterator over provided array elements in parallel - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function parallel(list, iterator, callback) -{ - var state = initState(list); +module.exports = function (xs, fn) { + var res = []; + for (var i = 0; i < xs.length; i++) { + var x = fn(xs[i], i); + if (isArray(x)) res.push.apply(res, x); + else res.push(x); + } + return res; +}; - while (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, function(error, result) - { - if (error) - { - callback(error, result); - return; - } +var isArray = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; +}; - // looks like it's the last one - if (Object.keys(state.jobs).length === 0) - { - callback(null, state.results); - return; - } - }); - state.index++; +/***/ }), + +/***/ 95898: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. + +// NOTE: These type checking functions intentionally don't use `instanceof` +// because it is fragile and can be easily faked with `Object.create()`. + +function isArray(arg) { + if (Array.isArray) { + return Array.isArray(arg); } + return objectToString(arg) === '[object Array]'; +} +exports.isArray = isArray; - return terminator.bind(state, callback); +function isBoolean(arg) { + return typeof arg === 'boolean'; } +exports.isBoolean = isBoolean; +function isNull(arg) { + return arg === null; +} +exports.isNull = isNull; -/***/ }), +function isNullOrUndefined(arg) { + return arg == null; +} +exports.isNullOrUndefined = isNullOrUndefined; -/***/ 50445: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function isNumber(arg) { + return typeof arg === 'number'; +} +exports.isNumber = isNumber; -var serialOrdered = __nccwpck_require__(3578); +function isString(arg) { + return typeof arg === 'string'; +} +exports.isString = isString; -// Public API -module.exports = serial; +function isSymbol(arg) { + return typeof arg === 'symbol'; +} +exports.isSymbol = isSymbol; -/** - * Runs iterator over provided array elements in series - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function serial(list, iterator, callback) -{ - return serialOrdered(list, iterator, null, callback); +function isUndefined(arg) { + return arg === void 0; } +exports.isUndefined = isUndefined; +function isRegExp(re) { + return objectToString(re) === '[object RegExp]'; +} +exports.isRegExp = isRegExp; -/***/ }), +function isObject(arg) { + return typeof arg === 'object' && arg !== null; +} +exports.isObject = isObject; -/***/ 3578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function isDate(d) { + return objectToString(d) === '[object Date]'; +} +exports.isDate = isDate; -var iterate = __nccwpck_require__(9023) - , initState = __nccwpck_require__(42474) - , terminator = __nccwpck_require__(37942) - ; +function isError(e) { + return (objectToString(e) === '[object Error]' || e instanceof Error); +} +exports.isError = isError; -// Public API -module.exports = serialOrdered; -// sorting helpers -module.exports.ascending = ascending; -module.exports.descending = descending; +function isFunction(arg) { + return typeof arg === 'function'; +} +exports.isFunction = isFunction; -/** - * Runs iterator over provided sorted array elements in series - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} sortMethod - custom sort function - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator - */ -function serialOrdered(list, iterator, sortMethod, callback) -{ - var state = initState(list, sortMethod); +function isPrimitive(arg) { + return arg === null || + typeof arg === 'boolean' || + typeof arg === 'number' || + typeof arg === 'string' || + typeof arg === 'symbol' || // ES6 symbol + typeof arg === 'undefined'; +} +exports.isPrimitive = isPrimitive; - iterate(list, iterator, state, function iteratorHandler(error, result) - { - if (error) - { - callback(error, result); - return; - } +exports.isBuffer = __nccwpck_require__(14300).Buffer.isBuffer; - state.index++; +function objectToString(o) { + return Object.prototype.toString.call(o); +} - // are we there yet? - if (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, iteratorHandler); - return; - } - // done here - callback(null, state.results); - }); +/***/ }), - return terminator.bind(state, callback); +/***/ 83201: +/***/ ((__unused_webpack_module, exports) => { + +/*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */ +/* vim: set ts=2: */ +/*exported CRC32 */ +var CRC32; +(function (factory) { + /*jshint ignore:start */ + /*eslint-disable */ + if(typeof DO_NOT_EXPORT_CRC === 'undefined') { + if(true) { + factory(exports); + } else {} + } else { + factory(CRC32 = {}); + } + /*eslint-enable */ + /*jshint ignore:end */ +}(function(CRC32) { +CRC32.version = '1.2.2'; +/*global Int32Array */ +function signed_crc_table() { + var c = 0, table = new Array(256); + + for(var n =0; n != 256; ++n){ + c = n; + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); + table[n] = c; + } + + return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table; } -/* - * -- Sort methods - */ +var T0 = signed_crc_table(); +function slice_by_16_tables(T) { + var c = 0, v = 0, n = 0, table = typeof Int32Array !== 'undefined' ? new Int32Array(4096) : new Array(4096) ; -/** - * sort helper to sort array elements in ascending order - * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result - */ -function ascending(a, b) -{ - return a < b ? -1 : a > b ? 1 : 0; + for(n = 0; n != 256; ++n) table[n] = T[n]; + for(n = 0; n != 256; ++n) { + v = T[n]; + for(c = 256 + n; c < 4096; c += 256) v = table[c] = (v >>> 8) ^ T[v & 0xFF]; + } + var out = []; + for(n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== 'undefined' ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256); + return out; +} +var TT = slice_by_16_tables(T0); +var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4]; +var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9]; +var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14]; +function crc32_bstr(bstr, seed) { + var C = seed ^ -1; + for(var i = 0, L = bstr.length; i < L;) C = (C>>>8) ^ T0[(C^bstr.charCodeAt(i++))&0xFF]; + return ~C; } -/** - * sort helper to sort array elements in descending order - * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result - */ -function descending(a, b) -{ - return -1 * ascending(a, b); +function crc32_buf(B, seed) { + var C = seed ^ -1, L = B.length - 15, i = 0; + for(; i < L;) C = + Tf[B[i++] ^ (C & 255)] ^ + Te[B[i++] ^ ((C >> 8) & 255)] ^ + Td[B[i++] ^ ((C >> 16) & 255)] ^ + Tc[B[i++] ^ (C >>> 24)] ^ + Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^ + T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^ + T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]]; + L += 15; + while(i < L) C = (C>>>8) ^ T0[(C^B[i++])&0xFF]; + return ~C; +} + +function crc32_str(str, seed) { + var C = seed ^ -1; + for(var i = 0, L = str.length, c = 0, d = 0; i < L;) { + c = str.charCodeAt(i++); + if(c < 0x80) { + C = (C>>>8) ^ T0[(C^c)&0xFF]; + } else if(c < 0x800) { + C = (C>>>8) ^ T0[(C ^ (192|((c>>6)&31)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; + } else if(c >= 0xD800 && c < 0xE000) { + c = (c&1023)+64; d = str.charCodeAt(i++)&1023; + C = (C>>>8) ^ T0[(C ^ (240|((c>>8)&7)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|((c>>2)&63)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|(d&63)))&0xFF]; + } else { + C = (C>>>8) ^ T0[(C ^ (224|((c>>12)&15)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|((c>>6)&63)))&0xFF]; + C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; + } + } + return ~C; } +CRC32.table = T0; +// $FlowIgnore +CRC32.bstr = crc32_bstr; +// $FlowIgnore +CRC32.buf = crc32_buf; +// $FlowIgnore +CRC32.str = crc32_str; +})); /***/ }), -/***/ 9417: -/***/ ((module) => { +/***/ 94521: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/** + * node-crc32-stream + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT + */ -module.exports = balanced; -function balanced(a, b, str) { - if (a instanceof RegExp) a = maybeMatch(a, str); - if (b instanceof RegExp) b = maybeMatch(b, str); - - var r = range(a, b, str); + - return r && { - start: r[0], - end: r[1], - pre: str.slice(0, r[0]), - body: str.slice(r[0] + a.length, r[1]), - post: str.slice(r[1] + b.length) - }; -} +const {Transform} = __nccwpck_require__(45193); -function maybeMatch(reg, str) { - var m = str.match(reg); - return m ? m[0] : null; -} +const crc32 = __nccwpck_require__(83201); -balanced.range = range; -function range(a, b, str) { - var begs, beg, left, right, result; - var ai = str.indexOf(a); - var bi = str.indexOf(b, ai + 1); - var i = ai; +class CRC32Stream extends Transform { + constructor(options) { + super(options); + this.checksum = Buffer.allocUnsafe(4); + this.checksum.writeInt32BE(0, 0); - if (ai >= 0 && bi > 0) { - begs = []; - left = str.length; + this.rawSize = 0; + } - while (i >= 0 && !result) { - if (i == ai) { - begs.push(i); - ai = str.indexOf(a, i + 1); - } else if (begs.length == 1) { - result = [ begs.pop(), bi ]; - } else { - beg = begs.pop(); - if (beg < left) { - left = beg; - right = bi; - } + _transform(chunk, encoding, callback) { + if (chunk) { + this.checksum = crc32.buf(chunk, this.checksum) >>> 0; + this.rawSize += chunk.length; + } - bi = str.indexOf(b, i + 1); - } + callback(null, chunk); + } - i = ai < bi && ai >= 0 ? ai : bi; - } + digest(encoding) { + const checksum = Buffer.allocUnsafe(4); + checksum.writeUInt32BE(this.checksum >>> 0, 0); + return encoding ? checksum.toString(encoding) : checksum; + } - if (begs.length) { - result = [ left, right ]; - } + hex() { + return this.digest('hex').toUpperCase(); } - return result; + size() { + return this.rawSize; + } } +module.exports = CRC32Stream; + /***/ }), -/***/ 83682: +/***/ 92563: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var register = __nccwpck_require__(44670); -var addHook = __nccwpck_require__(5549); -var removeHook = __nccwpck_require__(6819); +"use strict"; +/** + * node-crc32-stream + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT + */ -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind; -var bindable = bind.bind(bind); -function bindApi(hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach(function (kind) { - var args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); -} -function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {}, - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; -} +const {DeflateRaw} = __nccwpck_require__(59796); -function HookCollection() { - var state = { - registry: {}, - }; +const crc32 = __nccwpck_require__(83201); - var hook = register.bind(null, state); - bindApi(hook, state); +class DeflateCRC32Stream extends DeflateRaw { + constructor(options) { + super(options); - return hook; -} + this.checksum = Buffer.allocUnsafe(4); + this.checksum.writeInt32BE(0, 0); -var collectionHookDeprecationMessageDisplayed = false; -function Hook() { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn( - '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' - ); - collectionHookDeprecationMessageDisplayed = true; + this.rawSize = 0; + this.compressedSize = 0; } - return HookCollection(); -} - -Hook.Singular = HookSingular.bind(); -Hook.Collection = HookCollection.bind(); - -module.exports = Hook; -// expose constructors as a named property for TypeScript -module.exports.Hook = Hook; -module.exports.Singular = Hook.Singular; -module.exports.Collection = Hook.Collection; + push(chunk, encoding) { + if (chunk) { + this.compressedSize += chunk.length; + } -/***/ }), - -/***/ 5549: -/***/ ((module) => { + return super.push(chunk, encoding); + } -module.exports = addHook; + _transform(chunk, encoding, callback) { + if (chunk) { + this.checksum = crc32.buf(chunk, this.checksum) >>> 0; + this.rawSize += chunk.length; + } -function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; + super._transform(chunk, encoding, callback) } - if (kind === "before") { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)); - }; + digest(encoding) { + const checksum = Buffer.allocUnsafe(4); + checksum.writeUInt32BE(this.checksum >>> 0, 0); + return encoding ? checksum.toString(encoding) : checksum; } - if (kind === "after") { - hook = function (method, options) { - var result; - return Promise.resolve() - .then(method.bind(null, options)) - .then(function (result_) { - result = result_; - return orig(result, options); - }) - .then(function () { - return result; - }); - }; + hex() { + return this.digest('hex').toUpperCase(); } - if (kind === "error") { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options); - }); - }; + size(compressed = false) { + if (compressed) { + return this.compressedSize; + } else { + return this.rawSize; + } } +} - state.registry[name].push({ - hook: hook, - orig: orig, - }); +module.exports = DeflateCRC32Stream; + + +/***/ }), + +/***/ 5101: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/** + * node-crc32-stream + * + * Copyright (c) 2014 Chris Talkington, contributors. + * Licensed under the MIT license. + * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT + */ + + + +module.exports = { + CRC32Stream: __nccwpck_require__(94521), + DeflateCRC32Stream: __nccwpck_require__(92563) } /***/ }), -/***/ 44670: -/***/ ((module) => { +/***/ 18611: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = register; +var Stream = (__nccwpck_require__(12781).Stream); +var util = __nccwpck_require__(73837); -function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); +module.exports = DelayedStream; +function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; +} +util.inherits(DelayedStream, Stream); + +DelayedStream.create = function(source, options) { + var delayedStream = new this(); + + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; } - if (!options) { - options = {}; + delayedStream.source = source; + + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; + + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); } - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options); - }, method)(); + return delayedStream; +}; + +Object.defineProperty(DelayedStream.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; } +}); - return Promise.resolve().then(function () { - if (!state.registry[name]) { - return method(options); - } +DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); +}; - return state.registry[name].reduce(function (method, registered) { - return registered.hook.bind(null, method, options); - }, method)(); - }); -} +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); + } + + this.source.resume(); +}; +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; -/***/ }), +DelayedStream.prototype.release = function() { + this._released = true; -/***/ 6819: -/***/ ((module) => { + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; +}; -module.exports = removeHook; +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; +}; -function removeHook(state, name, method) { - if (!state.registry[name]) { +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); return; } - var index = state.registry[name] - .map(function (registered) { - return registered.orig; - }) - .indexOf(method); + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); + } - if (index === -1) { + this._bufferedEvents.push(args); +}; + +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { return; } - state.registry[name].splice(index, 1); + if (this.dataSize <= this.maxDataSize) { + return; + } + + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); +}; + + +/***/ }), + +/***/ 58932: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + + this.name = 'Deprecation'; + } + } +exports.Deprecation = Deprecation; + /***/ }), -/***/ 66474: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 13598: +/***/ ((module) => { -var Chainsaw = __nccwpck_require__(46533); -var EventEmitter = (__nccwpck_require__(82361).EventEmitter); -var Buffers = __nccwpck_require__(51590); -var Vars = __nccwpck_require__(13755); -var Stream = (__nccwpck_require__(12781).Stream); +"use strict"; -exports = module.exports = function (bufOrEm, eventName) { - if (Buffer.isBuffer(bufOrEm)) { - return exports.parse(bufOrEm); + +function _process (v, mod) { + var i + var r + + if (typeof mod === 'function') { + r = mod(v) + if (r !== undefined) { + v = r } - - var s = exports.stream(); - if (bufOrEm && bufOrEm.pipe) { - bufOrEm.pipe(s); + } else if (Array.isArray(mod)) { + for (i = 0; i < mod.length; i++) { + r = mod[i](v) + if (r !== undefined) { + v = r + } } - else if (bufOrEm) { - bufOrEm.on(eventName || 'data', function (buf) { - s.write(buf); - }); - - bufOrEm.on('end', function () { - s.end(); - }); + } + + return v +} + +function parseKey (key, val) { + // detect negative index notation + if (key[0] === '-' && Array.isArray(val) && /^-\d+$/.test(key)) { + return val.length + parseInt(key, 10) + } + return key +} + +function isIndex (k) { + return /^\d+$/.test(k) +} + +function isObject (val) { + return Object.prototype.toString.call(val) === '[object Object]' +} + +function isArrayOrObject (val) { + return Object(val) === val +} + +function isEmptyObject (val) { + return Object.keys(val).length === 0 +} + +var blacklist = ['__proto__', 'prototype', 'constructor'] +var blacklistFilter = function (part) { return blacklist.indexOf(part) === -1 } + +function parsePath (path, sep) { + if (path.indexOf('[') >= 0) { + path = path.replace(/\[/g, sep).replace(/]/g, '') + } + + var parts = path.split(sep) + + var check = parts.filter(blacklistFilter) + + if (check.length !== parts.length) { + throw Error('Refusing to update blacklisted property ' + path) + } + + return parts +} + +var hasOwnProperty = Object.prototype.hasOwnProperty + +function DotObject (separator, override, useArray, useBrackets) { + if (!(this instanceof DotObject)) { + return new DotObject(separator, override, useArray, useBrackets) + } + + if (typeof override === 'undefined') override = false + if (typeof useArray === 'undefined') useArray = true + if (typeof useBrackets === 'undefined') useBrackets = true + this.separator = separator || '.' + this.override = override + this.useArray = useArray + this.useBrackets = useBrackets + this.keepArray = false + + // contains touched arrays + this.cleanup = [] +} + +var dotDefault = new DotObject('.', false, true, true) +function wrap (method) { + return function () { + return dotDefault[method].apply(dotDefault, arguments) + } +} + +DotObject.prototype._fill = function (a, obj, v, mod) { + var k = a.shift() + + if (a.length > 0) { + obj[k] = obj[k] || (this.useArray && isIndex(a[0]) ? [] : {}) + + if (!isArrayOrObject(obj[k])) { + if (this.override) { + obj[k] = {} + } else { + if (!(isArrayOrObject(v) && isEmptyObject(v))) { + throw new Error( + 'Trying to redefine `' + k + '` which is a ' + typeof obj[k] + ) + } + + return + } } - return s; -}; -exports.stream = function (input) { - if (input) return exports.apply(null, arguments); - - var pending = null; - function getBytes (bytes, cb, skip) { - pending = { - bytes : bytes, - skip : skip, - cb : function (buf) { - pending = null; - cb(buf); - }, - }; - dispatch(); + this._fill(a, obj[k], v, mod) + } else { + if (!this.override && isArrayOrObject(obj[k]) && !isEmptyObject(obj[k])) { + if (!(isArrayOrObject(v) && isEmptyObject(v))) { + throw new Error("Trying to redefine non-empty obj['" + k + "']") + } + + return } - - var offset = null; - function dispatch () { - if (!pending) { - if (caughtEnd) done = true; - return; - } - if (typeof pending === 'function') { - pending(); - } - else { - var bytes = offset + pending.bytes; - - if (buffers.length >= bytes) { - var buf; - if (offset == null) { - buf = buffers.splice(0, bytes); - if (!pending.skip) { - buf = buf.slice(); - } - } - else { - if (!pending.skip) { - buf = buffers.slice(offset, bytes); - } - offset = bytes; - } - - if (pending.skip) { - pending.cb(); - } - else { - pending.cb(buf); - } + + obj[k] = _process(v, mod) + } +} + +/** + * + * Converts an object with dotted-key/value pairs to it's expanded version + * + * Optionally transformed by a set of modifiers. + * + * Usage: + * + * var row = { + * 'nr': 200, + * 'doc.name': ' My Document ' + * } + * + * var mods = { + * 'doc.name': [_s.trim, _s.underscored] + * } + * + * dot.object(row, mods) + * + * @param {Object} obj + * @param {Object} mods + */ +DotObject.prototype.object = function (obj, mods) { + var self = this + + Object.keys(obj).forEach(function (k) { + var mod = mods === undefined ? null : mods[k] + // normalize array notation. + var ok = parsePath(k, self.separator).join(self.separator) + + if (ok.indexOf(self.separator) !== -1) { + self._fill(ok.split(self.separator), obj, obj[k], mod) + delete obj[k] + } else { + obj[k] = _process(obj[k], mod) + } + }) + + return obj +} + +/** + * @param {String} path dotted path + * @param {String} v value to be set + * @param {Object} obj object to be modified + * @param {Function|Array} mod optional modifier + */ +DotObject.prototype.str = function (path, v, obj, mod) { + var ok = parsePath(path, this.separator).join(this.separator) + + if (path.indexOf(this.separator) !== -1) { + this._fill(ok.split(this.separator), obj, v, mod) + } else { + obj[path] = _process(v, mod) + } + + return obj +} + +/** + * + * Pick a value from an object using dot notation. + * + * Optionally remove the value + * + * @param {String} path + * @param {Object} obj + * @param {Boolean} remove + */ +DotObject.prototype.pick = function (path, obj, remove, reindexArray) { + var i + var keys + var val + var key + var cp + + keys = parsePath(path, this.separator) + for (i = 0; i < keys.length; i++) { + key = parseKey(keys[i], obj) + if (obj && typeof obj === 'object' && key in obj) { + if (i === keys.length - 1) { + if (remove) { + val = obj[key] + if (reindexArray && Array.isArray(obj)) { + obj.splice(key, 1) + } else { + delete obj[key] + } + if (Array.isArray(obj)) { + cp = keys.slice(0, -1).join('.') + if (this.cleanup.indexOf(cp) === -1) { + this.cleanup.push(cp) } + } + return val + } else { + return obj[key] } + } else { + obj = obj[key] + } + } else { + return undefined } - - function builder (saw) { - function next () { if (!done) saw.next() } - - var self = words(function (bytes, cb) { - return function (name) { - getBytes(bytes, function (buf) { - vars.set(name, cb(buf)); - next(); - }); - }; - }); - - self.tap = function (cb) { - saw.nest(cb, vars.store); - }; - - self.into = function (key, cb) { - if (!vars.get(key)) vars.set(key, {}); - var parent = vars; - vars = Vars(parent.get(key)); - - saw.nest(function () { - cb.apply(this, arguments); - this.tap(function () { - vars = parent; - }); - }, vars.store); - }; - - self.flush = function () { - vars.store = {}; - next(); - }; - - self.loop = function (cb) { - var end = false; - - saw.nest(false, function loop () { - this.vars = vars.store; - cb.call(this, function () { - end = true; - next(); - }, vars.store); - this.tap(function () { - if (end) saw.next() - else loop.call(this) - }.bind(this)); - }, vars.store); - }; - - self.buffer = function (name, bytes) { - if (typeof bytes === 'string') { - bytes = vars.get(bytes); - } - - getBytes(bytes, function (buf) { - vars.set(name, buf); - next(); - }); - }; - - self.skip = function (bytes) { - if (typeof bytes === 'string') { - bytes = vars.get(bytes); - } - - getBytes(bytes, function () { - next(); - }); - }; - - self.scan = function find (name, search) { - if (typeof search === 'string') { - search = new Buffer(search); - } - else if (!Buffer.isBuffer(search)) { - throw new Error('search must be a Buffer or a string'); - } - - var taken = 0; - pending = function () { - var pos = buffers.indexOf(search, offset + taken); - var i = pos-offset-taken; - if (pos !== -1) { - pending = null; - if (offset != null) { - vars.set( - name, - buffers.slice(offset, offset + taken + i) - ); - offset += taken + i + search.length; - } - else { - vars.set( - name, - buffers.slice(0, taken + i) - ); - buffers.splice(0, taken + i + search.length); - } - next(); - dispatch(); - } else { - i = Math.max(buffers.length - search.length - offset - taken, 0); - } - taken += i; - }; - dispatch(); - }; - - self.peek = function (cb) { - offset = 0; - saw.nest(function () { - cb.call(this, vars.store); - this.tap(function () { - offset = null; - }); - }); - }; - - return self; - }; - - var stream = Chainsaw.light(builder); - stream.writable = true; - - var buffers = Buffers(); - - stream.write = function (buf) { - buffers.push(buf); - dispatch(); - }; - - var vars = Vars(); - - var done = false, caughtEnd = false; - stream.end = function () { - caughtEnd = true; - }; - - stream.pipe = Stream.prototype.pipe; - Object.getOwnPropertyNames(EventEmitter.prototype).forEach(function (name) { - stream[name] = EventEmitter.prototype[name]; - }); - - return stream; -}; - -exports.parse = function parse (buffer) { - var self = words(function (bytes, cb) { - return function (name) { - if (offset + bytes <= buffer.length) { - var buf = buffer.slice(offset, offset + bytes); - offset += bytes; - vars.set(name, cb(buf)); - } - else { - vars.set(name, null); - } - return self; - }; - }); - - var offset = 0; - var vars = Vars(); - self.vars = vars.store; - - self.tap = function (cb) { - cb.call(self, vars.store); - return self; - }; - - self.into = function (key, cb) { - if (!vars.get(key)) { - vars.set(key, {}); - } - var parent = vars; - vars = Vars(parent.get(key)); - cb.call(self, vars.store); - vars = parent; - return self; - }; - - self.loop = function (cb) { - var end = false; - var ender = function () { end = true }; - while (end === false) { - cb.call(self, ender, vars.store); - } - return self; - }; - - self.buffer = function (name, size) { - if (typeof size === 'string') { - size = vars.get(size); - } - var buf = buffer.slice(offset, Math.min(buffer.length, offset + size)); - offset += size; - vars.set(name, buf); - - return self; - }; - - self.skip = function (bytes) { - if (typeof bytes === 'string') { - bytes = vars.get(bytes); - } - offset += bytes; - - return self; - }; - - self.scan = function (name, search) { - if (typeof search === 'string') { - search = new Buffer(search); - } - else if (!Buffer.isBuffer(search)) { - throw new Error('search must be a Buffer or a string'); - } - vars.set(name, null); - - // simple but slow string search - for (var i = 0; i + offset <= buffer.length - search.length + 1; i++) { - for ( - var j = 0; - j < search.length && buffer[offset+i+j] === search[j]; - j++ - ); - if (j === search.length) break; - } - - vars.set(name, buffer.slice(offset, offset + i)); - offset += i + search.length; - return self; - }; - - self.peek = function (cb) { - var was = offset; - cb.call(self, vars.store); - offset = was; - return self; - }; - - self.flush = function () { - vars.store = {}; - return self; - }; - - self.eof = function () { - return offset >= buffer.length; - }; - - return self; -}; - -// convert byte strings to unsigned little endian numbers -function decodeLEu (bytes) { - var acc = 0; - for (var i = 0; i < bytes.length; i++) { - acc += Math.pow(256,i) * bytes[i]; - } - return acc; + } + if (remove && Array.isArray(obj)) { + obj = obj.filter(function (n) { + return n !== undefined + }) + } + return obj } - -// convert byte strings to unsigned big endian numbers -function decodeBEu (bytes) { - var acc = 0; - for (var i = 0; i < bytes.length; i++) { - acc += Math.pow(256, bytes.length - i - 1) * bytes[i]; - } - return acc; +/** + * + * Delete value from an object using dot notation. + * + * @param {String} path + * @param {Object} obj + * @return {any} The removed value + */ +DotObject.prototype.delete = function (path, obj) { + return this.remove(path, obj, true) } -// convert byte strings to signed big endian numbers -function decodeBEs (bytes) { - var val = decodeBEu(bytes); - if ((bytes[0] & 0x80) == 0x80) { - val -= Math.pow(256, bytes.length); - } - return val; -} +/** + * + * Remove value from an object using dot notation. + * + * Will remove multiple items if path is an array. + * In this case array indexes will be retained until all + * removals have been processed. + * + * Use dot.delete() to automatically re-index arrays. + * + * @param {String|Array} path + * @param {Object} obj + * @param {Boolean} reindexArray + * @return {any} The removed value + */ +DotObject.prototype.remove = function (path, obj, reindexArray) { + var i -// convert byte strings to signed little endian numbers -function decodeLEs (bytes) { - var val = decodeLEu(bytes); - if ((bytes[bytes.length - 1] & 0x80) == 0x80) { - val -= Math.pow(256, bytes.length); + this.cleanup = [] + if (Array.isArray(path)) { + for (i = 0; i < path.length; i++) { + this.pick(path[i], obj, true, reindexArray) } - return val; -} - -function words (decode) { - var self = {}; - - [ 1, 2, 4, 8 ].forEach(function (bytes) { - var bits = bytes * 8; - - self['word' + bits + 'le'] - = self['word' + bits + 'lu'] - = decode(bytes, decodeLEu); - - self['word' + bits + 'ls'] - = decode(bytes, decodeLEs); - - self['word' + bits + 'be'] - = self['word' + bits + 'bu'] - = decode(bytes, decodeBEu); - - self['word' + bits + 'bs'] - = decode(bytes, decodeBEs); - }); - - // word8be(n) == word8le(n) for all n - self.word8 = self.word8u = self.word8be; - self.word8s = self.word8bs; - - return self; + if (!reindexArray) { + this._cleanup(obj) + } + return obj + } else { + return this.pick(path, obj, true, reindexArray) + } } - -/***/ }), - -/***/ 13755: -/***/ ((module) => { - -module.exports = function (store) { - function getset (name, value) { - var node = vars.store; - var keys = name.split('.'); - keys.slice(0,-1).forEach(function (k) { - if (node[k] === undefined) node[k] = {}; - node = node[k] - }); - var key = keys[keys.length - 1]; - if (arguments.length == 1) { - return node[key]; - } - else { - return node[key] = value; - } +DotObject.prototype._cleanup = function (obj) { + var ret + var i + var keys + var root + if (this.cleanup.length) { + for (i = 0; i < this.cleanup.length; i++) { + keys = this.cleanup[i].split('.') + root = keys.splice(0, -1).join('.') + ret = root ? this.pick(root, obj) : obj + ret = ret[keys[0]].filter(function (v) { + return v !== undefined + }) + this.set(this.cleanup[i], ret, obj) } - - var vars = { - get : function (name) { - return getset(name); - }, - set : function (name, value) { - return getset(name, value); - }, - store : store || {}, - }; - return vars; -}; - - -/***/ }), - -/***/ 23664: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -const { Buffer } = __nccwpck_require__(14300) -const symbol = Symbol.for('BufferList') - -function BufferList (buf) { - if (!(this instanceof BufferList)) { - return new BufferList(buf) + this.cleanup = [] } - - BufferList._init.call(this, buf) } -BufferList._init = function _init (buf) { - Object.defineProperty(this, symbol, { value: true }) - - this._bufs = [] - this.length = 0 +/** + * Alias method for `dot.remove` + * + * Note: this is not an alias for dot.delete() + * + * @param {String|Array} path + * @param {Object} obj + * @param {Boolean} reindexArray + * @return {any} The removed value + */ +DotObject.prototype.del = DotObject.prototype.remove - if (buf) { - this.append(buf) +/** + * + * Move a property from one place to the other. + * + * If the source path does not exist (undefined) + * the target property will not be set. + * + * @param {String} source + * @param {String} target + * @param {Object} obj + * @param {Function|Array} mods + * @param {Boolean} merge + */ +DotObject.prototype.move = function (source, target, obj, mods, merge) { + if (typeof mods === 'function' || Array.isArray(mods)) { + this.set(target, _process(this.pick(source, obj, true), mods), obj, merge) + } else { + merge = mods + this.set(target, this.pick(source, obj, true), obj, merge) } -} -BufferList.prototype._new = function _new (buf) { - return new BufferList(buf) + return obj } -BufferList.prototype._offset = function _offset (offset) { - if (offset === 0) { - return [0, 0] +/** + * + * Transfer a property from one object to another object. + * + * If the source path does not exist (undefined) + * the property on the other object will not be set. + * + * @param {String} source + * @param {String} target + * @param {Object} obj1 + * @param {Object} obj2 + * @param {Function|Array} mods + * @param {Boolean} merge + */ +DotObject.prototype.transfer = function ( + source, + target, + obj1, + obj2, + mods, + merge +) { + if (typeof mods === 'function' || Array.isArray(mods)) { + this.set( + target, + _process(this.pick(source, obj1, true), mods), + obj2, + merge + ) + } else { + merge = mods + this.set(target, this.pick(source, obj1, true), obj2, merge) } - let tot = 0 - - for (let i = 0; i < this._bufs.length; i++) { - const _t = tot + this._bufs[i].length - if (offset < _t || i === this._bufs.length - 1) { - return [i, offset - tot] - } - tot = _t - } + return obj2 } -BufferList.prototype._reverseOffset = function (blOffset) { - const bufferId = blOffset[0] - let offset = blOffset[1] - - for (let i = 0; i < bufferId; i++) { - offset += this._bufs[i].length +/** + * + * Copy a property from one object to another object. + * + * If the source path does not exist (undefined) + * the property on the other object will not be set. + * + * @param {String} source + * @param {String} target + * @param {Object} obj1 + * @param {Object} obj2 + * @param {Function|Array} mods + * @param {Boolean} merge + */ +DotObject.prototype.copy = function (source, target, obj1, obj2, mods, merge) { + if (typeof mods === 'function' || Array.isArray(mods)) { + this.set( + target, + _process( + // clone what is picked + JSON.parse(JSON.stringify(this.pick(source, obj1, false))), + mods + ), + obj2, + merge + ) + } else { + merge = mods + this.set(target, this.pick(source, obj1, false), obj2, merge) } - return offset + return obj2 } -BufferList.prototype.get = function get (index) { - if (index > this.length || index < 0) { - return undefined - } - - const offset = this._offset(index) - - return this._bufs[offset[0]][offset[1]] -} +/** + * + * Set a property on an object using dot notation. + * + * @param {String} path + * @param {any} val + * @param {Object} obj + * @param {Boolean} merge + */ +DotObject.prototype.set = function (path, val, obj, merge) { + var i + var k + var keys + var key -BufferList.prototype.slice = function slice (start, end) { - if (typeof start === 'number' && start < 0) { - start += this.length + // Do not operate if the value is undefined. + if (typeof val === 'undefined') { + return obj } + keys = parsePath(path, this.separator) - if (typeof end === 'number' && end < 0) { - end += this.length + for (i = 0; i < keys.length; i++) { + key = keys[i] + if (i === keys.length - 1) { + if (merge && isObject(val) && isObject(obj[key])) { + for (k in val) { + if (hasOwnProperty.call(val, k)) { + obj[key][k] = val[k] + } + } + } else if (merge && Array.isArray(obj[key]) && Array.isArray(val)) { + for (var j = 0; j < val.length; j++) { + obj[keys[i]].push(val[j]) + } + } else { + obj[key] = val + } + } else if ( + // force the value to be an object + !hasOwnProperty.call(obj, key) || + (!isObject(obj[key]) && !Array.isArray(obj[key])) + ) { + // initialize as array if next key is numeric + if (/^\d+$/.test(keys[i + 1])) { + obj[key] = [] + } else { + obj[key] = {} + } + } + obj = obj[key] } - - return this.copy(null, 0, start, end) + return obj } -BufferList.prototype.copy = function copy (dst, dstStart, srcStart, srcEnd) { - if (typeof srcStart !== 'number' || srcStart < 0) { - srcStart = 0 - } - - if (typeof srcEnd !== 'number' || srcEnd > this.length) { - srcEnd = this.length - } - - if (srcStart >= this.length) { - return dst || Buffer.alloc(0) - } +/** + * + * Transform an object + * + * Usage: + * + * var obj = { + * "id": 1, + * "some": { + * "thing": "else" + * } + * } + * + * var transform = { + * "id": "nr", + * "some.thing": "name" + * } + * + * var tgt = dot.transform(transform, obj) + * + * @param {Object} recipe Transform recipe + * @param {Object} obj Object to be transformed + * @param {Array} mods modifiers for the target + */ +DotObject.prototype.transform = function (recipe, obj, tgt) { + obj = obj || {} + tgt = tgt || {} + Object.keys(recipe).forEach( + function (key) { + this.set(recipe[key], this.pick(key, obj), tgt) + }.bind(this) + ) + return tgt +} - if (srcEnd <= 0) { - return dst || Buffer.alloc(0) - } +/** + * + * Convert object to dotted-key/value pair + * + * Usage: + * + * var tgt = dot.dot(obj) + * + * or + * + * var tgt = {} + * dot.dot(obj, tgt) + * + * @param {Object} obj source object + * @param {Object} tgt target object + * @param {Array} path path array (internal) + */ +DotObject.prototype.dot = function (obj, tgt, path) { + tgt = tgt || {} + path = path || [] + var isArray = Array.isArray(obj) - const copy = !!dst - const off = this._offset(srcStart) - const len = srcEnd - srcStart - let bytes = len - let bufoff = (copy && dstStart) || 0 - let start = off[1] + Object.keys(obj).forEach( + function (key) { + var index = isArray && this.useBrackets ? '[' + key + ']' : key + if ( + isArrayOrObject(obj[key]) && + ((isObject(obj[key]) && !isEmptyObject(obj[key])) || + (Array.isArray(obj[key]) && !this.keepArray && obj[key].length !== 0)) + ) { + if (isArray && this.useBrackets) { + var previousKey = path[path.length - 1] || '' + return this.dot( + obj[key], + tgt, + path.slice(0, -1).concat(previousKey + index) + ) + } else { + return this.dot(obj[key], tgt, path.concat(index)) + } + } else { + if (isArray && this.useBrackets) { + tgt[path.join(this.separator).concat('[' + key + ']')] = obj[key] + } else { + tgt[path.concat(index).join(this.separator)] = obj[key] + } + } + }.bind(this) + ) + return tgt +} - // copy/slice everything - if (srcStart === 0 && srcEnd === this.length) { - if (!copy) { - // slice, but full concat if multiple buffers - return this._bufs.length === 1 - ? this._bufs[0] - : Buffer.concat(this._bufs, this.length) +DotObject.pick = wrap('pick') +DotObject.move = wrap('move') +DotObject.transfer = wrap('transfer') +DotObject.transform = wrap('transform') +DotObject.copy = wrap('copy') +DotObject.object = wrap('object') +DotObject.str = wrap('str') +DotObject.set = wrap('set') +DotObject.delete = wrap('delete') +DotObject.del = DotObject.remove = wrap('remove') +DotObject.dot = wrap('dot'); +['override', 'overwrite'].forEach(function (prop) { + Object.defineProperty(DotObject, prop, { + get: function () { + return dotDefault.override + }, + set: function (val) { + dotDefault.override = !!val } - - // copy, need to copy individual buffers - for (let i = 0; i < this._bufs.length; i++) { - this._bufs[i].copy(dst, bufoff) - bufoff += this._bufs[i].length + }) +}); +['useArray', 'keepArray', 'useBrackets'].forEach(function (prop) { + Object.defineProperty(DotObject, prop, { + get: function () { + return dotDefault[prop] + }, + set: function (val) { + dotDefault[prop] = val } + }) +}) - return dst - } - - // easy, cheap case where it's a subset of one of the buffers - if (bytes <= this._bufs[off[0]].length - start) { - return copy - ? this._bufs[off[0]].copy(dst, dstStart, start, start + bytes) - : this._bufs[off[0]].slice(start, start + bytes) - } - - if (!copy) { - // a slice, we need something to copy in to - dst = Buffer.allocUnsafe(len) - } - - for (let i = off[0]; i < this._bufs.length; i++) { - const l = this._bufs[i].length - start +DotObject._process = _process - if (bytes > l) { - this._bufs[i].copy(dst, bufoff, start) - bufoff += l - } else { - this._bufs[i].copy(dst, bufoff, start, start + bytes) - bufoff += l - break - } +module.exports = DotObject - bytes -= l - if (start) { - start = 0 - } - } +/***/ }), - // safeguard so that we don't return uninitialized memory - if (dst.length > bufoff) return dst.slice(0, bufoff) +/***/ 84697: +/***/ ((module, exports) => { - return dst -} +"use strict"; +/** + * @author Toru Nagashima + * @copyright 2015 Toru Nagashima. All rights reserved. + * See LICENSE file in root directory for full license. + */ -BufferList.prototype.shallowSlice = function shallowSlice (start, end) { - start = start || 0 - end = typeof end !== 'number' ? this.length : end - if (start < 0) { - start += this.length - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - if (end < 0) { - end += this.length - } +/** + * @typedef {object} PrivateData + * @property {EventTarget} eventTarget The event target. + * @property {{type:string}} event The original event object. + * @property {number} eventPhase The current event phase. + * @property {EventTarget|null} currentTarget The current event target. + * @property {boolean} canceled The flag to prevent default. + * @property {boolean} stopped The flag to stop propagation. + * @property {boolean} immediateStopped The flag to stop propagation immediately. + * @property {Function|null} passiveListener The listener if the current listener is passive. Otherwise this is null. + * @property {number} timeStamp The unix time. + * @private + */ - if (start === end) { - return this._new() - } +/** + * Private data for event wrappers. + * @type {WeakMap} + * @private + */ +const privateData = new WeakMap(); - const startOffset = this._offset(start) - const endOffset = this._offset(end) - const buffers = this._bufs.slice(startOffset[0], endOffset[0] + 1) +/** + * Cache for wrapper classes. + * @type {WeakMap} + * @private + */ +const wrappers = new WeakMap(); - if (endOffset[1] === 0) { - buffers.pop() - } else { - buffers[buffers.length - 1] = buffers[buffers.length - 1].slice(0, endOffset[1]) - } +/** + * Get private data. + * @param {Event} event The event object to get private data. + * @returns {PrivateData} The private data of the event. + * @private + */ +function pd(event) { + const retv = privateData.get(event); + console.assert( + retv != null, + "'this' is expected an Event object, but got", + event + ); + return retv +} - if (startOffset[1] !== 0) { - buffers[0] = buffers[0].slice(startOffset[1]) - } +/** + * https://dom.spec.whatwg.org/#set-the-canceled-flag + * @param data {PrivateData} private data. + */ +function setCancelFlag(data) { + if (data.passiveListener != null) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error( + "Unable to preventDefault inside passive event listener invocation.", + data.passiveListener + ); + } + return + } + if (!data.event.cancelable) { + return + } - return this._new(buffers) + data.canceled = true; + if (typeof data.event.preventDefault === "function") { + data.event.preventDefault(); + } } -BufferList.prototype.toString = function toString (encoding, start, end) { - return this.slice(start, end).toString(encoding) -} +/** + * @see https://dom.spec.whatwg.org/#interface-event + * @private + */ +/** + * The event wrapper. + * @constructor + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Event|{type:string}} event The original event to wrap. + */ +function Event(eventTarget, event) { + privateData.set(this, { + eventTarget, + event, + eventPhase: 2, + currentTarget: eventTarget, + canceled: false, + stopped: false, + immediateStopped: false, + passiveListener: null, + timeStamp: event.timeStamp || Date.now(), + }); -BufferList.prototype.consume = function consume (bytes) { - // first, normalize the argument, in accordance with how Buffer does it - bytes = Math.trunc(bytes) - // do nothing if not a positive number - if (Number.isNaN(bytes) || bytes <= 0) return this + // https://heycam.github.io/webidl/#Unforgeable + Object.defineProperty(this, "isTrusted", { value: false, enumerable: true }); - while (this._bufs.length) { - if (bytes >= this._bufs[0].length) { - bytes -= this._bufs[0].length - this.length -= this._bufs[0].length - this._bufs.shift() - } else { - this._bufs[0] = this._bufs[0].slice(bytes) - this.length -= bytes - break + // Define accessors + const keys = Object.keys(event); + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in this)) { + Object.defineProperty(this, key, defineRedirectDescriptor(key)); + } } - } - - return this } -BufferList.prototype.duplicate = function duplicate () { - const copy = this._new() +// Should be enumerable, but class methods are not enumerable. +Event.prototype = { + /** + * The type of this event. + * @type {string} + */ + get type() { + return pd(this).event.type + }, - for (let i = 0; i < this._bufs.length; i++) { - copy.append(this._bufs[i]) - } + /** + * The target of this event. + * @type {EventTarget} + */ + get target() { + return pd(this).eventTarget + }, - return copy -} + /** + * The target of this event. + * @type {EventTarget} + */ + get currentTarget() { + return pd(this).currentTarget + }, -BufferList.prototype.append = function append (buf) { - if (buf == null) { - return this - } + /** + * @returns {EventTarget[]} The composed path of this event. + */ + composedPath() { + const currentTarget = pd(this).currentTarget; + if (currentTarget == null) { + return [] + } + return [currentTarget] + }, - if (buf.buffer) { - // append a view of the underlying ArrayBuffer - this._appendBuffer(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength)) - } else if (Array.isArray(buf)) { - for (let i = 0; i < buf.length; i++) { - this.append(buf[i]) - } - } else if (this._isBufferList(buf)) { - // unwrap argument into individual BufferLists - for (let i = 0; i < buf._bufs.length; i++) { - this.append(buf._bufs[i]) - } - } else { - // coerce number arguments to strings, since Buffer(number) does - // uninitialized memory allocation - if (typeof buf === 'number') { - buf = buf.toString() - } + /** + * Constant of NONE. + * @type {number} + */ + get NONE() { + return 0 + }, - this._appendBuffer(Buffer.from(buf)) - } + /** + * Constant of CAPTURING_PHASE. + * @type {number} + */ + get CAPTURING_PHASE() { + return 1 + }, - return this -} + /** + * Constant of AT_TARGET. + * @type {number} + */ + get AT_TARGET() { + return 2 + }, -BufferList.prototype._appendBuffer = function appendBuffer (buf) { - this._bufs.push(buf) - this.length += buf.length -} + /** + * Constant of BUBBLING_PHASE. + * @type {number} + */ + get BUBBLING_PHASE() { + return 3 + }, -BufferList.prototype.indexOf = function (search, offset, encoding) { - if (encoding === undefined && typeof offset === 'string') { - encoding = offset - offset = undefined - } + /** + * The target of this event. + * @type {number} + */ + get eventPhase() { + return pd(this).eventPhase + }, - if (typeof search === 'function' || Array.isArray(search)) { - throw new TypeError('The "value" argument must be one of type string, Buffer, BufferList, or Uint8Array.') - } else if (typeof search === 'number') { - search = Buffer.from([search]) - } else if (typeof search === 'string') { - search = Buffer.from(search, encoding) - } else if (this._isBufferList(search)) { - search = search.slice() - } else if (Array.isArray(search.buffer)) { - search = Buffer.from(search.buffer, search.byteOffset, search.byteLength) - } else if (!Buffer.isBuffer(search)) { - search = Buffer.from(search) - } + /** + * Stop event bubbling. + * @returns {void} + */ + stopPropagation() { + const data = pd(this); - offset = Number(offset || 0) + data.stopped = true; + if (typeof data.event.stopPropagation === "function") { + data.event.stopPropagation(); + } + }, - if (isNaN(offset)) { - offset = 0 - } + /** + * Stop event bubbling. + * @returns {void} + */ + stopImmediatePropagation() { + const data = pd(this); - if (offset < 0) { - offset = this.length + offset - } + data.stopped = true; + data.immediateStopped = true; + if (typeof data.event.stopImmediatePropagation === "function") { + data.event.stopImmediatePropagation(); + } + }, - if (offset < 0) { - offset = 0 - } + /** + * The flag to be bubbling. + * @type {boolean} + */ + get bubbles() { + return Boolean(pd(this).event.bubbles) + }, - if (search.length === 0) { - return offset > this.length ? this.length : offset - } + /** + * The flag to be cancelable. + * @type {boolean} + */ + get cancelable() { + return Boolean(pd(this).event.cancelable) + }, + + /** + * Cancel this event. + * @returns {void} + */ + preventDefault() { + setCancelFlag(pd(this)); + }, - const blOffset = this._offset(offset) - let blIndex = blOffset[0] // index of which internal buffer we're working on - let buffOffset = blOffset[1] // offset of the internal buffer we're working on + /** + * The flag to indicate cancellation state. + * @type {boolean} + */ + get defaultPrevented() { + return pd(this).canceled + }, - // scan over each buffer - for (; blIndex < this._bufs.length; blIndex++) { - const buff = this._bufs[blIndex] + /** + * The flag to be composed. + * @type {boolean} + */ + get composed() { + return Boolean(pd(this).event.composed) + }, - while (buffOffset < buff.length) { - const availableWindow = buff.length - buffOffset + /** + * The unix time of this event. + * @type {number} + */ + get timeStamp() { + return pd(this).timeStamp + }, - if (availableWindow >= search.length) { - const nativeSearchResult = buff.indexOf(search, buffOffset) + /** + * The target of this event. + * @type {EventTarget} + * @deprecated + */ + get srcElement() { + return pd(this).eventTarget + }, - if (nativeSearchResult !== -1) { - return this._reverseOffset([blIndex, nativeSearchResult]) + /** + * The flag to stop event bubbling. + * @type {boolean} + * @deprecated + */ + get cancelBubble() { + return pd(this).stopped + }, + set cancelBubble(value) { + if (!value) { + return } + const data = pd(this); - buffOffset = buff.length - search.length + 1 // end of native search window - } else { - const revOffset = this._reverseOffset([blIndex, buffOffset]) + data.stopped = true; + if (typeof data.event.cancelBubble === "boolean") { + data.event.cancelBubble = true; + } + }, - if (this._match(revOffset, search)) { - return revOffset + /** + * The flag to indicate cancellation state. + * @type {boolean} + * @deprecated + */ + get returnValue() { + return !pd(this).canceled + }, + set returnValue(value) { + if (!value) { + setCancelFlag(pd(this)); } + }, - buffOffset++ - } - } + /** + * Initialize this event object. But do nothing under event dispatching. + * @param {string} type The event type. + * @param {boolean} [bubbles=false] The flag to be possible to bubble up. + * @param {boolean} [cancelable=false] The flag to be possible to cancel. + * @deprecated + */ + initEvent() { + // Do nothing. + }, +}; - buffOffset = 0 - } +// `constructor` is not enumerable. +Object.defineProperty(Event.prototype, "constructor", { + value: Event, + configurable: true, + writable: true, +}); - return -1 +// Ensure `event instanceof window.Event` is `true`. +if (typeof window !== "undefined" && typeof window.Event !== "undefined") { + Object.setPrototypeOf(Event.prototype, window.Event.prototype); + + // Make association for wrappers. + wrappers.set(window.Event.prototype, Event); } -BufferList.prototype._match = function (offset, search) { - if (this.length - offset < search.length) { - return false - } +/** + * Get the property descriptor to redirect a given property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to redirect the property. + * @private + */ +function defineRedirectDescriptor(key) { + return { + get() { + return pd(this).event[key] + }, + set(value) { + pd(this).event[key] = value; + }, + configurable: true, + enumerable: true, + } +} - for (let searchOffset = 0; searchOffset < search.length; searchOffset++) { - if (this.get(offset + searchOffset) !== search[searchOffset]) { - return false +/** + * Get the property descriptor to call a given method property. + * @param {string} key Property name to define property descriptor. + * @returns {PropertyDescriptor} The property descriptor to call the method property. + * @private + */ +function defineCallDescriptor(key) { + return { + value() { + const event = pd(this).event; + return event[key].apply(event, arguments) + }, + configurable: true, + enumerable: true, } - } - return true } -;(function () { - const methods = { - readDoubleBE: 8, - readDoubleLE: 8, - readFloatBE: 4, - readFloatLE: 4, - readInt32BE: 4, - readInt32LE: 4, - readUInt32BE: 4, - readUInt32LE: 4, - readInt16BE: 2, - readInt16LE: 2, - readUInt16BE: 2, - readUInt16LE: 2, - readInt8: 1, - readUInt8: 1, - readIntBE: null, - readIntLE: null, - readUIntBE: null, - readUIntLE: null - } - - for (const m in methods) { - (function (m) { - if (methods[m] === null) { - BufferList.prototype[m] = function (offset, byteLength) { - return this.slice(offset, offset + byteLength)[m](0, byteLength) - } - } else { - BufferList.prototype[m] = function (offset = 0) { - return this.slice(offset, offset + methods[m])[m](0) +/** + * Define new wrapper class. + * @param {Function} BaseEvent The base wrapper class. + * @param {Object} proto The prototype of the original event. + * @returns {Function} The defined wrapper class. + * @private + */ +function defineWrapper(BaseEvent, proto) { + const keys = Object.keys(proto); + if (keys.length === 0) { + return BaseEvent + } + + /** CustomEvent */ + function CustomEvent(eventTarget, event) { + BaseEvent.call(this, eventTarget, event); + } + + CustomEvent.prototype = Object.create(BaseEvent.prototype, { + constructor: { value: CustomEvent, configurable: true, writable: true }, + }); + + // Define accessors. + for (let i = 0; i < keys.length; ++i) { + const key = keys[i]; + if (!(key in BaseEvent.prototype)) { + const descriptor = Object.getOwnPropertyDescriptor(proto, key); + const isFunc = typeof descriptor.value === "function"; + Object.defineProperty( + CustomEvent.prototype, + key, + isFunc + ? defineCallDescriptor(key) + : defineRedirectDescriptor(key) + ); } - } - }(m)) - } -}()) + } -// Used internally by the class and also as an indicator of this object being -// a `BufferList`. It's not possible to use `instanceof BufferList` in a browser -// environment because there could be multiple different copies of the -// BufferList class and some `BufferList`s might be `BufferList`s. -BufferList.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferList || BufferList.isBufferList(b) + return CustomEvent } -BufferList.isBufferList = function isBufferList (b) { - return b != null && b[symbol] -} +/** + * Get the wrapper class of a given prototype. + * @param {Object} proto The prototype of the original event to get its wrapper. + * @returns {Function} The wrapper class. + * @private + */ +function getWrapper(proto) { + if (proto == null || proto === Object.prototype) { + return Event + } -module.exports = BufferList + let wrapper = wrappers.get(proto); + if (wrapper == null) { + wrapper = defineWrapper(getWrapper(Object.getPrototypeOf(proto)), proto); + wrappers.set(proto, wrapper); + } + return wrapper +} +/** + * Wrap a given event to management a dispatching. + * @param {EventTarget} eventTarget The event target of this dispatching. + * @param {Object} event The event to wrap. + * @returns {Event} The wrapper instance. + * @private + */ +function wrapEvent(eventTarget, event) { + const Wrapper = getWrapper(Object.getPrototypeOf(event)); + return new Wrapper(eventTarget, event) +} -/***/ }), +/** + * Get the immediateStopped flag of a given event. + * @param {Event} event The event to get. + * @returns {boolean} The flag to stop propagation immediately. + * @private + */ +function isStopped(event) { + return pd(event).immediateStopped +} -/***/ 20336: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Set the current event phase of a given event. + * @param {Event} event The event to set current target. + * @param {number} eventPhase New event phase. + * @returns {void} + * @private + */ +function setEventPhase(event, eventPhase) { + pd(event).eventPhase = eventPhase; +} -"use strict"; +/** + * Set the current target of a given event. + * @param {Event} event The event to set current target. + * @param {EventTarget|null} currentTarget New current target. + * @returns {void} + * @private + */ +function setCurrentTarget(event, currentTarget) { + pd(event).currentTarget = currentTarget; +} +/** + * Set a passive listener of a given event. + * @param {Event} event The event to set current target. + * @param {Function|null} passiveListener New passive listener. + * @returns {void} + * @private + */ +function setPassiveListener(event, passiveListener) { + pd(event).passiveListener = passiveListener; +} -const DuplexStream = (__nccwpck_require__(51642).Duplex) -const inherits = __nccwpck_require__(44124) -const BufferList = __nccwpck_require__(23664) +/** + * @typedef {object} ListenerNode + * @property {Function} listener + * @property {1|2|3} listenerType + * @property {boolean} passive + * @property {boolean} once + * @property {ListenerNode|null} next + * @private + */ -function BufferListStream (callback) { - if (!(this instanceof BufferListStream)) { - return new BufferListStream(callback) - } +/** + * @type {WeakMap>} + * @private + */ +const listenersMap = new WeakMap(); - if (typeof callback === 'function') { - this._callback = callback +// Listener types +const CAPTURE = 1; +const BUBBLE = 2; +const ATTRIBUTE = 3; - const piper = function piper (err) { - if (this._callback) { - this._callback(err) - this._callback = null - } - }.bind(this) +/** + * Check whether a given value is an object or not. + * @param {any} x The value to check. + * @returns {boolean} `true` if the value is an object. + */ +function isObject(x) { + return x !== null && typeof x === "object" //eslint-disable-line no-restricted-syntax +} - this.on('pipe', function onPipe (src) { - src.on('error', piper) - }) - this.on('unpipe', function onUnpipe (src) { - src.removeListener('error', piper) - }) +/** + * Get listeners. + * @param {EventTarget} eventTarget The event target to get. + * @returns {Map} The listeners. + * @private + */ +function getListeners(eventTarget) { + const listeners = listenersMap.get(eventTarget); + if (listeners == null) { + throw new TypeError( + "'this' is expected an EventTarget object, but got another value." + ) + } + return listeners +} - callback = null - } +/** + * Get the property descriptor for the event attribute of a given event. + * @param {string} eventName The event name to get property descriptor. + * @returns {PropertyDescriptor} The property descriptor. + * @private + */ +function defineEventAttributeDescriptor(eventName) { + return { + get() { + const listeners = getListeners(this); + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + return node.listener + } + node = node.next; + } + return null + }, - BufferList._init.call(this, callback) - DuplexStream.call(this) -} + set(listener) { + if (typeof listener !== "function" && !isObject(listener)) { + listener = null; // eslint-disable-line no-param-reassign + } + const listeners = getListeners(this); + + // Traverse to the tail while removing old value. + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if (node.listenerType === ATTRIBUTE) { + // Remove old value. + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } -inherits(BufferListStream, DuplexStream) -Object.assign(BufferListStream.prototype, BufferList.prototype) + node = node.next; + } -BufferListStream.prototype._new = function _new (callback) { - return new BufferListStream(callback) + // Add new value. + if (listener !== null) { + const newNode = { + listener, + listenerType: ATTRIBUTE, + passive: false, + once: false, + next: null, + }; + if (prev === null) { + listeners.set(eventName, newNode); + } else { + prev.next = newNode; + } + } + }, + configurable: true, + enumerable: true, + } } -BufferListStream.prototype._write = function _write (buf, encoding, callback) { - this._appendBuffer(buf) - - if (typeof callback === 'function') { - callback() - } +/** + * Define an event attribute (e.g. `eventTarget.onclick`). + * @param {Object} eventTargetPrototype The event target prototype to define an event attrbite. + * @param {string} eventName The event name to define. + * @returns {void} + */ +function defineEventAttribute(eventTargetPrototype, eventName) { + Object.defineProperty( + eventTargetPrototype, + `on${eventName}`, + defineEventAttributeDescriptor(eventName) + ); } -BufferListStream.prototype._read = function _read (size) { - if (!this.length) { - return this.push(null) - } +/** + * Define a custom EventTarget with event attributes. + * @param {string[]} eventNames Event names for event attributes. + * @returns {EventTarget} The custom EventTarget. + * @private + */ +function defineCustomEventTarget(eventNames) { + /** CustomEventTarget */ + function CustomEventTarget() { + EventTarget.call(this); + } - size = Math.min(size, this.length) - this.push(this.slice(0, size)) - this.consume(size) -} + CustomEventTarget.prototype = Object.create(EventTarget.prototype, { + constructor: { + value: CustomEventTarget, + configurable: true, + writable: true, + }, + }); -BufferListStream.prototype.end = function end (chunk) { - DuplexStream.prototype.end.call(this, chunk) + for (let i = 0; i < eventNames.length; ++i) { + defineEventAttribute(CustomEventTarget.prototype, eventNames[i]); + } - if (this._callback) { - this._callback(null, this.slice()) - this._callback = null - } + return CustomEventTarget } -BufferListStream.prototype._destroy = function _destroy (err, cb) { - this._bufs.length = 0 - this.length = 0 - cb(err) +/** + * EventTarget. + * + * - This is constructor if no arguments. + * - This is a function which returns a CustomEventTarget constructor if there are arguments. + * + * For example: + * + * class A extends EventTarget {} + * class B extends EventTarget("message") {} + * class C extends EventTarget("message", "error") {} + * class D extends EventTarget(["message", "error"]) {} + */ +function EventTarget() { + /*eslint-disable consistent-return */ + if (this instanceof EventTarget) { + listenersMap.set(this, new Map()); + return + } + if (arguments.length === 1 && Array.isArray(arguments[0])) { + return defineCustomEventTarget(arguments[0]) + } + if (arguments.length > 0) { + const types = new Array(arguments.length); + for (let i = 0; i < arguments.length; ++i) { + types[i] = arguments[i]; + } + return defineCustomEventTarget(types) + } + throw new TypeError("Cannot call a class as a function") + /*eslint-enable consistent-return */ } -BufferListStream.prototype._isBufferList = function _isBufferList (b) { - return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b) -} +// Should be enumerable, but class methods are not enumerable. +EventTarget.prototype = { + /** + * Add a given listener to this event target. + * @param {string} eventName The event name to add. + * @param {Function} listener The listener to add. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + addEventListener(eventName, listener, options) { + if (listener == null) { + return + } + if (typeof listener !== "function" && !isObject(listener)) { + throw new TypeError("'listener' should be a function or an object.") + } + + const listeners = getListeners(this); + const optionsIsObj = isObject(options); + const capture = optionsIsObj + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + const newNode = { + listener, + listenerType, + passive: optionsIsObj && Boolean(options.passive), + once: optionsIsObj && Boolean(options.once), + next: null, + }; -BufferListStream.isBufferList = BufferList.isBufferList + // Set it as the first node if the first node is null. + let node = listeners.get(eventName); + if (node === undefined) { + listeners.set(eventName, newNode); + return + } -module.exports = BufferListStream -module.exports.BufferListStream = BufferListStream -module.exports.BufferList = BufferList + // Traverse to the tail while checking duplication.. + let prev = null; + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + // Should ignore duplication. + return + } + prev = node; + node = node.next; + } + // Add it. + prev.next = newNode; + }, -/***/ }), + /** + * Remove a given listener from this event target. + * @param {string} eventName The event name to remove. + * @param {Function} listener The listener to remove. + * @param {boolean|{capture?:boolean,passive?:boolean,once?:boolean}} [options] The options for this listener. + * @returns {void} + */ + removeEventListener(eventName, listener, options) { + if (listener == null) { + return + } -/***/ 11174: -/***/ (function(module) { + const listeners = getListeners(this); + const capture = isObject(options) + ? Boolean(options.capture) + : Boolean(options); + const listenerType = capture ? CAPTURE : BUBBLE; + + let prev = null; + let node = listeners.get(eventName); + while (node != null) { + if ( + node.listener === listener && + node.listenerType === listenerType + ) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + return + } -/** - * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support. - * https://github.com/SGrondin/bottleneck - */ -(function (global, factory) { - true ? module.exports = factory() : - 0; -}(this, (function () { 'use strict'; - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + prev = node; + node = node.next; + } + }, - function getCjsExportFromNamespace (n) { - return n && n['default'] || n; - } + /** + * Dispatch a given event. + * @param {Event|{type:string}} event The event to dispatch. + * @returns {boolean} `false` if canceled. + */ + dispatchEvent(event) { + if (event == null || typeof event.type !== "string") { + throw new TypeError('"event.type" should be a string.') + } - var load = function(received, defaults, onto = {}) { - var k, ref, v; - for (k in defaults) { - v = defaults[k]; - onto[k] = (ref = received[k]) != null ? ref : v; - } - return onto; - }; + // If listeners aren't registered, terminate. + const listeners = getListeners(this); + const eventName = event.type; + let node = listeners.get(eventName); + if (node == null) { + return true + } - var overwrite = function(received, defaults, onto = {}) { - var k, v; - for (k in received) { - v = received[k]; - if (defaults[k] !== void 0) { - onto[k] = v; - } - } - return onto; - }; + // Since we cannot rewrite several properties, so wrap object. + const wrappedEvent = wrapEvent(this, event); - var parser = { - load: load, - overwrite: overwrite - }; + // This doesn't process capturing phase and bubbling phase. + // This isn't participating in a tree. + let prev = null; + while (node != null) { + // Remove this listener if it's once + if (node.once) { + if (prev !== null) { + prev.next = node.next; + } else if (node.next !== null) { + listeners.set(eventName, node.next); + } else { + listeners.delete(eventName); + } + } else { + prev = node; + } - var DLList; + // Call this listener + setPassiveListener( + wrappedEvent, + node.passive ? node.listener : null + ); + if (typeof node.listener === "function") { + try { + node.listener.call(this, wrappedEvent); + } catch (err) { + if ( + typeof console !== "undefined" && + typeof console.error === "function" + ) { + console.error(err); + } + } + } else if ( + node.listenerType !== ATTRIBUTE && + typeof node.listener.handleEvent === "function" + ) { + node.listener.handleEvent(wrappedEvent); + } - DLList = class DLList { - constructor(incr, decr) { - this.incr = incr; - this.decr = decr; - this._first = null; - this._last = null; - this.length = 0; - } + // Break if `event.stopImmediatePropagation` was called. + if (isStopped(wrappedEvent)) { + break + } - push(value) { - var node; - this.length++; - if (typeof this.incr === "function") { - this.incr(); - } - node = { - value, - prev: this._last, - next: null - }; - if (this._last != null) { - this._last.next = node; - this._last = node; - } else { - this._first = this._last = node; - } - return void 0; - } + node = node.next; + } + setPassiveListener(wrappedEvent, null); + setEventPhase(wrappedEvent, 0); + setCurrentTarget(wrappedEvent, null); - shift() { - var value; - if (this._first == null) { - return; - } else { - this.length--; - if (typeof this.decr === "function") { - this.decr(); - } - } - value = this._first.value; - if ((this._first = this._first.next) != null) { - this._first.prev = null; - } else { - this._last = null; - } - return value; - } + return !wrappedEvent.defaultPrevented + }, +}; - first() { - if (this._first != null) { - return this._first.value; - } - } +// `constructor` is not enumerable. +Object.defineProperty(EventTarget.prototype, "constructor", { + value: EventTarget, + configurable: true, + writable: true, +}); - getArray() { - var node, ref, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, ref.value)); - } - return results; - } +// Ensure `eventTarget instanceof window.EventTarget` is `true`. +if ( + typeof window !== "undefined" && + typeof window.EventTarget !== "undefined" +) { + Object.setPrototypeOf(EventTarget.prototype, window.EventTarget.prototype); +} - forEachShift(cb) { - var node; - node = this.shift(); - while (node != null) { - (cb(node), node = this.shift()); - } - return void 0; - } +exports.defineEventAttribute = defineEventAttribute; +exports.EventTarget = EventTarget; +exports["default"] = EventTarget; - debug() { - var node, ref, ref1, ref2, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, { - value: ref.value, - prev: (ref1 = ref.prev) != null ? ref1.value : void 0, - next: (ref2 = ref.next) != null ? ref2.value : void 0 - })); - } - return results; - } +module.exports = EventTarget +module.exports.EventTarget = module.exports["default"] = EventTarget +module.exports.defineEventAttribute = defineEventAttribute +//# sourceMappingURL=event-target-shim.js.map - }; - var DLList_1 = DLList; +/***/ }), - var Events; +/***/ 27030: +/***/ ((module) => { - Events = class Events { - constructor(instance) { - this.instance = instance; - this._events = {}; - if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) { - throw new Error("An Emitter already exists for this object"); - } - this.instance.on = (name, cb) => { - return this._addListener(name, "many", cb); - }; - this.instance.once = (name, cb) => { - return this._addListener(name, "once", cb); - }; - this.instance.removeAllListeners = (name = null) => { - if (name != null) { - return delete this._events[name]; - } else { - return this._events = {}; - } - }; - } +module.exports = class FixedFIFO { + constructor (hwm) { + if (!(hwm > 0) || ((hwm - 1) & hwm) !== 0) throw new Error('Max size for a FixedFIFO should be a power of two') + this.buffer = new Array(hwm) + this.mask = hwm - 1 + this.top = 0 + this.btm = 0 + this.next = null + } - _addListener(name, status, cb) { - var base; - if ((base = this._events)[name] == null) { - base[name] = []; - } - this._events[name].push({cb, status}); - return this.instance; - } + clear () { + this.top = this.btm = 0 + this.next = null + this.buffer.fill(undefined) + } - listenerCount(name) { - if (this._events[name] != null) { - return this._events[name].length; - } else { - return 0; - } - } + push (data) { + if (this.buffer[this.top] !== undefined) return false + this.buffer[this.top] = data + this.top = (this.top + 1) & this.mask + return true + } - async trigger(name, ...args) { - var e, promises; - try { - if (name !== "debug") { - this.trigger("debug", `Event triggered: ${name}`, args); - } - if (this._events[name] == null) { - return; - } - this._events[name] = this._events[name].filter(function(listener) { - return listener.status !== "none"; - }); - promises = this._events[name].map(async(listener) => { - var e, returned; - if (listener.status === "none") { - return; - } - if (listener.status === "once") { - listener.status = "none"; - } - try { - returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; - if (typeof (returned != null ? returned.then : void 0) === "function") { - return (await returned); - } else { - return returned; - } - } catch (error) { - e = error; - { - this.trigger("error", e); - } - return null; - } - }); - return ((await Promise.all(promises))).find(function(x) { - return x != null; - }); - } catch (error) { - e = error; - { - this.trigger("error", e); - } - return null; - } - } + shift () { + const last = this.buffer[this.btm] + if (last === undefined) return undefined + this.buffer[this.btm] = undefined + this.btm = (this.btm + 1) & this.mask + return last + } - }; + peek () { + return this.buffer[this.btm] + } - var Events_1 = Events; + isEmpty () { + return this.buffer[this.btm] === undefined + } +} - var DLList$1, Events$1, Queues; - DLList$1 = DLList_1; +/***/ }), - Events$1 = Events_1; +/***/ 92958: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Queues = class Queues { - constructor(num_priorities) { - var i; - this.Events = new Events$1(this); - this._length = 0; - this._lists = (function() { - var j, ref, results; - results = []; - for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { - results.push(new DLList$1((() => { - return this.incr(); - }), (() => { - return this.decr(); - }))); - } - return results; - }).call(this); - } +const FixedFIFO = __nccwpck_require__(27030) - incr() { - if (this._length++ === 0) { - return this.Events.trigger("leftzero"); - } - } +module.exports = class FastFIFO { + constructor (hwm) { + this.hwm = hwm || 16 + this.head = new FixedFIFO(this.hwm) + this.tail = this.head + this.length = 0 + } - decr() { - if (--this._length === 0) { - return this.Events.trigger("zero"); - } - } + clear () { + this.head = this.tail + this.head.clear() + this.length = 0 + } - push(job) { - return this._lists[job.options.priority].push(job); - } + push (val) { + this.length++ + if (!this.head.push(val)) { + const prev = this.head + this.head = prev.next = new FixedFIFO(2 * this.head.buffer.length) + this.head.push(val) + } + } - queued(priority) { - if (priority != null) { - return this._lists[priority].length; - } else { - return this._length; - } - } + shift () { + if (this.length !== 0) this.length-- + const val = this.tail.shift() + if (val === undefined && this.tail.next) { + const next = this.tail.next + this.tail.next = null + this.tail = next + return this.tail.shift() + } - shiftAll(fn) { - return this._lists.forEach(function(list) { - return list.forEachShift(fn); - }); - } + return val + } - getFirst(arr = this._lists) { - var j, len, list; - for (j = 0, len = arr.length; j < len; j++) { - list = arr[j]; - if (list.length > 0) { - return list; - } - } - return []; - } + peek () { + const val = this.tail.peek() + if (val === undefined && this.tail.next) return this.tail.next.peek() + return val + } - shiftLastFrom(priority) { - return this.getFirst(this._lists.slice(priority).reverse()).shift(); - } + isEmpty () { + return this.length === 0 + } +} - }; - var Queues_1 = Queues; +/***/ }), - var BottleneckError; +/***/ 64334: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - BottleneckError = class BottleneckError extends Error {}; +var CombinedStream = __nccwpck_require__(85443); +var util = __nccwpck_require__(73837); +var path = __nccwpck_require__(71017); +var http = __nccwpck_require__(13685); +var https = __nccwpck_require__(95687); +var parseUrl = (__nccwpck_require__(57310).parse); +var fs = __nccwpck_require__(57147); +var Stream = (__nccwpck_require__(12781).Stream); +var mime = __nccwpck_require__(43583); +var asynckit = __nccwpck_require__(14812); +var populate = __nccwpck_require__(17142); - var BottleneckError_1 = BottleneckError; +// Public API +module.exports = FormData; - var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; +// make it a Stream +util.inherits(FormData, CombinedStream); - NUM_PRIORITIES = 10; +/** + * Create readable "multipart/form-data" streams. + * Can be used to submit forms + * and file uploads to other web applications. + * + * @constructor + * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + */ +function FormData(options) { + if (!(this instanceof FormData)) { + return new FormData(options); + } - DEFAULT_PRIORITY = 5; + this._overheadLength = 0; + this._valueLength = 0; + this._valuesToMeasure = []; - parser$1 = parser; + CombinedStream.call(this); - BottleneckError$1 = BottleneckError_1; + options = options || {}; + for (var option in options) { + this[option] = options[option]; + } +} - Job = class Job { - constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { - this.task = task; - this.args = args; - this.rejectOnDrop = rejectOnDrop; - this.Events = Events; - this._states = _states; - this.Promise = Promise; - this.options = parser$1.load(options, jobDefaults); - this.options.priority = this._sanitizePriority(this.options.priority); - if (this.options.id === jobDefaults.id) { - this.options.id = `${this.options.id}-${this._randomIndex()}`; - } - this.promise = new this.Promise((_resolve, _reject) => { - this._resolve = _resolve; - this._reject = _reject; - }); - this.retryCount = 0; - } +FormData.LINE_BREAK = '\r\n'; +FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; - _sanitizePriority(priority) { - var sProperty; - sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; - if (sProperty < 0) { - return 0; - } else if (sProperty > NUM_PRIORITIES - 1) { - return NUM_PRIORITIES - 1; - } else { - return sProperty; - } - } +FormData.prototype.append = function(field, value, options) { - _randomIndex() { - return Math.random().toString(36).slice(2); - } + options = options || {}; - doDrop({error, message = "This job has been dropped by Bottleneck"} = {}) { - if (this._states.remove(this.options.id)) { - if (this.rejectOnDrop) { - this._reject(error != null ? error : new BottleneckError$1(message)); - } - this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise}); - return true; - } else { - return false; - } - } + // allow filename as single option + if (typeof options == 'string') { + options = {filename: options}; + } - _assertStatus(expected) { - var status; - status = this._states.jobStatus(this.options.id); - if (!(status === expected || (expected === "DONE" && status === null))) { - throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); - } - } + var append = CombinedStream.prototype.append.bind(this); - doReceive() { - this._states.start(this.options.id); - return this.Events.trigger("received", {args: this.args, options: this.options}); - } + // all that streamy business can't handle numbers + if (typeof value == 'number') { + value = '' + value; + } - doQueue(reachedHWM, blocked) { - this._assertStatus("RECEIVED"); - this._states.next(this.options.id); - return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked}); - } + // https://github.com/felixge/node-form-data/issues/38 + if (util.isArray(value)) { + // Please convert your array into string + // the way web server expects it + this._error(new Error('Arrays are not supported.')); + return; + } - doRun() { - if (this.retryCount === 0) { - this._assertStatus("QUEUED"); - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); - } - return this.Events.trigger("scheduled", {args: this.args, options: this.options}); - } + var header = this._multiPartHeader(field, value, options); + var footer = this._multiPartFooter(); - async doExecute(chained, clearGlobalState, run, free) { - var error, eventInfo, passed; - if (this.retryCount === 0) { - this._assertStatus("RUNNING"); - this._states.next(this.options.id); - } else { - this._assertStatus("EXECUTING"); - } - eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; - this.Events.trigger("executing", eventInfo); - try { - passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args))); - if (clearGlobalState()) { - this.doDone(eventInfo); - await free(this.options, eventInfo); - this._assertStatus("DONE"); - return this._resolve(passed); - } - } catch (error1) { - error = error1; - return this._onFailure(error, eventInfo, clearGlobalState, run, free); - } - } + append(header); + append(value); + append(footer); - doExpire(clearGlobalState, run, free) { - var error, eventInfo; - if (this._states.jobStatus(this.options.id === "RUNNING")) { - this._states.next(this.options.id); - } - this._assertStatus("EXECUTING"); - eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; - error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`); - return this._onFailure(error, eventInfo, clearGlobalState, run, free); - } + // pass along options.knownLength + this._trackLength(header, value, options); +}; - async _onFailure(error, eventInfo, clearGlobalState, run, free) { - var retry, retryAfter; - if (clearGlobalState()) { - retry = (await this.Events.trigger("failed", error, eventInfo)); - if (retry != null) { - retryAfter = ~~retry; - this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); - this.retryCount++; - return run(retryAfter); - } else { - this.doDone(eventInfo); - await free(this.options, eventInfo); - this._assertStatus("DONE"); - return this._reject(error); - } - } - } +FormData.prototype._trackLength = function(header, value, options) { + var valueLength = 0; - doDone(eventInfo) { - this._assertStatus("EXECUTING"); - this._states.next(this.options.id); - return this.Events.trigger("done", eventInfo); - } - - }; - - var Job_1 = Job; + // used w/ getLengthSync(), when length is known. + // e.g. for streaming directly from a remote server, + // w/ a known file a size, and not wanting to wait for + // incoming file to finish to get its size. + if (options.knownLength != null) { + valueLength += +options.knownLength; + } else if (Buffer.isBuffer(value)) { + valueLength = value.length; + } else if (typeof value === 'string') { + valueLength = Buffer.byteLength(value); + } - var BottleneckError$2, LocalDatastore, parser$2; + this._valueLength += valueLength; - parser$2 = parser; + // @check why add CRLF? does this account for custom/multiple CRLFs? + this._overheadLength += + Buffer.byteLength(header) + + FormData.LINE_BREAK.length; - BottleneckError$2 = BottleneckError_1; + // empty or either doesn't have path or not an http response or not a stream + if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { + return; + } - LocalDatastore = class LocalDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.clientId = this.instance._randomIndex(); - parser$2.load(storeInstanceOptions, storeInstanceOptions, this); - this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); - this._running = 0; - this._done = 0; - this._unblockTime = 0; - this.ready = this.Promise.resolve(); - this.clients = {}; - this._startHeartbeat(); - } + // no need to bother with the length + if (!options.knownLength) { + this._valuesToMeasure.push(value); + } +}; - _startHeartbeat() { - var base; - if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) { - return typeof (base = (this.heartbeat = setInterval(() => { - var amount, incr, maximum, now, reservoir; - now = Date.now(); - if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { - this._lastReservoirRefresh = now; - this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; - this.instance._drainAll(this.computeCapacity()); - } - if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { - ({ - reservoirIncreaseAmount: amount, - reservoirIncreaseMaximum: maximum, - reservoir - } = this.storeOptions); - this._lastReservoirIncrease = now; - incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; - if (incr > 0) { - this.storeOptions.reservoir += incr; - return this.instance._drainAll(this.computeCapacity()); - } - } - }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0; - } else { - return clearInterval(this.heartbeat); - } - } +FormData.prototype._lengthRetriever = function(value, callback) { - async __publish__(message) { - await this.yieldLoop(); - return this.instance.Events.trigger("message", message.toString()); - } + if (value.hasOwnProperty('fd')) { - async __disconnect__(flush) { - await this.yieldLoop(); - clearInterval(this.heartbeat); - return this.Promise.resolve(); - } + // take read range into a account + // `end` = Infinity –> read file till the end + // + // TODO: Looks like there is bug in Node fs.createReadStream + // it doesn't respect `end` options without `start` options + // Fix it when node fixes it. + // https://github.com/joyent/node/issues/7819 + if (value.end != undefined && value.end != Infinity && value.start != undefined) { - yieldLoop(t = 0) { - return new this.Promise(function(resolve, reject) { - return setTimeout(resolve, t); - }); - } + // when end specified + // no need to calculate range + // inclusive, starts with 0 + callback(null, value.end + 1 - (value.start ? value.start : 0)); - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; - } + // not that fast snoopy + } else { + // still need to fetch file size from fs + fs.stat(value.path, function(err, stat) { - async __updateSettings__(options) { - await this.yieldLoop(); - parser$2.overwrite(options, options, this.storeOptions); - this._startHeartbeat(); - this.instance._drainAll(this.computeCapacity()); - return true; - } + var fileSize; - async __running__() { - await this.yieldLoop(); - return this._running; - } + if (err) { + callback(err); + return; + } - async __queued__() { - await this.yieldLoop(); - return this.instance.queued(); - } + // update final size based on the range options + fileSize = stat.size - (value.start ? value.start : 0); + callback(null, fileSize); + }); + } - async __done__() { - await this.yieldLoop(); - return this._done; - } + // or http response + } else if (value.hasOwnProperty('httpVersion')) { + callback(null, +value.headers['content-length']); - async __groupCheck__(time) { - await this.yieldLoop(); - return (this._nextRequest + this.timeout) < time; - } + // or request stream http://github.com/mikeal/request + } else if (value.hasOwnProperty('httpModule')) { + // wait till response come back + value.on('response', function(response) { + value.pause(); + callback(null, +response.headers['content-length']); + }); + value.resume(); - computeCapacity() { - var maxConcurrent, reservoir; - ({maxConcurrent, reservoir} = this.storeOptions); - if ((maxConcurrent != null) && (reservoir != null)) { - return Math.min(maxConcurrent - this._running, reservoir); - } else if (maxConcurrent != null) { - return maxConcurrent - this._running; - } else if (reservoir != null) { - return reservoir; - } else { - return null; - } - } + // something else + } else { + callback('Unknown stream'); + } +}; - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return (capacity == null) || weight <= capacity; - } +FormData.prototype._multiPartHeader = function(field, value, options) { + // custom header specified (as string)? + // it becomes responsible for boundary + // (e.g. to handle extra CRLFs on .NET servers) + if (typeof options.header == 'string') { + return options.header; + } - async __incrementReservoir__(incr) { - var reservoir; - await this.yieldLoop(); - reservoir = this.storeOptions.reservoir += incr; - this.instance._drainAll(this.computeCapacity()); - return reservoir; - } + var contentDisposition = this._getContentDisposition(value, options); + var contentType = this._getContentType(value, options); - async __currentReservoir__() { - await this.yieldLoop(); - return this.storeOptions.reservoir; - } + var contents = ''; + var headers = { + // add custom disposition as third element or keep it two elements if not + 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), + // if no content type. allow it to be empty array + 'Content-Type': [].concat(contentType || []) + }; - isBlocked(now) { - return this._unblockTime >= now; - } + // allow custom headers. + if (typeof options.header == 'object') { + populate(headers, options.header); + } - check(weight, now) { - return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; - } + var header; + for (var prop in headers) { + if (!headers.hasOwnProperty(prop)) continue; + header = headers[prop]; - async __check__(weight) { - var now; - await this.yieldLoop(); - now = Date.now(); - return this.check(weight, now); - } + // skip nullish headers. + if (header == null) { + continue; + } - async __register__(index, weight, expiration) { - var now, wait; - await this.yieldLoop(); - now = Date.now(); - if (this.conditionsCheck(weight)) { - this._running += weight; - if (this.storeOptions.reservoir != null) { - this.storeOptions.reservoir -= weight; - } - wait = Math.max(this._nextRequest - now, 0); - this._nextRequest = now + wait + this.storeOptions.minTime; - return { - success: true, - wait, - reservoir: this.storeOptions.reservoir - }; - } else { - return { - success: false - }; - } - } + // convert all headers to arrays. + if (!Array.isArray(header)) { + header = [header]; + } - strategyIsBlock() { - return this.storeOptions.strategy === 3; - } + // add non-empty headers. + if (header.length) { + contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; + } + } - async __submit__(queueLength, weight) { - var blocked, now, reachedHWM; - await this.yieldLoop(); - if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { - throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); - } - now = Date.now(); - reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now); - blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); - if (blocked) { - this._unblockTime = now + this.computePenalty(); - this._nextRequest = this._unblockTime + this.storeOptions.minTime; - this.instance._dropAllQueued(); - } - return { - reachedHWM, - blocked, - strategy: this.storeOptions.strategy - }; - } + return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; +}; - async __free__(index, weight) { - await this.yieldLoop(); - this._running -= weight; - this._done += weight; - this.instance._drainAll(this.computeCapacity()); - return { - running: this._running - }; - } +FormData.prototype._getContentDisposition = function(value, options) { - }; + var filename + , contentDisposition + ; - var LocalDatastore_1 = LocalDatastore; + if (typeof options.filepath === 'string') { + // custom filepath for relative paths + filename = path.normalize(options.filepath).replace(/\\/g, '/'); + } else if (options.filename || value.name || value.path) { + // custom filename take precedence + // formidable and the browser add a name property + // fs- and request- streams have path property + filename = path.basename(options.filename || value.name || value.path); + } else if (value.readable && value.hasOwnProperty('httpVersion')) { + // or try http response + filename = path.basename(value.client._httpMessage.path || ''); + } - var BottleneckError$3, States; + if (filename) { + contentDisposition = 'filename="' + filename + '"'; + } - BottleneckError$3 = BottleneckError_1; + return contentDisposition; +}; - States = class States { - constructor(status1) { - this.status = status1; - this._jobs = {}; - this.counts = this.status.map(function() { - return 0; - }); - } +FormData.prototype._getContentType = function(value, options) { - next(id) { - var current, next; - current = this._jobs[id]; - next = current + 1; - if ((current != null) && next < this.status.length) { - this.counts[current]--; - this.counts[next]++; - return this._jobs[id]++; - } else if (current != null) { - this.counts[current]--; - return delete this._jobs[id]; - } - } + // use custom content-type above all + var contentType = options.contentType; - start(id) { - var initial; - initial = 0; - this._jobs[id] = initial; - return this.counts[initial]++; - } + // or try `name` from formidable, browser + if (!contentType && value.name) { + contentType = mime.lookup(value.name); + } - remove(id) { - var current; - current = this._jobs[id]; - if (current != null) { - this.counts[current]--; - delete this._jobs[id]; - } - return current != null; - } + // or try `path` from fs-, request- streams + if (!contentType && value.path) { + contentType = mime.lookup(value.path); + } - jobStatus(id) { - var ref; - return (ref = this.status[this._jobs[id]]) != null ? ref : null; - } + // or if it's http-reponse + if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { + contentType = value.headers['content-type']; + } - statusJobs(status) { - var k, pos, ref, results, v; - if (status != null) { - pos = this.status.indexOf(status); - if (pos < 0) { - throw new BottleneckError$3(`status must be one of ${this.status.join(', ')}`); - } - ref = this._jobs; - results = []; - for (k in ref) { - v = ref[k]; - if (v === pos) { - results.push(k); - } - } - return results; - } else { - return Object.keys(this._jobs); - } - } + // or guess it from the filepath or filename + if (!contentType && (options.filepath || options.filename)) { + contentType = mime.lookup(options.filepath || options.filename); + } - statusCounts() { - return this.counts.reduce(((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }), {}); - } + // fallback to the default content type if `value` is not simple value + if (!contentType && typeof value == 'object') { + contentType = FormData.DEFAULT_CONTENT_TYPE; + } - }; + return contentType; +}; - var States_1 = States; +FormData.prototype._multiPartFooter = function() { + return function(next) { + var footer = FormData.LINE_BREAK; - var DLList$2, Sync; + var lastPart = (this._streams.length === 0); + if (lastPart) { + footer += this._lastBoundary(); + } - DLList$2 = DLList_1; + next(footer); + }.bind(this); +}; - Sync = class Sync { - constructor(name, Promise) { - this.schedule = this.schedule.bind(this); - this.name = name; - this.Promise = Promise; - this._running = 0; - this._queue = new DLList$2(); - } +FormData.prototype._lastBoundary = function() { + return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; +}; - isEmpty() { - return this._queue.length === 0; - } +FormData.prototype.getHeaders = function(userHeaders) { + var header; + var formHeaders = { + 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() + }; - async _tryToRun() { - var args, cb, error, reject, resolve, returned, task; - if ((this._running < 1) && this._queue.length > 0) { - this._running++; - ({task, args, resolve, reject} = this._queue.shift()); - cb = (await (async function() { - try { - returned = (await task(...args)); - return function() { - return resolve(returned); - }; - } catch (error1) { - error = error1; - return function() { - return reject(error); - }; - } - })()); - this._running--; - this._tryToRun(); - return cb(); - } - } + for (header in userHeaders) { + if (userHeaders.hasOwnProperty(header)) { + formHeaders[header.toLowerCase()] = userHeaders[header]; + } + } - schedule(task, ...args) { - var promise, reject, resolve; - resolve = reject = null; - promise = new this.Promise(function(_resolve, _reject) { - resolve = _resolve; - return reject = _reject; - }); - this._queue.push({task, args, resolve, reject}); - this._tryToRun(); - return promise; - } + return formHeaders; +}; - }; +FormData.prototype.setBoundary = function(boundary) { + this._boundary = boundary; +}; - var Sync_1 = Sync; +FormData.prototype.getBoundary = function() { + if (!this._boundary) { + this._generateBoundary(); + } - var version = "2.19.5"; - var version$1 = { - version: version - }; + return this._boundary; +}; - var version$2 = /*#__PURE__*/Object.freeze({ - version: version, - default: version$1 - }); +FormData.prototype.getBuffer = function() { + var dataBuffer = new Buffer.alloc( 0 ); + var boundary = this.getBoundary(); - var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + // Create the form content. Add Line breaks to the end of data. + for (var i = 0, len = this._streams.length; i < len; i++) { + if (typeof this._streams[i] !== 'function') { - var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + // Add content to the buffer. + if(Buffer.isBuffer(this._streams[i])) { + dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); + }else { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); + } - var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + // Add break after content. + if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { + dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); + } + } + } - var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; + // Add the footer and return the Buffer object. + return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); +}; - parser$3 = parser; +FormData.prototype._generateBoundary = function() { + // This generates a 50 character boundary similar to those used by Firefox. + // They are optimized for boyer-moore parsing. + var boundary = '--------------------------'; + for (var i = 0; i < 24; i++) { + boundary += Math.floor(Math.random() * 10).toString(16); + } - Events$2 = Events_1; + this._boundary = boundary; +}; - RedisConnection$1 = require$$2; +// Note: getLengthSync DOESN'T calculate streams length +// As workaround one can calculate file size manually +// and add it as knownLength option +FormData.prototype.getLengthSync = function() { + var knownLength = this._overheadLength + this._valueLength; - IORedisConnection$1 = require$$3; + // Don't get confused, there are 3 "internal" streams for each keyval pair + // so it basically checks if there is any value added to the form + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } - Scripts$1 = require$$4; + // https://github.com/form-data/form-data/issues/40 + if (!this.hasKnownLength()) { + // Some async length retrievers are present + // therefore synchronous length calculation is false. + // Please use getLength(callback) to get proper length + this._error(new Error('Cannot calculate proper length in synchronous way.')); + } - Group = (function() { - class Group { - constructor(limiterOptions = {}) { - this.deleteKey = this.deleteKey.bind(this); - this.limiterOptions = limiterOptions; - parser$3.load(this.limiterOptions, this.defaults, this); - this.Events = new Events$2(this); - this.instances = {}; - this.Bottleneck = Bottleneck_1; - this._startAutoCleanup(); - this.sharedConnection = this.connection != null; - if (this.connection == null) { - if (this.limiterOptions.datastore === "redis") { - this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); - } else if (this.limiterOptions.datastore === "ioredis") { - this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); - } - } - } + return knownLength; +}; - key(key = "") { - var ref; - return (ref = this.instances[key]) != null ? ref : (() => { - var limiter; - limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { - id: `${this.id}-${key}`, - timeout: this.timeout, - connection: this.connection - })); - this.Events.trigger("created", limiter, key); - return limiter; - })(); - } +// Public API to check if length of added values is known +// https://github.com/form-data/form-data/issues/196 +// https://github.com/form-data/form-data/issues/262 +FormData.prototype.hasKnownLength = function() { + var hasKnownLength = true; - async deleteKey(key = "") { - var deleted, instance; - instance = this.instances[key]; - if (this.connection) { - deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)])); - } - if (instance != null) { - delete this.instances[key]; - await instance.disconnect(); - } - return (instance != null) || deleted > 0; - } + if (this._valuesToMeasure.length) { + hasKnownLength = false; + } - limiters() { - var k, ref, results, v; - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - results.push({ - key: k, - limiter: v - }); - } - return results; - } + return hasKnownLength; +}; - keys() { - return Object.keys(this.instances); - } +FormData.prototype.getLength = function(cb) { + var knownLength = this._overheadLength + this._valueLength; - async clusterKeys() { - var cursor, end, found, i, k, keys, len, next, start; - if (this.connection == null) { - return this.Promise.resolve(this.keys()); - } - keys = []; - cursor = null; - start = `b_${this.id}-`.length; - end = "_settings".length; - while (cursor !== 0) { - [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000])); - cursor = ~~next; - for (i = 0, len = found.length; i < len; i++) { - k = found[i]; - keys.push(k.slice(start, -end)); - } - } - return keys; - } + if (this._streams.length) { + knownLength += this._lastBoundary().length; + } - _startAutoCleanup() { - var base; - clearInterval(this.interval); - return typeof (base = (this.interval = setInterval(async() => { - var e, k, ref, results, time, v; - time = Date.now(); - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - try { - if ((await v._store.__groupCheck__(time))) { - results.push(this.deleteKey(k)); - } else { - results.push(void 0); - } - } catch (error) { - e = error; - results.push(v.Events.trigger("error", e)); - } - } - return results; - }, this.timeout / 2))).unref === "function" ? base.unref() : void 0; - } + if (!this._valuesToMeasure.length) { + process.nextTick(cb.bind(this, null, knownLength)); + return; + } - updateSettings(options = {}) { - parser$3.overwrite(options, this.defaults, this); - parser$3.overwrite(options, options, this.limiterOptions); - if (options.timeout != null) { - return this._startAutoCleanup(); - } - } + asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { + if (err) { + cb(err); + return; + } - disconnect(flush = true) { - var ref; - if (!this.sharedConnection) { - return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; - } - } + values.forEach(function(length) { + knownLength += length; + }); - } - Group.prototype.defaults = { - timeout: 1000 * 60 * 5, - connection: null, - Promise: Promise, - id: "group-key" - }; + cb(null, knownLength); + }); +}; - return Group; +FormData.prototype.submit = function(params, cb) { + var request + , options + , defaults = {method: 'post'} + ; - }).call(commonjsGlobal); + // parse provided url if it's string + // or treat it as options object + if (typeof params == 'string') { - var Group_1 = Group; + params = parseUrl(params); + options = populate({ + port: params.port, + path: params.pathname, + host: params.hostname, + protocol: params.protocol + }, defaults); - var Batcher, Events$3, parser$4; + // use custom params + } else { - parser$4 = parser; + options = populate(params, defaults); + // if no port provided use default one + if (!options.port) { + options.port = options.protocol == 'https:' ? 443 : 80; + } + } - Events$3 = Events_1; + // put that good code in getHeaders to some use + options.headers = this.getHeaders(params.headers); - Batcher = (function() { - class Batcher { - constructor(options = {}) { - this.options = options; - parser$4.load(this.options, this.defaults, this); - this.Events = new Events$3(this); - this._arr = []; - this._resetPromise(); - this._lastFlush = Date.now(); - } + // https if specified, fallback to http in any other case + if (options.protocol == 'https:') { + request = https.request(options); + } else { + request = http.request(options); + } - _resetPromise() { - return this._promise = new this.Promise((res, rej) => { - return this._resolve = res; - }); - } + // get content length and fire away + this.getLength(function(err, length) { + if (err && err !== 'Unknown stream') { + this._error(err); + return; + } - _flush() { - clearTimeout(this._timeout); - this._lastFlush = Date.now(); - this._resolve(); - this.Events.trigger("batch", this._arr); - this._arr = []; - return this._resetPromise(); - } + // add content length + if (length) { + request.setHeader('Content-Length', length); + } - add(data) { - var ret; - this._arr.push(data); - ret = this._promise; - if (this._arr.length === this.maxSize) { - this._flush(); - } else if ((this.maxTime != null) && this._arr.length === 1) { - this._timeout = setTimeout(() => { - return this._flush(); - }, this.maxTime); - } - return ret; - } + this.pipe(request); + if (cb) { + var onResponse; - } - Batcher.prototype.defaults = { - maxTime: null, - maxSize: null, - Promise: Promise - }; + var callback = function (error, responce) { + request.removeListener('error', callback); + request.removeListener('response', onResponse); - return Batcher; + return cb.call(this, error, responce); + }; - }).call(commonjsGlobal); + onResponse = callback.bind(this, null); - var Batcher_1 = Batcher; + request.on('error', callback); + request.on('response', onResponse); + } + }.bind(this)); - var require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + return request; +}; - var require$$8 = getCjsExportFromNamespace(version$2); +FormData.prototype._error = function(err) { + if (!this.error) { + this.error = err; + this.pause(); + this.emit('error', err); + } +}; - var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, - splice = [].splice; +FormData.prototype.toString = function () { + return '[object FormData]'; +}; - NUM_PRIORITIES$1 = 10; - DEFAULT_PRIORITY$1 = 5; +/***/ }), - parser$5 = parser; +/***/ 17142: +/***/ ((module) => { - Queues$1 = Queues_1; +// populates missing values +module.exports = function(dst, src) { - Job$1 = Job_1; + Object.keys(src).forEach(function(prop) + { + dst[prop] = dst[prop] || src[prop]; + }); - LocalDatastore$1 = LocalDatastore_1; + return dst; +}; - RedisDatastore$1 = require$$4$1; - Events$4 = Events_1; +/***/ }), - States$1 = States_1; +/***/ 67356: +/***/ ((module) => { - Sync$1 = Sync_1; +"use strict"; - Bottleneck = (function() { - class Bottleneck { - constructor(options = {}, ...invalid) { - var storeInstanceOptions, storeOptions; - this._addToQueue = this._addToQueue.bind(this); - this._validateOptions(options, invalid); - parser$5.load(options, this.instanceDefaults, this); - this._queues = new Queues$1(NUM_PRIORITIES$1); - this._scheduled = {}; - this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); - this._limiter = null; - this.Events = new Events$4(this); - this._submitLock = new Sync$1("submit", this.Promise); - this._registerLock = new Sync$1("register", this.Promise); - storeOptions = parser$5.load(options, this.storeDefaults, {}); - this._store = (function() { - if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { - storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {}); - return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); - } else if (this.datastore === "local") { - storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {}); - return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); - } else { - throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); - } - }).call(this); - this._queues.on("leftzero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; - }); - this._queues.on("zero", () => { - var ref; - return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; - }); - } - _validateOptions(options, invalid) { - if (!((options != null) && typeof options === "object" && invalid.length === 0)) { - throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); - } - } +module.exports = clone - ready() { - return this._store.ready; - } +var getPrototypeOf = Object.getPrototypeOf || function (obj) { + return obj.__proto__ +} - clients() { - return this._store.clients; - } +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj - channel() { - return `b_${this.id}`; - } + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) } + else + var copy = Object.create(null) - channel_client() { - return `b_${this.id}_${this._store.clientId}`; - } + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) - publish(message) { - return this._store.__publish__(message); - } + return copy +} - disconnect(flush = true) { - return this._store.__disconnect__(flush); - } - chain(_limiter) { - this._limiter = _limiter; - return this; - } +/***/ }), - queued(priority) { - return this._queues.queued(priority); - } +/***/ 77758: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - clusterQueued() { - return this._store.__queued__(); - } +var fs = __nccwpck_require__(57147) +var polyfills = __nccwpck_require__(20263) +var legacy = __nccwpck_require__(73086) +var clone = __nccwpck_require__(67356) - empty() { - return this.queued() === 0 && this._submitLock.isEmpty(); - } +var util = __nccwpck_require__(73837) - running() { - return this._store.__running__(); - } +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol - done() { - return this._store.__done__(); - } +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' +} - jobStatus(id) { - return this._states.jobStatus(id); - } +function noop () {} - jobs(status) { - return this._states.statusJobs(status); - } +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue + } + }) +} - counts() { - return this._states.statusCounts(); - } +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } - _randomIndex() { - return Math.random().toString(36).slice(2); - } +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) - check(weight = 1) { - return this._store.__check__(weight); - } + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + resetQueue() + } - _clearGlobalState(index) { - if (this._scheduled[index] != null) { - clearTimeout(this._scheduled[index].expiration); - delete this._scheduled[index]; - return true; - } else { - return false; - } - } - - async _free(index, job, options, eventInfo) { - var e, running; - try { - ({running} = (await this._store.__free__(index, options.weight))); - this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); - if (running === 0 && this.empty()) { - return this.Events.trigger("idle"); - } - } catch (error1) { - e = error1; - return this.Events.trigger("error", e); - } - } - - _run(index, job, wait) { - var clearGlobalState, free, run; - job.doRun(); - clearGlobalState = this._clearGlobalState.bind(this, index); - run = this._run.bind(this, index, job); - free = this._free.bind(this, index, job); - return this._scheduled[index] = { - timeout: setTimeout(() => { - return job.doExecute(this._limiter, clearGlobalState, run, free); - }, wait), - expiration: job.options.expiration != null ? setTimeout(function() { - return job.doExpire(clearGlobalState, run, free); - }, wait + job.options.expiration) : void 0, - job: job - }; - } - - _drainOne(capacity) { - return this._registerLock.schedule(() => { - var args, index, next, options, queue; - if (this.queued() === 0) { - return this.Promise.resolve(null); - } - queue = this._queues.getFirst(); - ({options, args} = next = queue.first()); - if ((capacity != null) && options.weight > capacity) { - return this.Promise.resolve(null); - } - this.Events.trigger("debug", `Draining ${options.id}`, {args, options}); - index = this._randomIndex(); - return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => { - var empty; - this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options}); - if (success) { - queue.shift(); - empty = this.empty(); - if (empty) { - this.Events.trigger("empty"); - } - if (reservoir === 0) { - this.Events.trigger("depleted", empty); - } - this._run(index, next, wait); - return this.Promise.resolve(options.weight); - } else { - return this.Promise.resolve(null); - } - }); - }); - } - - _drainAll(capacity, total = 0) { - return this._drainOne(capacity).then((drained) => { - var newCapacity; - if (drained != null) { - newCapacity = capacity != null ? capacity - drained : capacity; - return this._drainAll(newCapacity, total + drained); - } else { - return this.Promise.resolve(total); - } - }).catch((e) => { - return this.Events.trigger("error", e); - }); - } - - _dropAllQueued(message) { - return this._queues.shiftAll(function(job) { - return job.doDrop({message}); - }); - } - - stop(options = {}) { - var done, waitForExecuting; - options = parser$5.load(options, this.stopDefaults); - waitForExecuting = (at) => { - var finished; - finished = () => { - var counts; - counts = this._states.counts; - return (counts[0] + counts[1] + counts[2] + counts[3]) === at; - }; - return new this.Promise((resolve, reject) => { - if (finished()) { - return resolve(); - } else { - return this.on("done", () => { - if (finished()) { - this.removeAllListeners("done"); - return resolve(); - } - }); - } - }); - }; - done = options.dropWaitingJobs ? (this._run = function(index, next) { - return next.doDrop({ - message: options.dropErrorMessage - }); - }, this._drainOne = () => { - return this.Promise.resolve(null); - }, this._registerLock.schedule(() => { - return this._submitLock.schedule(() => { - var k, ref, v; - ref = this._scheduled; - for (k in ref) { - v = ref[k]; - if (this.jobStatus(v.job.options.id) === "RUNNING") { - clearTimeout(v.timeout); - clearTimeout(v.expiration); - v.job.doDrop({ - message: options.dropErrorMessage - }); - } - } - this._dropAllQueued(options.dropErrorMessage); - return waitForExecuting(0); - }); - })) : this.schedule({ - priority: NUM_PRIORITIES$1 - 1, - weight: 0 - }, () => { - return waitForExecuting(1); - }); - this._receive = function(job) { - return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); - }; - this.stop = () => { - return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); - }; - return done; - } - - async _addToQueue(job) { - var args, blocked, error, options, reachedHWM, shifted, strategy; - ({args, options} = job); - try { - ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); - } catch (error1) { - error = error1; - this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error}); - job.doDrop({error}); - return false; - } - if (blocked) { - job.doDrop(); - return true; - } else if (reachedHWM) { - shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; - if (shifted != null) { - shifted.doDrop(); - } - if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { - if (shifted == null) { - job.doDrop(); - } - return reachedHWM; - } - } - job.doQueue(reachedHWM, blocked); - this._queues.push(job); - await this._drainAll(); - return reachedHWM; - } - - _receive(job) { - if (this._states.jobStatus(job.options.id) != null) { - job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); - return false; - } else { - job.doReceive(); - return this._submitLock.schedule(this._addToQueue, job); - } - } + if (typeof cb === 'function') + cb.apply(this, arguments) + }) + } - submit(...args) { - var cb, fn, job, options, ref, ref1, task; - if (typeof args[0] === "function") { - ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1); - options = parser$5.load({}, this.jobDefaults); - } else { - ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1); - options = parser$5.load(options, this.jobDefaults); - } - task = (...args) => { - return new this.Promise(function(resolve, reject) { - return fn(...args, function(...args) { - return (args[0] != null ? reject : resolve)(args); - }); - }); - }; - job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - job.promise.then(function(args) { - return typeof cb === "function" ? cb(...args) : void 0; - }).catch(function(args) { - if (Array.isArray(args)) { - return typeof cb === "function" ? cb(...args) : void 0; - } else { - return typeof cb === "function" ? cb(args) : void 0; - } - }); - return this._receive(job); - } + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) - schedule(...args) { - var job, options, task; - if (typeof args[0] === "function") { - [task, ...args] = args; - options = {}; - } else { - [options, task, ...args] = args; - } - job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); - this._receive(job); - return job.promise; - } + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + resetQueue() + } - wrap(fn) { - var schedule, wrapped; - schedule = this.schedule.bind(this); - wrapped = function(...args) { - return schedule(fn.bind(this), ...args); - }; - wrapped.withOptions = function(options, ...args) { - return schedule(options, fn, ...args); - }; - return wrapped; - } + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) - async updateSettings(options = {}) { - await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); - parser$5.overwrite(options, this.instanceDefaults, this); - return this; - } + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + __nccwpck_require__(39491).equal(fs[gracefulQueue].length, 0) + }) + } +} - currentReservoir() { - return this._store.__currentReservoir__(); - } +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); +} - incrementReservoir(incr = 0) { - return this._store.__incrementReservoir__(incr); - } +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} - } - Bottleneck.default = Bottleneck; +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch - Bottleneck.Events = Events$4; + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - Bottleneck.version = Bottleneck.prototype.version = require$$8.version; + return go$readFile(path, options, cb) - Bottleneck.strategy = Bottleneck.prototype.strategy = { - LEAK: 1, - OVERFLOW: 2, - OVERFLOW_PRIORITY: 4, - BLOCK: 3 - }; + function go$readFile (path, options, cb, startTime) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } - Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - Bottleneck.Group = Bottleneck.prototype.Group = Group_1; + return go$writeFile(path, data, options, cb) - Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; + function go$writeFile (path, data, options, cb, startTime) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } - Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null - Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; + return go$appendFile(path, data, options, cb) - Bottleneck.prototype.jobDefaults = { - priority: DEFAULT_PRIORITY$1, - weight: 1, - expiration: null, - id: "" - }; + function go$appendFile (path, data, options, cb, startTime) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } - Bottleneck.prototype.storeDefaults = { - maxConcurrent: null, - minTime: 0, - highWater: null, - strategy: Bottleneck.prototype.strategy.LEAK, - penalty: null, - reservoir: null, - reservoirRefreshInterval: null, - reservoirRefreshAmount: null, - reservoirIncreaseInterval: null, - reservoirIncreaseAmount: null, - reservoirIncreaseMaximum: null - }; + var fs$copyFile = fs.copyFile + if (fs$copyFile) + fs.copyFile = copyFile + function copyFile (src, dest, flags, cb) { + if (typeof flags === 'function') { + cb = flags + flags = 0 + } + return go$copyFile(src, dest, flags, cb) - Bottleneck.prototype.localStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 250 - }; + function go$copyFile (src, dest, flags, cb, startTime) { + return fs$copyFile(src, dest, flags, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } - Bottleneck.prototype.redisStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 5000, - clientTimeout: 10000, - Redis: null, - clientOptions: {}, - clusterNodes: null, - clearDatastore: false, - connection: null - }; + var fs$readdir = fs.readdir + fs.readdir = readdir + var noReaddirOptionVersions = /^v[0-5]\./ + function readdir (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - Bottleneck.prototype.instanceDefaults = { - datastore: "local", - connection: null, - id: "", - rejectOnDrop: true, - trackDoneStatus: false, - Promise: Promise - }; + var go$readdir = noReaddirOptionVersions.test(process.version) + ? function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, fs$readdirCallback( + path, options, cb, startTime + )) + } + : function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, options, fs$readdirCallback( + path, options, cb, startTime + )) + } - Bottleneck.prototype.stopDefaults = { - enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", - dropWaitingJobs: true, - dropErrorMessage: "This limiter has been stopped." - }; + return go$readdir(path, options, cb) - return Bottleneck; + function fs$readdirCallback (path, options, cb, startTime) { + return function (err, files) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([ + go$readdir, + [path, options, cb], + err, + startTime || Date.now(), + Date.now() + ]) + else { + if (files && files.sort) + files.sort() - }).call(commonjsGlobal); + if (typeof cb === 'function') + cb.call(this, err, files) + } + } + } + } - var Bottleneck_1 = Bottleneck; + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } - var lib = Bottleneck_1; + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } - return lib; + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } -}))); + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) -/***/ }), + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } -/***/ 33717: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() -var balanced = __nccwpck_require__(9417); + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } -module.exports = expandTop; + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } -var escSlash = '\0SLASH'+Math.random()+'\0'; -var escOpen = '\0OPEN'+Math.random()+'\0'; -var escClose = '\0CLOSE'+Math.random()+'\0'; -var escComma = '\0COMMA'+Math.random()+'\0'; -var escPeriod = '\0PERIOD'+Math.random()+'\0'; + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } -function numeric(str) { - return parseInt(str, 10) == str - ? parseInt(str, 10) - : str.charCodeAt(0); -} + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } -function escapeBraces(str) { - return str.split('\\\\').join(escSlash) - .split('\\{').join(escOpen) - .split('\\}').join(escClose) - .split('\\,').join(escComma) - .split('\\.').join(escPeriod); + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } + + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null + + return go$open(path, flags, mode, cb) + + function go$open (path, flags, mode, cb, startTime) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + return fs } -function unescapeBraces(str) { - return str.split(escSlash).join('\\') - .split(escOpen).join('{') - .split(escClose).join('}') - .split(escComma).join(',') - .split(escPeriod).join('.'); +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) + retry() } +// keep track of the timeout between retry() calls +var retryTimer -// Basically just str.split(","), but handling cases -// where we have nested braced sections, which should be -// treated as individual members, like {a,{b,c},d} -function parseCommaParts(str) { - if (!str) - return ['']; +// reset the startTime and lastTime to now +// this resets the start of the 60 second overall timeout as well as the +// delay between attempts so that we'll retry these jobs sooner +function resetQueue () { + var now = Date.now() + for (var i = 0; i < fs[gracefulQueue].length; ++i) { + // entries that are only a length of 2 are from an older version, don't + // bother modifying those since they'll be retried anyway. + if (fs[gracefulQueue][i].length > 2) { + fs[gracefulQueue][i][3] = now // startTime + fs[gracefulQueue][i][4] = now // lastTime + } + } + // call retry to make sure we're actively processing the queue + retry() +} - var parts = []; - var m = balanced('{', '}', str); +function retry () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer) + retryTimer = undefined - if (!m) - return str.split(','); + if (fs[gracefulQueue].length === 0) + return - var pre = m.pre; - var body = m.body; - var post = m.post; - var p = pre.split(','); + var elem = fs[gracefulQueue].shift() + var fn = elem[0] + var args = elem[1] + // these items may be unset if they were added by an older graceful-fs + var err = elem[2] + var startTime = elem[3] + var lastTime = elem[4] - p[p.length-1] += '{' + body + '}'; - var postParts = parseCommaParts(post); - if (post.length) { - p[p.length-1] += postParts.shift(); - p.push.apply(p, postParts); + // if we don't have a startTime we have no way of knowing if we've waited + // long enough, so go ahead and retry this item now + if (startTime === undefined) { + debug('RETRY', fn.name, args) + fn.apply(null, args) + } else if (Date.now() - startTime >= 60000) { + // it's been more than 60 seconds total, bail now + debug('TIMEOUT', fn.name, args) + var cb = args.pop() + if (typeof cb === 'function') + cb.call(null, err) + } else { + // the amount of time between the last attempt and right now + var sinceAttempt = Date.now() - lastTime + // the amount of time between when we first tried, and when we last tried + // rounded up to at least 1 + var sinceStart = Math.max(lastTime - startTime, 1) + // backoff. wait longer than the total time we've been retrying, but only + // up to a maximum of 100ms + var desiredDelay = Math.min(sinceStart * 1.2, 100) + // it's been long enough since the last retry, do it again + if (sinceAttempt >= desiredDelay) { + debug('RETRY', fn.name, args) + fn.apply(null, args.concat([startTime])) + } else { + // if we can't do this job yet, push it to the end of the queue + // and let the next iteration check again + fs[gracefulQueue].push(elem) + } } - parts.push.apply(parts, p); - - return parts; + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0) + } } -function expandTop(str) { - if (!str) - return []; - // I don't know why Bash 4.3 does this, but it does. - // Anything starting with {} will have the first two bytes preserved - // but *only* at the top level, so {},a}b will not expand to anything, - // but a{},b}c will be expanded to [a}c,abc]. - // One could argue that this is a bug in Bash, but since the goal of - // this module is to match Bash's rules, we escape a leading {} - if (str.substr(0, 2) === '{}') { - str = '\\{\\}' + str.substr(2); +/***/ }), + +/***/ 73086: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Stream = (__nccwpck_require__(12781).Stream) + +module.exports = legacy + +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream } - return expand(escapeBraces(str), true).map(unescapeBraces); -} + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); -function embrace(str) { - return '{' + str + '}'; -} -function isPadded(el) { - return /^-?0\d/.test(el); -} + Stream.call(this); -function lte(i, y) { - return i <= y; -} -function gte(i, y) { - return i >= y; -} + var self = this; -function expand(str, isTop) { - var expansions = []; + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; - var m = balanced('{', '}', str); - if (!m) return [str]; + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; - // no need to expand pre, since it is guaranteed to be free of brace-sets - var pre = m.pre; - var post = m.post.length - ? expand(m.post, false) - : ['']; + options = options || {}; - if (/\$$/.test(m.pre)) { - for (var k = 0; k < post.length; k++) { - var expansion = pre+ '{' + m.body + '}' + post[k]; - expansions.push(expansion); + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; } - } else { - var isNumericSequence = /^-?\d+\.\.-?\d+(?:\.\.-?\d+)?$/.test(m.body); - var isAlphaSequence = /^[a-zA-Z]\.\.[a-zA-Z](?:\.\.-?\d+)?$/.test(m.body); - var isSequence = isNumericSequence || isAlphaSequence; - var isOptions = m.body.indexOf(',') >= 0; - if (!isSequence && !isOptions) { - // {a},b} - if (m.post.match(/,.*\}/)) { - str = m.pre + '{' + m.body + escClose + m.post; - return expand(str); + + if (this.encoding) this.setEncoding(this.encoding); + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); } - return [str]; - } - var n; - if (isSequence) { - n = m.body.split(/\.\./); - } else { - n = parseCommaParts(m.body); - if (n.length === 1) { - // x{{a,b}}y ==> x{a}y x{b}y - n = expand(n[0], false).map(embrace); - if (n.length === 1) { - return post.map(function(p) { - return m.pre + n[0] + p; - }); - } + if (this.start > this.end) { + throw new Error('start must be <= end'); } + + this.pos = this.start; } - // at this point, n is the parts, and we know it's not a comma set - // with a single entry. - var N; + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } - if (isSequence) { - var x = numeric(n[0]); - var y = numeric(n[1]); - var width = Math.max(n[0].length, n[1].length) - var incr = n.length == 3 - ? Math.abs(numeric(n[2])) - : 1; - var test = lte; - var reverse = y < x; - if (reverse) { - incr *= -1; - test = gte; + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; } - var pad = n.some(isPadded); - N = []; + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } - for (var i = x; test(i, y); i += incr) { - var c; - if (isAlphaSequence) { - c = String.fromCharCode(i); - if (c === '\\') - c = ''; - } else { - c = String(i); - if (pad) { - var need = width - c.length; - if (need > 0) { - var z = new Array(need + 1).join('0'); - if (i < 0) - c = '-' + z + c.slice(1); - else - c = z + c; - } - } - } - N.push(c); - } - } else { - N = []; + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); - for (var j = 0; j < n.length; j++) { - N.push.apply(N, expand(n[j], false)); - } + Stream.call(this); + + this.path = path; + this.fd = null; + this.writable = true; + + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; } - for (var j = 0; j < N.length; j++) { - for (var k = 0; k < post.length; k++) { - var expansion = pre + N[j] + post[k]; - if (!isTop || isSequence || expansion) - expansions.push(expansion); + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); } + + this.pos = this.start; } - } - return expansions; -} + this.busy = false; + this._queue = []; + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } +} /***/ }), -/***/ 84794: +/***/ 20263: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var Buffer = (__nccwpck_require__(14300).Buffer); - -var CRC_TABLE = [ - 0x00000000, 0x77073096, 0xee0e612c, 0x990951ba, 0x076dc419, - 0x706af48f, 0xe963a535, 0x9e6495a3, 0x0edb8832, 0x79dcb8a4, - 0xe0d5e91e, 0x97d2d988, 0x09b64c2b, 0x7eb17cbd, 0xe7b82d07, - 0x90bf1d91, 0x1db71064, 0x6ab020f2, 0xf3b97148, 0x84be41de, - 0x1adad47d, 0x6ddde4eb, 0xf4d4b551, 0x83d385c7, 0x136c9856, - 0x646ba8c0, 0xfd62f97a, 0x8a65c9ec, 0x14015c4f, 0x63066cd9, - 0xfa0f3d63, 0x8d080df5, 0x3b6e20c8, 0x4c69105e, 0xd56041e4, - 0xa2677172, 0x3c03e4d1, 0x4b04d447, 0xd20d85fd, 0xa50ab56b, - 0x35b5a8fa, 0x42b2986c, 0xdbbbc9d6, 0xacbcf940, 0x32d86ce3, - 0x45df5c75, 0xdcd60dcf, 0xabd13d59, 0x26d930ac, 0x51de003a, - 0xc8d75180, 0xbfd06116, 0x21b4f4b5, 0x56b3c423, 0xcfba9599, - 0xb8bda50f, 0x2802b89e, 0x5f058808, 0xc60cd9b2, 0xb10be924, - 0x2f6f7c87, 0x58684c11, 0xc1611dab, 0xb6662d3d, 0x76dc4190, - 0x01db7106, 0x98d220bc, 0xefd5102a, 0x71b18589, 0x06b6b51f, - 0x9fbfe4a5, 0xe8b8d433, 0x7807c9a2, 0x0f00f934, 0x9609a88e, - 0xe10e9818, 0x7f6a0dbb, 0x086d3d2d, 0x91646c97, 0xe6635c01, - 0x6b6b51f4, 0x1c6c6162, 0x856530d8, 0xf262004e, 0x6c0695ed, - 0x1b01a57b, 0x8208f4c1, 0xf50fc457, 0x65b0d9c6, 0x12b7e950, - 0x8bbeb8ea, 0xfcb9887c, 0x62dd1ddf, 0x15da2d49, 0x8cd37cf3, - 0xfbd44c65, 0x4db26158, 0x3ab551ce, 0xa3bc0074, 0xd4bb30e2, - 0x4adfa541, 0x3dd895d7, 0xa4d1c46d, 0xd3d6f4fb, 0x4369e96a, - 0x346ed9fc, 0xad678846, 0xda60b8d0, 0x44042d73, 0x33031de5, - 0xaa0a4c5f, 0xdd0d7cc9, 0x5005713c, 0x270241aa, 0xbe0b1010, - 0xc90c2086, 0x5768b525, 0x206f85b3, 0xb966d409, 0xce61e49f, - 0x5edef90e, 0x29d9c998, 0xb0d09822, 0xc7d7a8b4, 0x59b33d17, - 0x2eb40d81, 0xb7bd5c3b, 0xc0ba6cad, 0xedb88320, 0x9abfb3b6, - 0x03b6e20c, 0x74b1d29a, 0xead54739, 0x9dd277af, 0x04db2615, - 0x73dc1683, 0xe3630b12, 0x94643b84, 0x0d6d6a3e, 0x7a6a5aa8, - 0xe40ecf0b, 0x9309ff9d, 0x0a00ae27, 0x7d079eb1, 0xf00f9344, - 0x8708a3d2, 0x1e01f268, 0x6906c2fe, 0xf762575d, 0x806567cb, - 0x196c3671, 0x6e6b06e7, 0xfed41b76, 0x89d32be0, 0x10da7a5a, - 0x67dd4acc, 0xf9b9df6f, 0x8ebeeff9, 0x17b7be43, 0x60b08ed5, - 0xd6d6a3e8, 0xa1d1937e, 0x38d8c2c4, 0x4fdff252, 0xd1bb67f1, - 0xa6bc5767, 0x3fb506dd, 0x48b2364b, 0xd80d2bda, 0xaf0a1b4c, - 0x36034af6, 0x41047a60, 0xdf60efc3, 0xa867df55, 0x316e8eef, - 0x4669be79, 0xcb61b38c, 0xbc66831a, 0x256fd2a0, 0x5268e236, - 0xcc0c7795, 0xbb0b4703, 0x220216b9, 0x5505262f, 0xc5ba3bbe, - 0xb2bd0b28, 0x2bb45a92, 0x5cb36a04, 0xc2d7ffa7, 0xb5d0cf31, - 0x2cd99e8b, 0x5bdeae1d, 0x9b64c2b0, 0xec63f226, 0x756aa39c, - 0x026d930a, 0x9c0906a9, 0xeb0e363f, 0x72076785, 0x05005713, - 0x95bf4a82, 0xe2b87a14, 0x7bb12bae, 0x0cb61b38, 0x92d28e9b, - 0xe5d5be0d, 0x7cdcefb7, 0x0bdbdf21, 0x86d3d2d4, 0xf1d4e242, - 0x68ddb3f8, 0x1fda836e, 0x81be16cd, 0xf6b9265b, 0x6fb077e1, - 0x18b74777, 0x88085ae6, 0xff0f6a70, 0x66063bca, 0x11010b5c, - 0x8f659eff, 0xf862ae69, 0x616bffd3, 0x166ccf45, 0xa00ae278, - 0xd70dd2ee, 0x4e048354, 0x3903b3c2, 0xa7672661, 0xd06016f7, - 0x4969474d, 0x3e6e77db, 0xaed16a4a, 0xd9d65adc, 0x40df0b66, - 0x37d83bf0, 0xa9bcae53, 0xdebb9ec5, 0x47b2cf7f, 0x30b5ffe9, - 0xbdbdf21c, 0xcabac28a, 0x53b39330, 0x24b4a3a6, 0xbad03605, - 0xcdd70693, 0x54de5729, 0x23d967bf, 0xb3667a2e, 0xc4614ab8, - 0x5d681b02, 0x2a6f2b94, 0xb40bbe37, 0xc30c8ea1, 0x5a05df1b, - 0x2d02ef8d -]; +var constants = __nccwpck_require__(22057) -if (typeof Int32Array !== 'undefined') { - CRC_TABLE = new Int32Array(CRC_TABLE); -} +var origCwd = process.cwd +var cwd = null -function ensureBuffer(input) { - if (Buffer.isBuffer(input)) { - return input; - } +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform - var hasNewBufferAPI = - typeof Buffer.alloc === "function" && - typeof Buffer.from === "function"; +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +try { + process.cwd() +} catch (er) {} - if (typeof input === "number") { - return hasNewBufferAPI ? Buffer.alloc(input) : new Buffer(input); - } - else if (typeof input === "string") { - return hasNewBufferAPI ? Buffer.from(input) : new Buffer(input); - } - else { - throw new Error("input must be buffer, number, or string, received " + - typeof input); +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir = process.chdir + process.chdir = function (d) { + cwd = null + chdir.call(process, d) } + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) } -function bufferizeInt(num) { - var tmp = ensureBuffer(4); - tmp.writeInt32BE(num, 0); - return tmp; -} +module.exports = patch -function _crc32(buf, previous) { - buf = ensureBuffer(buf); - if (Buffer.isBuffer(previous)) { - previous = previous.readUInt32BE(0); +function patch (fs) { + // (re-)implement some things that are known busted or missing. + + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) } - var crc = ~~previous ^ -1; - for (var n = 0; n < buf.length; n++) { - crc = CRC_TABLE[(crc ^ buf[n]) & 0xff] ^ (crc >>> 8); + + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) } - return (crc ^ -1); -} -function crc32() { - return bufferizeInt(_crc32.apply(null, arguments)); -} -crc32.signed = function () { - return _crc32.apply(null, arguments); -}; -crc32.unsigned = function () { - return _crc32.apply(null, arguments) >>> 0; -}; + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. -module.exports = crc32; + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) -/***/ }), + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) -/***/ 51590: -/***/ ((module) => { + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) -module.exports = Buffers; + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) -function Buffers (bufs) { - if (!(this instanceof Buffers)) return new Buffers(bufs); - this.buffers = bufs || []; - this.length = this.buffers.reduce(function (size, buf) { - return size + buf.length - }, 0); -} + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) -Buffers.prototype.push = function () { - for (var i = 0; i < arguments.length; i++) { - if (!Buffer.isBuffer(arguments[i])) { - throw new TypeError('Tried to push a non-buffer'); - } + // if lchmod/lchown do not exist, then make them no-ops + if (fs.chmod && !fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) } - - for (var i = 0; i < arguments.length; i++) { - var buf = arguments[i]; - this.buffers.push(buf); - this.length += buf.length; + fs.lchmodSync = function () {} + } + if (fs.chown && !fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) } - return this.length; -}; + fs.lchownSync = function () {} + } -Buffers.prototype.unshift = function () { - for (var i = 0; i < arguments.length; i++) { - if (!Buffer.isBuffer(arguments[i])) { - throw new TypeError('Tried to unshift a non-buffer'); + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. + + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = typeof fs.rename !== 'function' ? fs.rename + : (function (fs$rename) { + function rename (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) + return rename + })(fs.rename) + } + + // if read() returns EAGAIN, then just try it again. + fs.read = typeof fs.read !== 'function' ? fs.read + : (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) } - - for (var i = 0; i < arguments.length; i++) { - var buf = arguments[i]; - this.buffers.unshift(buf); - this.length += buf.length; - } - return this.length; -}; -Buffers.prototype.copy = function (dst, dStart, start, end) { - return this.slice(start, end).copy(dst, dStart, 0, end - start); -}; + // This ensures `util.promisify` works as it does for native `fs.read`. + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) + return read + })(fs.read) -Buffers.prototype.splice = function (i, howMany) { - var buffers = this.buffers; - var index = i >= 0 ? i : this.length - i; - var reps = [].slice.call(arguments, 2); - - if (howMany === undefined) { - howMany = this.length - index; - } - else if (howMany > this.length - index) { - howMany = this.length - index; - } - - for (var i = 0; i < reps.length; i++) { - this.length += reps[i].length; - } - - var removed = new Buffers(); - var bytes = 0; - - var startBytes = 0; - for ( - var ii = 0; - ii < buffers.length && startBytes + buffers[ii].length < index; - ii ++ - ) { startBytes += buffers[ii].length } - - if (index - startBytes > 0) { - var start = index - startBytes; - - if (start + howMany < buffers[ii].length) { - removed.push(buffers[ii].slice(start, start + howMany)); - - var orig = buffers[ii]; - //var buf = new Buffer(orig.length - howMany); - var buf0 = new Buffer(start); - for (var i = 0; i < start; i++) { - buf0[i] = orig[i]; - } - - var buf1 = new Buffer(orig.length - start - howMany); - for (var i = start + howMany; i < orig.length; i++) { - buf1[ i - howMany - start ] = orig[i] - } - - if (reps.length > 0) { - var reps_ = reps.slice(); - reps_.unshift(buf0); - reps_.push(buf1); - buffers.splice.apply(buffers, [ ii, 1 ].concat(reps_)); - ii += reps_.length; - reps = []; - } - else { - buffers.splice(ii, 1, buf0, buf1); - //buffers[ii] = buf; - ii += 2; - } - } - else { - removed.push(buffers[ii].slice(start)); - buffers[ii] = buffers[ii].slice(0, start); - ii ++; + fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync + : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue } + throw er + } } - - if (reps.length > 0) { - buffers.splice.apply(buffers, [ ii, 0 ].concat(reps)); - ii += reps.length; - } - - while (removed.length < howMany) { - var buf = buffers[ii]; - var len = buf.length; - var take = Math.min(len, howMany - removed.length); - - if (take === len) { - removed.push(buf); - buffers.splice(ii, 1); - } - else { - removed.push(buf.slice(0, take)); - buffers[ii] = buffers[ii].slice(take); + }})(fs.readSync) + + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) } - - this.length -= removed.length; - - return removed; -}; - -Buffers.prototype.slice = function (i, j) { - var buffers = this.buffers; - if (j === undefined) j = this.length; - if (i === undefined) i = 0; - - if (j > this.length) j = this.length; - - var startBytes = 0; - for ( - var si = 0; - si < buffers.length && startBytes + buffers[si].length <= i; - si ++ - ) { startBytes += buffers[si].length } - - var target = new Buffer(j - i); - - var ti = 0; - for (var ii = si; ti < j - i && ii < buffers.length; ii++) { - var len = buffers[ii].length; - - var start = ti === 0 ? i - startBytes : 0; - var end = ti + len >= j - i - ? Math.min(start + (j - i) - ti, len) - : len - ; - - buffers[ii].copy(target, ti, start, end); - ti += end - start; - } - - return target; -}; -Buffers.prototype.pos = function (i) { - if (i < 0 || i >= this.length) throw new Error('oob'); - var l = i, bi = 0, bu = null; - for (;;) { - bu = this.buffers[bi]; - if (l < bu.length) { - return {buf: bi, offset: l}; + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} } else { - l -= bu.length; + fs.closeSync(fd) } - bi++; + } + return ret } -}; - -Buffers.prototype.get = function get (i) { - var pos = this.pos(i); - - return this.buffers[pos.buf].get(pos.offset); -}; + } -Buffers.prototype.set = function set (i, b) { - var pos = this.pos(i); + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } - return this.buffers[pos.buf].set(pos.offset, b); -}; + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } -Buffers.prototype.indexOf = function (needle, offset) { - if ("string" === typeof needle) { - needle = new Buffer(needle); - } else if (needle instanceof Buffer) { - // already a buffer - } else { - throw new Error('Invalid type for a search string'); + } else if (fs.futimes) { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} } + } - if (!needle.length) { - return 0; + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) } + } - if (!this.length) { - return -1; + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } } + } - var i = 0, j = 0, match = 0, mstart, pos = 0; - // start search from a particular point in the virtual buffer - if (offset) { - var p = this.pos(offset); - i = p.buf; - j = p.offset; - pos = offset; + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) } + } - // for each character in virtual buffer - for (;;) { - while (j >= this.buffers[i].length) { - j = 0; - i++; + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } - if (i >= this.buffers.length) { - // search string not found - return -1; - } + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } + } - var char = this.buffers[i][j]; + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + return stats; + } + } - if (char == needle[match]) { - // keep track where match started - if (match == 0) { - mstart = { - i: i, - j: j, - pos: pos - }; - } - match++; - if (match == needle.length) { - // full match - return mstart.pos; - } - } else if (match != 0) { - // a partial match ended, go back to match starting position - // this will continue the search at the next character - i = mstart.i; - j = mstart.j; - pos = mstart.pos; - match = 0; - } + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true - j++; - pos++; - } -}; + if (er.code === "ENOSYS") + return true -Buffers.prototype.toBuffer = function() { - return this.slice(); -} + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } -Buffers.prototype.toString = function(encoding, start, end) { - return this.slice(start, end).toString(encoding); + return false + } } /***/ }), -/***/ 46533: +/***/ 44124: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var Traverse = __nccwpck_require__(8588); -var EventEmitter = (__nccwpck_require__(82361).EventEmitter); - -module.exports = Chainsaw; -function Chainsaw (builder) { - var saw = Chainsaw.saw(builder, {}); - var r = builder.call(saw.handlers, saw); - if (r !== undefined) saw.handlers = r; - saw.record(); - return saw.chain(); -}; +try { + var util = __nccwpck_require__(73837); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __nccwpck_require__(8544); +} -Chainsaw.light = function ChainsawLight (builder) { - var saw = Chainsaw.saw(builder, {}); - var r = builder.call(saw.handlers, saw); - if (r !== undefined) saw.handlers = r; - return saw.chain(); -}; -Chainsaw.saw = function (builder, handlers) { - var saw = new EventEmitter; - saw.handlers = handlers; - saw.actions = []; +/***/ }), - saw.chain = function () { - var ch = Traverse(saw.handlers).map(function (node) { - if (this.isRoot) return node; - var ps = this.path; +/***/ 8544: +/***/ ((module) => { - if (typeof node === 'function') { - this.update(function () { - saw.actions.push({ - path : ps, - args : [].slice.call(arguments) - }); - return ch; - }); - } - }); - - process.nextTick(function () { - saw.emit('begin'); - saw.next(); - }); - - return ch; - }; - - saw.pop = function () { - return saw.actions.shift(); - }; - - saw.next = function () { - var action = saw.pop(); - - if (!action) { - saw.emit('end'); - } - else if (!action.trap) { - var node = saw.handlers; - action.path.forEach(function (key) { node = node[key] }); - node.apply(saw.handlers, action.args); +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true } - }; - - saw.nest = function (cb) { - var args = [].slice.call(arguments, 1); - var autonext = true; + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} - if (typeof cb === 'boolean') { - var autonext = cb; - cb = args.shift(); - } - var s = Chainsaw.saw(builder, {}); - var r = builder.call(s.handlers, s); +/***/ }), - if (r !== undefined) s.handlers = r; +/***/ 63287: +/***/ ((__unused_webpack_module, exports) => { - // If we are recording... - if ("undefined" !== typeof saw.step) { - // ... our children should, too - s.record(); - } +"use strict"; - cb.apply(s.chain(), args); - if (autonext !== false) s.on('end', saw.next); - }; - saw.record = function () { - upgradeChainsaw(saw); - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); - ['trap', 'down', 'jump'].forEach(function (method) { - saw[method] = function () { - throw new Error("To use the trap, down and jump features, please "+ - "call record() first to start recording actions."); - }; - }); +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ - return saw; -}; +function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; +} -function upgradeChainsaw(saw) { - saw.step = 0; +function isPlainObject(o) { + var ctor,prot; - // override pop - saw.pop = function () { - return saw.actions[saw.step++]; - }; + if (isObject(o) === false) return false; - saw.trap = function (name, cb) { - var ps = Array.isArray(name) ? name : [name]; - saw.actions.push({ - path : ps, - step : saw.step, - cb : cb, - trap : true - }); - }; + // If has modified constructor + ctor = o.constructor; + if (ctor === undefined) return true; - saw.down = function (name) { - var ps = (Array.isArray(name) ? name : [name]).join('/'); - var i = saw.actions.slice(saw.step).map(function (x) { - if (x.trap && x.step <= saw.step) return false; - return x.path.join('/') == ps; - }).indexOf(true); + // If has modified prototype + prot = ctor.prototype; + if (isObject(prot) === false) return false; - if (i >= 0) saw.step += i; - else saw.step = saw.actions.length; + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; + } - var act = saw.actions[saw.step - 1]; - if (act && act.trap) { - // It's a trap! - saw.step = act.step; - act.cb(); - } - else saw.next(); - }; + // Most likely a plain Object + return true; +} - saw.jump = function (step) { - saw.step = step; - saw.next(); - }; -}; +exports.isPlainObject = isPlainObject; /***/ }), -/***/ 85443: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 41554: +/***/ ((module) => { -var util = __nccwpck_require__(73837); -var Stream = (__nccwpck_require__(12781).Stream); -var DelayedStream = __nccwpck_require__(18611); +"use strict"; -module.exports = CombinedStream; -function CombinedStream() { - this.writable = false; - this.readable = true; - this.dataSize = 0; - this.maxDataSize = 2 * 1024 * 1024; - this.pauseStreams = true; - this._released = false; - this._streams = []; - this._currentStream = null; - this._insideLoop = false; - this._pendingNext = false; -} -util.inherits(CombinedStream, Stream); +const isStream = stream => + stream !== null && + typeof stream === 'object' && + typeof stream.pipe === 'function'; -CombinedStream.create = function(options) { - var combinedStream = new this(); +isStream.writable = stream => + isStream(stream) && + stream.writable !== false && + typeof stream._write === 'function' && + typeof stream._writableState === 'object'; - options = options || {}; - for (var option in options) { - combinedStream[option] = options[option]; - } +isStream.readable = stream => + isStream(stream) && + stream.readable !== false && + typeof stream._read === 'function' && + typeof stream._readableState === 'object'; - return combinedStream; -}; +isStream.duplex = stream => + isStream.writable(stream) && + isStream.readable(stream); -CombinedStream.isStreamLike = function(stream) { - return (typeof stream !== 'function') - && (typeof stream !== 'string') - && (typeof stream !== 'boolean') - && (typeof stream !== 'number') - && (!Buffer.isBuffer(stream)); -}; +isStream.transform = stream => + isStream.duplex(stream) && + typeof stream._transform === 'function'; -CombinedStream.prototype.append = function(stream) { - var isStreamLike = CombinedStream.isStreamLike(stream); +module.exports = isStream; - if (isStreamLike) { - if (!(stream instanceof DelayedStream)) { - var newStream = DelayedStream.create(stream, { - maxDataSize: Infinity, - pauseStream: this.pauseStreams, - }); - stream.on('data', this._checkDataSize.bind(this)); - stream = newStream; - } - this._handleErrors(stream); +/***/ }), - if (this.pauseStreams) { - stream.pause(); - } - } +/***/ 20893: +/***/ ((module) => { - this._streams.push(stream); - return this; -}; +var toString = {}.toString; -CombinedStream.prototype.pipe = function(dest, options) { - Stream.prototype.pipe.call(this, dest, options); - this.resume(); - return dest; +module.exports = Array.isArray || function (arr) { + return toString.call(arr) == '[object Array]'; }; -CombinedStream.prototype._getNext = function() { - this._currentStream = null; - if (this._insideLoop) { - this._pendingNext = true; - return; // defer call - } +/***/ }), - this._insideLoop = true; - try { - do { - this._pendingNext = false; - this._realGetNext(); - } while (this._pendingNext); - } finally { - this._insideLoop = false; - } -}; +/***/ 84329: +/***/ ((module) => { -CombinedStream.prototype._realGetNext = function() { - var stream = this._streams.shift(); +"use strict"; +function e(e){this.message=e}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var r="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(r){var t=String(r).replace(/=+$/,"");if(t.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,o,a=0,i=0,c="";o=t.charAt(i++);~o&&(n=a%4?64*n+o:o,a++%4)?c+=String.fromCharCode(255&n>>(-2*a&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return c};function t(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(r(e).replace(/(.)/g,(function(e,r){var t=r.charCodeAt(0).toString(16).toUpperCase();return t.length<2&&(t="0"+t),"%"+t})))}(t)}catch(e){return r(t)}}function n(e){this.message=e}function o(e,r){if("string"!=typeof e)throw new n("Invalid token specified");var o=!0===(r=r||{}).header?0:1;try{return JSON.parse(t(e.split(".")[o]))}catch(e){throw new n("Invalid token specified: "+e.message)}}n.prototype=new Error,n.prototype.name="InvalidTokenError";const a=o;a.default=o,a.InvalidTokenError=n,module.exports=a; +//# sourceMappingURL=jwt-decode.cjs.js.map - if (typeof stream == 'undefined') { - this.end(); - return; - } +/***/ }), - if (typeof stream !== 'function') { - this._pipeNext(stream); - return; - } +/***/ 12084: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var getStream = stream; - getStream(function(stream) { - var isStreamLike = CombinedStream.isStreamLike(stream); - if (isStreamLike) { - stream.on('data', this._checkDataSize.bind(this)); - this._handleErrors(stream); - } +var util = __nccwpck_require__(73837); +var PassThrough = __nccwpck_require__(27818); - this._pipeNext(stream); - }.bind(this)); +module.exports = { + Readable: Readable, + Writable: Writable }; -CombinedStream.prototype._pipeNext = function(stream) { - this._currentStream = stream; +util.inherits(Readable, PassThrough); +util.inherits(Writable, PassThrough); - var isStreamLike = CombinedStream.isStreamLike(stream); - if (isStreamLike) { - stream.on('end', this._getNext.bind(this)); - stream.pipe(this, {end: false}); - return; - } +// Patch the given method of instance so that the callback +// is executed once, before the actual method is called the +// first time. +function beforeFirstCall(instance, method, callback) { + instance[method] = function() { + delete instance[method]; + callback.apply(this, arguments); + return this[method].apply(this, arguments); + }; +} - var value = stream; - this.write(value); - this._getNext(); -}; +function Readable(fn, options) { + if (!(this instanceof Readable)) + return new Readable(fn, options); -CombinedStream.prototype._handleErrors = function(stream) { - var self = this; - stream.on('error', function(err) { - self._emitError(err); + PassThrough.call(this, options); + + beforeFirstCall(this, '_read', function() { + var source = fn.call(this, options); + var emit = this.emit.bind(this, 'error'); + source.on('error', emit); + source.pipe(this); }); -}; -CombinedStream.prototype.write = function(data) { - this.emit('data', data); -}; + this.emit('readable'); +} -CombinedStream.prototype.pause = function() { - if (!this.pauseStreams) { - return; - } +function Writable(fn, options) { + if (!(this instanceof Writable)) + return new Writable(fn, options); - if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); - this.emit('pause'); -}; + PassThrough.call(this, options); -CombinedStream.prototype.resume = function() { - if (!this._released) { - this._released = true; - this.writable = true; - this._getNext(); - } + beforeFirstCall(this, '_write', function() { + var destination = fn.call(this, options); + var emit = this.emit.bind(this, 'error'); + destination.on('error', emit); + this.pipe(destination); + }); - if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); - this.emit('resume'); -}; + this.emit('writable'); +} -CombinedStream.prototype.end = function() { - this._reset(); - this.emit('end'); -}; -CombinedStream.prototype.destroy = function() { - this._reset(); - this.emit('close'); -}; -CombinedStream.prototype._reset = function() { - this.writable = false; - this._streams = []; - this._currentStream = null; -}; +/***/ }), -CombinedStream.prototype._checkDataSize = function() { - this._updateDataSize(); - if (this.dataSize <= this.maxDataSize) { - return; - } +/***/ 5706: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; - this._emitError(new Error(message)); -}; +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -CombinedStream.prototype._updateDataSize = function() { - this.dataSize = 0; +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototypal inheritance, this class +// prototypally inherits from Readable, and then parasitically from +// Writable. - var self = this; - this._streams.forEach(function(stream) { - if (!stream.dataSize) { - return; - } - self.dataSize += stream.dataSize; - }); - if (this._currentStream && this._currentStream.dataSize) { - this.dataSize += this._currentStream.dataSize; - } -}; +/**/ -CombinedStream.prototype._emitError = function(err) { - this._reset(); - this.emit('error', err); -}; +var pna = __nccwpck_require__(47810); +/**/ +/**/ +var objectKeys = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + keys.push(key); + }return keys; +}; +/**/ -/***/ }), +module.exports = Duplex; -/***/ 92240: -/***/ ((module) => { +/**/ +var util = Object.create(__nccwpck_require__(95898)); +util.inherits = __nccwpck_require__(44124); +/**/ -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var ArchiveEntry = module.exports = function() {}; +var Readable = __nccwpck_require__(99140); +var Writable = __nccwpck_require__(14960); -ArchiveEntry.prototype.getName = function() {}; +util.inherits(Duplex, Readable); -ArchiveEntry.prototype.getSize = function() {}; +{ + // avoid scope creep, the keys array can then be collected + var keys = objectKeys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } +} -ArchiveEntry.prototype.getLastModifiedDate = function() {}; +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options); -ArchiveEntry.prototype.isDirectory = function() {}; + Readable.call(this, options); + Writable.call(this, options); -/***/ }), + if (options && options.readable === false) this.readable = false; -/***/ 36728: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (options && options.writable === false) this.writable = false; -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var inherits = (__nccwpck_require__(73837).inherits); -var Transform = (__nccwpck_require__(51642).Transform); + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; -var ArchiveEntry = __nccwpck_require__(92240); -var util = __nccwpck_require__(95208); + this.once('end', onend); +} -var ArchiveOutputStream = module.exports = function(options) { - if (!(this instanceof ArchiveOutputStream)) { - return new ArchiveOutputStream(options); +Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; } +}); - Transform.call(this, options); - - this.offset = 0; - this._archive = { - finish: false, - finished: false, - processing: false - }; -}; +// the no-half-open enforcer +function onend() { + // if we allow half-open state, or if the writable side ended, + // then we're ok. + if (this.allowHalfOpen || this._writableState.ended) return; -inherits(ArchiveOutputStream, Transform); + // no more data can be written. + // But allow more writes to happen in this tick. + pna.nextTick(onEndNT, this); +} -ArchiveOutputStream.prototype._appendBuffer = function(zae, source, callback) { - // scaffold only -}; +function onEndNT(self) { + self.end(); +} -ArchiveOutputStream.prototype._appendStream = function(zae, source, callback) { - // scaffold only -}; +Object.defineProperty(Duplex.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined || this._writableState === undefined) { + return false; + } + return this._readableState.destroyed && this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (this._readableState === undefined || this._writableState === undefined) { + return; + } -ArchiveOutputStream.prototype._emitErrorCallback = function(err) { - if (err) { - this.emit('error', err); + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + this._writableState.destroyed = value; } -}; - -ArchiveOutputStream.prototype._finish = function(ae) { - // scaffold only -}; +}); -ArchiveOutputStream.prototype._normalizeEntry = function(ae) { - // scaffold only -}; +Duplex.prototype._destroy = function (err, cb) { + this.push(null); + this.end(); -ArchiveOutputStream.prototype._transform = function(chunk, encoding, callback) { - callback(null, chunk); + pna.nextTick(cb, err); }; -ArchiveOutputStream.prototype.entry = function(ae, source, callback) { - source = source || null; - - if (typeof callback !== 'function') { - callback = this._emitErrorCallback.bind(this); - } +/***/ }), - if (!(ae instanceof ArchiveEntry)) { - callback(new Error('not a valid instance of ArchiveEntry')); - return; - } +/***/ 70982: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this._archive.finish || this._archive.finished) { - callback(new Error('unacceptable entry after finish')); - return; - } +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - if (this._archive.processing) { - callback(new Error('already processing an entry')); - return; - } +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. - this._archive.processing = true; - this._normalizeEntry(ae); - this._entry = ae; - source = util.normalizeInputSource(source); - if (Buffer.isBuffer(source)) { - this._appendBuffer(ae, source, callback); - } else if (util.isStream(source)) { - this._appendStream(ae, source, callback); - } else { - this._archive.processing = false; - callback(new Error('input source must be valid Stream or Buffer instance')); - return; - } +module.exports = PassThrough; - return this; -}; +var Transform = __nccwpck_require__(75072); -ArchiveOutputStream.prototype.finish = function() { - if (this._archive.processing) { - this._archive.finish = true; - return; - } +/**/ +var util = Object.create(__nccwpck_require__(95898)); +util.inherits = __nccwpck_require__(44124); +/**/ - this._finish(); -}; +util.inherits(PassThrough, Transform); -ArchiveOutputStream.prototype.getBytesWritten = function() { - return this.offset; -}; +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options); -ArchiveOutputStream.prototype.write = function(chunk, cb) { - if (chunk) { - this.offset += chunk.length; - } + Transform.call(this, options); +} - return Transform.prototype.write.call(this, chunk, cb); +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); }; /***/ }), -/***/ 11704: -/***/ ((module) => { - -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -module.exports = { - WORD: 4, - DWORD: 8, - EMPTY: Buffer.alloc(0), +/***/ 99140: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - SHORT: 2, - SHORT_MASK: 0xffff, - SHORT_SHIFT: 16, - SHORT_ZERO: Buffer.from(Array(2)), - LONG: 4, - LONG_ZERO: Buffer.from(Array(4)), +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - MIN_VERSION_INITIAL: 10, - MIN_VERSION_DATA_DESCRIPTOR: 20, - MIN_VERSION_ZIP64: 45, - VERSION_MADEBY: 45, - METHOD_STORED: 0, - METHOD_DEFLATED: 8, - PLATFORM_UNIX: 3, - PLATFORM_FAT: 0, +/**/ - SIG_LFH: 0x04034b50, - SIG_DD: 0x08074b50, - SIG_CFH: 0x02014b50, - SIG_EOCD: 0x06054b50, - SIG_ZIP64_EOCD: 0x06064B50, - SIG_ZIP64_EOCD_LOC: 0x07064B50, +var pna = __nccwpck_require__(47810); +/**/ - ZIP64_MAGIC_SHORT: 0xffff, - ZIP64_MAGIC: 0xffffffff, - ZIP64_EXTRA_ID: 0x0001, +module.exports = Readable; - ZLIB_NO_COMPRESSION: 0, - ZLIB_BEST_SPEED: 1, - ZLIB_BEST_COMPRESSION: 9, - ZLIB_DEFAULT_COMPRESSION: -1, +/**/ +var isArray = __nccwpck_require__(20893); +/**/ - MODE_MASK: 0xFFF, - DEFAULT_FILE_MODE: 33188, // 010644 = -rw-r--r-- = S_IFREG | S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH - DEFAULT_DIR_MODE: 16877, // 040755 = drwxr-xr-x = S_IFDIR | S_IRWXU | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH +/**/ +var Duplex; +/**/ - EXT_FILE_ATTR_DIR: 1106051088, // 010173200020 = drwxr-xr-x = (((S_IFDIR | 0755) << 16) | S_DOS_D) - EXT_FILE_ATTR_FILE: 2175008800, // 020151000040 = -rw-r--r-- = (((S_IFREG | 0644) << 16) | S_DOS_A) >>> 0 +Readable.ReadableState = ReadableState; - // Unix file types - S_IFMT: 61440, // 0170000 type of file mask - S_IFIFO: 4096, // 010000 named pipe (fifo) - S_IFCHR: 8192, // 020000 character special - S_IFDIR: 16384, // 040000 directory - S_IFBLK: 24576, // 060000 block special - S_IFREG: 32768, // 0100000 regular - S_IFLNK: 40960, // 0120000 symbolic link - S_IFSOCK: 49152, // 0140000 socket +/**/ +var EE = (__nccwpck_require__(82361).EventEmitter); - // DOS file type flags - S_DOS_A: 32, // 040 Archive - S_DOS_D: 16, // 020 Directory - S_DOS_V: 8, // 010 Volume - S_DOS_S: 4, // 04 System - S_DOS_H: 2, // 02 Hidden - S_DOS_R: 1 // 01 Read Only +var EElistenerCount = function (emitter, type) { + return emitter.listeners(type).length; }; +/**/ +/**/ +var Stream = __nccwpck_require__(58745); +/**/ -/***/ }), +/**/ -/***/ 63229: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var Buffer = (__nccwpck_require__(15054).Buffer); +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var zipUtil = __nccwpck_require__(68682); +/**/ -var DATA_DESCRIPTOR_FLAG = 1 << 3; -var ENCRYPTION_FLAG = 1 << 0; -var NUMBER_OF_SHANNON_FANO_TREES_FLAG = 1 << 2; -var SLIDING_DICTIONARY_SIZE_FLAG = 1 << 1; -var STRONG_ENCRYPTION_FLAG = 1 << 6; -var UFT8_NAMES_FLAG = 1 << 11; +/**/ +var util = Object.create(__nccwpck_require__(95898)); +util.inherits = __nccwpck_require__(44124); +/**/ -var GeneralPurposeBit = module.exports = function() { - if (!(this instanceof GeneralPurposeBit)) { - return new GeneralPurposeBit(); - } +/**/ +var debugUtil = __nccwpck_require__(73837); +var debug = void 0; +if (debugUtil && debugUtil.debuglog) { + debug = debugUtil.debuglog('stream'); +} else { + debug = function () {}; +} +/**/ - this.descriptor = false; - this.encryption = false; - this.utf8 = false; - this.numberOfShannonFanoTrees = 0; - this.strongEncryption = false; - this.slidingDictionarySize = 0; +var BufferList = __nccwpck_require__(75454); +var destroyImpl = __nccwpck_require__(78999); +var StringDecoder; - return this; -}; +util.inherits(Readable, Stream); -GeneralPurposeBit.prototype.encode = function() { - return zipUtil.getShortBytes( - (this.descriptor ? DATA_DESCRIPTOR_FLAG : 0) | - (this.utf8 ? UFT8_NAMES_FLAG : 0) | - (this.encryption ? ENCRYPTION_FLAG : 0) | - (this.strongEncryption ? STRONG_ENCRYPTION_FLAG : 0) - ); -}; +var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; -GeneralPurposeBit.prototype.parse = function(buf, offset) { - var flag = zipUtil.getShortBytesValue(buf, offset); - var gbp = new GeneralPurposeBit(); +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); - gbp.useDataDescriptor((flag & DATA_DESCRIPTOR_FLAG) !== 0); - gbp.useUTF8ForNames((flag & UFT8_NAMES_FLAG) !== 0); - gbp.useStrongEncryption((flag & STRONG_ENCRYPTION_FLAG) !== 0); - gbp.useEncryption((flag & ENCRYPTION_FLAG) !== 0); - gbp.setSlidingDictionarySize((flag & SLIDING_DICTIONARY_SIZE_FLAG) !== 0 ? 8192 : 4096); - gbp.setNumberOfShannonFanoTrees((flag & NUMBER_OF_SHANNON_FANO_TREES_FLAG) !== 0 ? 3 : 2); + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; +} - return gbp; -}; +function ReadableState(options, stream) { + Duplex = Duplex || __nccwpck_require__(5706); -GeneralPurposeBit.prototype.setNumberOfShannonFanoTrees = function(n) { - this.numberOfShannonFanoTrees = n; -}; + options = options || {}; -GeneralPurposeBit.prototype.getNumberOfShannonFanoTrees = function() { - return this.numberOfShannonFanoTrees; -}; + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; -GeneralPurposeBit.prototype.setSlidingDictionarySize = function(n) { - this.slidingDictionarySize = n; -}; + // object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away + this.objectMode = !!options.objectMode; -GeneralPurposeBit.prototype.getSlidingDictionarySize = function() { - return this.slidingDictionarySize; -}; + if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; -GeneralPurposeBit.prototype.useDataDescriptor = function(b) { - this.descriptor = b; -}; + // the point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + var hwm = options.highWaterMark; + var readableHwm = options.readableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; -GeneralPurposeBit.prototype.usesDataDescriptor = function() { - return this.descriptor; -}; + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; -GeneralPurposeBit.prototype.useEncryption = function(b) { - this.encryption = b; -}; + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); -GeneralPurposeBit.prototype.usesEncryption = function() { - return this.encryption; -}; + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift() + this.buffer = new BufferList(); + this.length = 0; + this.pipes = null; + this.pipesCount = 0; + this.flowing = null; + this.ended = false; + this.endEmitted = false; + this.reading = false; -GeneralPurposeBit.prototype.useStrongEncryption = function(b) { - this.strongEncryption = b; -}; + // a flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + this.sync = true; -GeneralPurposeBit.prototype.usesStrongEncryption = function() { - return this.strongEncryption; -}; + // whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + this.needReadable = false; + this.emittedReadable = false; + this.readableListening = false; + this.resumeScheduled = false; -GeneralPurposeBit.prototype.useUTF8ForNames = function(b) { - this.utf8 = b; -}; + // has it been destroyed + this.destroyed = false; -GeneralPurposeBit.prototype.usesUTF8ForNames = function() { - return this.utf8; -}; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; -/***/ }), + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; -/***/ 70713: -/***/ ((module) => { + // if true, a maybeReadMore has been scheduled + this.readingMore = false; -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -module.exports = { - /** - * Bits used for permissions (and sticky bit) - */ - PERM_MASK: 4095, // 07777 + this.decoder = null; + this.encoding = null; + if (options.encoding) { + if (!StringDecoder) StringDecoder = (__nccwpck_require__(24749)/* .StringDecoder */ .s); + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } +} - /** - * Bits used to indicate the filesystem object type. - */ - FILE_TYPE_FLAG: 61440, // 0170000 +function Readable(options) { + Duplex = Duplex || __nccwpck_require__(5706); - /** - * Indicates symbolic links. - */ - LINK_FLAG: 40960, // 0120000 + if (!(this instanceof Readable)) return new Readable(options); - /** - * Indicates plain files. - */ - FILE_FLAG: 32768, // 0100000 + this._readableState = new ReadableState(options, this); - /** - * Indicates directories. - */ - DIR_FLAG: 16384, // 040000 + // legacy + this.readable = true; - // ---------------------------------------------------------- - // somewhat arbitrary choices that are quite common for shared - // installations - // ----------------------------------------------------------- + if (options) { + if (typeof options.read === 'function') this._read = options.read; - /** - * Default permissions for symbolic links. - */ - DEFAULT_LINK_PERM: 511, // 0777 + if (typeof options.destroy === 'function') this._destroy = options.destroy; + } - /** - * Default permissions for directories. - */ - DEFAULT_DIR_PERM: 493, // 0755 + Stream.call(this); +} - /** - * Default permissions for plain files. - */ - DEFAULT_FILE_PERM: 420 // 0644 -}; +Object.defineProperty(Readable.prototype, 'destroyed', { + get: function () { + if (this._readableState === undefined) { + return false; + } + return this._readableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._readableState) { + return; + } -/***/ }), + // backward compatibility, the user is explicitly + // managing destroyed + this._readableState.destroyed = value; + } +}); -/***/ 68682: -/***/ ((module) => { +Readable.prototype.destroy = destroyImpl.destroy; +Readable.prototype._undestroy = destroyImpl.undestroy; +Readable.prototype._destroy = function (err, cb) { + this.push(null); + cb(err); +}; -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var util = module.exports = {}; +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + var state = this._readableState; + var skipChunkCheck; -util.dateToDos = function(d, forceLocalTime) { - forceLocalTime = forceLocalTime || false; - - var year = forceLocalTime ? d.getFullYear() : d.getUTCFullYear(); - - if (year < 1980) { - return 2162688; // 1980-1-1 00:00:00 - } else if (year >= 2044) { - return 2141175677; // 2043-12-31 23:59:58 + if (!state.objectMode) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + skipChunkCheck = true; + } + } else { + skipChunkCheck = true; } - var val = { - year: year, - month: forceLocalTime ? d.getMonth() : d.getUTCMonth(), - date: forceLocalTime ? d.getDate() : d.getUTCDate(), - hours: forceLocalTime ? d.getHours() : d.getUTCHours(), - minutes: forceLocalTime ? d.getMinutes() : d.getUTCMinutes(), - seconds: forceLocalTime ? d.getSeconds() : d.getUTCSeconds() - }; - - return ((val.year - 1980) << 25) | ((val.month + 1) << 21) | (val.date << 16) | - (val.hours << 11) | (val.minutes << 5) | (val.seconds / 2); + return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; -util.dosToDate = function(dos) { - return new Date(((dos >> 25) & 0x7f) + 1980, ((dos >> 21) & 0x0f) - 1, (dos >> 16) & 0x1f, (dos >> 11) & 0x1f, (dos >> 5) & 0x3f, (dos & 0x1f) << 1); +// Unshift should *always* be something directly out of read() +Readable.prototype.unshift = function (chunk) { + return readableAddChunk(this, chunk, null, true, false); }; -util.fromDosTime = function(buf) { - return util.dosToDate(buf.readUInt32LE(0)); -}; +function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { + var state = stream._readableState; + if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else { + var er; + if (!skipChunkCheck) er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { + chunk = _uint8ArrayToBuffer(chunk); + } -util.getEightBytes = function(v) { - var buf = Buffer.alloc(8); - buf.writeUInt32LE(v % 0x0100000000, 0); - buf.writeUInt32LE((v / 0x0100000000) | 0, 4); + if (addToFront) { + if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); + } else if (state.ended) { + stream.emit('error', new Error('stream.push() after EOF')); + } else { + state.reading = false; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.reading = false; + } + } - return buf; -}; + return needMoreData(state); +} -util.getShortBytes = function(v) { - var buf = Buffer.alloc(2); - buf.writeUInt16LE((v & 0xFFFF) >>> 0, 0); +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync) { + stream.emit('data', chunk); + stream.read(0); + } else { + // update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); - return buf; -}; + if (state.needReadable) emitReadable(stream); + } + maybeReadMore(stream, state); +} -util.getShortBytesValue = function(buf, offset) { - return buf.readUInt16LE(offset); -}; +function chunkInvalid(state, chunk) { + var er; + if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; +} -util.getLongBytes = function(v) { - var buf = Buffer.alloc(4); - buf.writeUInt32LE((v & 0xFFFFFFFF) >>> 0, 0); +// if it's past the high water mark, we can push in some more. +// Also, if we have no data yet, we can stand some +// more bytes. This is to work around cases where hwm=0, +// such as the repl. Also, if the push() triggered a +// readable event, and the user called read(largeNumber) such that +// needReadable was set, then we ought to push more, so that another +// 'readable' event will be triggered. +function needMoreData(state) { + return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); +} - return buf; +Readable.prototype.isPaused = function () { + return this._readableState.flowing === false; }; -util.getLongBytesValue = function(buf, offset) { - return buf.readUInt32LE(offset); +// backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + if (!StringDecoder) StringDecoder = (__nccwpck_require__(24749)/* .StringDecoder */ .s); + this._readableState.decoder = new StringDecoder(enc); + this._readableState.encoding = enc; + return this; }; -util.toDosTime = function(d) { - return util.getLongBytes(util.dateToDos(d)); -}; +// Don't raise the hwm > 8MB +var MAX_HWM = 0x800000; +function computeNewHighWaterMark(n) { + if (n >= MAX_HWM) { + n = MAX_HWM; + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n; +} -/***/ }), +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || state.length === 0 && state.ended) return 0; + if (state.objectMode) return 1; + if (n !== n) { + // Only flow one buffer at a time + if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; + } + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n <= state.length) return n; + // Don't have enough + if (!state.ended) { + state.needReadable = true; + return 0; + } + return state.length; +} -/***/ 3179: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// you can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var inherits = (__nccwpck_require__(73837).inherits); -var normalizePath = __nccwpck_require__(55388); + if (n !== 0) state.emittedReadable = false; -var ArchiveEntry = __nccwpck_require__(92240); -var GeneralPurposeBit = __nccwpck_require__(63229); -var UnixStat = __nccwpck_require__(70713); + // if we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); + return null; + } -var constants = __nccwpck_require__(11704); -var zipUtil = __nccwpck_require__(68682); + n = howMuchToRead(n, state); -var ZipArchiveEntry = module.exports = function(name) { - if (!(this instanceof ZipArchiveEntry)) { - return new ZipArchiveEntry(name); + // if we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null; } - ArchiveEntry.call(this); + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. - this.platform = constants.PLATFORM_FAT; - this.method = -1; + // if we need a readable event, then we need to do some reading. + var doRead = state.needReadable; + debug('need readable', doRead); - this.name = null; - this.size = 0; - this.csize = 0; - this.gpb = new GeneralPurposeBit(); - this.crc = 0; - this.time = -1; + // if we currently have less than the highWaterMark, then also read some + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } - this.minver = constants.MIN_VERSION_INITIAL; - this.mode = -1; - this.extra = null; - this.exattr = 0; - this.inattr = 0; - this.comment = null; + // however, if we've ended, then there's no point, and if we're already + // reading, then it's unnecessary. + if (state.ended || state.reading) { + doRead = false; + debug('reading or ended', doRead); + } else if (doRead) { + debug('do read'); + state.reading = true; + state.sync = true; + // if the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.needReadable = true; + // call internal read method + this._read(state.highWaterMark); + state.sync = false; + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } - if (name) { - this.setName(name); + var ret; + if (n > 0) ret = fromList(n, state);else ret = null; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; } -}; -inherits(ZipArchiveEntry, ArchiveEntry); + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; -/** - * Returns the extra fields related to the entry. - * - * @returns {Buffer} - */ -ZipArchiveEntry.prototype.getCentralDirectoryExtra = function() { - return this.getExtra(); -}; + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } -/** - * Returns the comment set for the entry. - * - * @returns {string} - */ -ZipArchiveEntry.prototype.getComment = function() { - return this.comment !== null ? this.comment : ''; -}; + if (ret !== null) this.emit('data', ret); -/** - * Returns the compressed size of the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getCompressedSize = function() { - return this.csize; + return ret; }; -/** - * Returns the CRC32 digest for the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getCrc = function() { - return this.crc; -}; +function onEofChunk(stream, state) { + if (state.ended) return; + if (state.decoder) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; -/** - * Returns the external file attributes for the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getExternalAttributes = function() { - return this.exattr; -}; + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); +} -/** - * Returns the extra fields related to the entry. - * - * @returns {Buffer} - */ -ZipArchiveEntry.prototype.getExtra = function() { - return this.extra !== null ? this.extra : constants.EMPTY; -}; +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + var state = stream._readableState; + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); + } +} -/** - * Returns the general purpose bits related to the entry. - * - * @returns {GeneralPurposeBit} - */ -ZipArchiveEntry.prototype.getGeneralPurposeBit = function() { - return this.gpb; -}; +function emitReadable_(stream) { + debug('emit readable'); + stream.emit('readable'); + flow(stream); +} -/** - * Returns the internal file attributes for the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getInternalAttributes = function() { - return this.inattr; -}; +// at this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore) { + state.readingMore = true; + pna.nextTick(maybeReadMore_, stream, state); + } +} -/** - * Returns the last modified date of the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getLastModifiedDate = function() { - return this.getTime(); -}; +function maybeReadMore_(stream, state) { + var len = state.length; + while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // didn't get any data, stop spinning. + break;else len = state.length; + } + state.readingMore = false; +} -/** - * Returns the extra fields related to the entry. - * - * @returns {Buffer} - */ -ZipArchiveEntry.prototype.getLocalFileDataExtra = function() { - return this.getExtra(); +// abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + this.emit('error', new Error('_read() is not implemented')); }; -/** - * Returns the compression method used on the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getMethod = function() { - return this.method; -}; +Readable.prototype.pipe = function (dest, pipeOpts) { + var src = this; + var state = this._readableState; -/** - * Returns the filename of the entry. - * - * @returns {string} - */ -ZipArchiveEntry.prototype.getName = function() { - return this.name; -}; + switch (state.pipesCount) { + case 0: + state.pipes = dest; + break; + case 1: + state.pipes = [state.pipes, dest]; + break; + default: + state.pipes.push(dest); + break; + } + state.pipesCount += 1; + debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); -/** - * Returns the platform on which the entry was made. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getPlatform = function() { - return this.platform; -}; + var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; -/** - * Returns the size of the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getSize = function() { - return this.size; -}; + var endFn = doEnd ? onend : unpipe; + if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); -/** - * Returns a date object representing the last modified date of the entry. - * - * @returns {number|Date} - */ -ZipArchiveEntry.prototype.getTime = function() { - return this.time !== -1 ? zipUtil.dosToDate(this.time) : -1; -}; + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } -/** - * Returns the DOS timestamp for the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getTimeDos = function() { - return this.time !== -1 ? this.time : 0; -}; + function onend() { + debug('onend'); + dest.end(); + } -/** - * Returns the UNIX file permissions for the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getUnixMode = function() { - return this.platform !== constants.PLATFORM_UNIX ? 0 : ((this.getExternalAttributes() >> constants.SHORT_SHIFT) & constants.SHORT_MASK); -}; + // when the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + var ondrain = pipeOnDrain(src); + dest.on('drain', ondrain); -/** - * Returns the version of ZIP needed to extract the entry. - * - * @returns {number} - */ -ZipArchiveEntry.prototype.getVersionNeededToExtract = function() { - return this.minver; -}; + var cleanedUp = false; + function cleanup() { + debug('cleanup'); + // cleanup event handlers once the pipe is broken + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + dest.removeListener('drain', ondrain); + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); -/** - * Sets the comment of the entry. - * - * @param comment - */ -ZipArchiveEntry.prototype.setComment = function(comment) { - if (Buffer.byteLength(comment) !== comment.length) { - this.getGeneralPurposeBit().useUTF8ForNames(true); + cleanedUp = true; + + // if the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } - this.comment = comment; -}; + // If the user pushes more data while we're writing to dest then we'll end up + // in ondata again. However, we only want to increase awaitDrain once because + // dest will only emit one 'drain' event for the multiple writes. + // => Introduce a guard on increasing awaitDrain. + var increasedAwaitDrain = false; + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + increasedAwaitDrain = false; + var ret = dest.write(chunk); + if (false === ret && !increasedAwaitDrain) { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { + debug('false write response, pause', state.awaitDrain); + state.awaitDrain++; + increasedAwaitDrain = true; + } + src.pause(); + } + } -/** - * Sets the compressed size of the entry. - * - * @param size - */ -ZipArchiveEntry.prototype.setCompressedSize = function(size) { - if (size < 0) { - throw new Error('invalid entry compressed size'); + // if the dest has an error, then stop piping into it. + // however, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); } - this.csize = size; -}; + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); -/** - * Sets the checksum of the entry. - * - * @param crc - */ -ZipArchiveEntry.prototype.setCrc = function(crc) { - if (crc < 0) { - throw new Error('invalid entry crc32'); + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); - this.crc = crc; -}; - -/** - * Sets the external file attributes of the entry. - * - * @param attr - */ -ZipArchiveEntry.prototype.setExternalAttributes = function(attr) { - this.exattr = attr >>> 0; -}; + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } -/** - * Sets the extra fields related to the entry. - * - * @param extra - */ -ZipArchiveEntry.prototype.setExtra = function(extra) { - this.extra = extra; -}; + // tell the dest that it's being piped to + dest.emit('pipe', src); -/** - * Sets the general purpose bits related to the entry. - * - * @param gpb - */ -ZipArchiveEntry.prototype.setGeneralPurposeBit = function(gpb) { - if (!(gpb instanceof GeneralPurposeBit)) { - throw new Error('invalid entry GeneralPurposeBit'); + // start the flow if it hasn't been started already. + if (!state.flowing) { + debug('pipe resume'); + src.resume(); } - this.gpb = gpb; + return dest; }; -/** - * Sets the internal file attributes of the entry. - * - * @param attr - */ -ZipArchiveEntry.prototype.setInternalAttributes = function(attr) { - this.inattr = attr; -}; +function pipeOnDrain(src) { + return function () { + var state = src._readableState; + debug('pipeOnDrain', state.awaitDrain); + if (state.awaitDrain) state.awaitDrain--; + if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { + state.flowing = true; + flow(src); + } + }; +} -/** - * Sets the compression method of the entry. - * - * @param method - */ -ZipArchiveEntry.prototype.setMethod = function(method) { - if (method < 0) { - throw new Error('invalid entry compression method'); - } +Readable.prototype.unpipe = function (dest) { + var state = this._readableState; + var unpipeInfo = { hasUnpiped: false }; - this.method = method; -}; + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; -/** - * Sets the name of the entry. - * - * @param name - * @param prependSlash - */ -ZipArchiveEntry.prototype.setName = function(name, prependSlash = false) { - name = normalizePath(name, false) - .replace(/^\w+:/, '') - .replace(/^(\.\.\/|\/)+/, ''); + // just one destination. most common case. + if (state.pipesCount === 1) { + // passed in one, but it's not the right one. + if (dest && dest !== state.pipes) return this; - if (prependSlash) { - name = `/${name}`; - } + if (!dest) dest = state.pipes; - if (Buffer.byteLength(name) !== name.length) { - this.getGeneralPurposeBit().useUTF8ForNames(true); + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this, unpipeInfo); + return this; } - this.name = name; -}; + // slow case. multiple pipe destinations. -/** - * Sets the platform on which the entry was made. - * - * @param platform - */ -ZipArchiveEntry.prototype.setPlatform = function(platform) { - this.platform = platform; -}; + if (!dest) { + // remove all. + var dests = state.pipes; + var len = state.pipesCount; + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; -/** - * Sets the size of the entry. - * - * @param size - */ -ZipArchiveEntry.prototype.setSize = function(size) { - if (size < 0) { - throw new Error('invalid entry size'); + for (var i = 0; i < len; i++) { + dests[i].emit('unpipe', this, { hasUnpiped: false }); + }return this; } - this.size = size; -}; + // try to find the right one. + var index = indexOf(state.pipes, dest); + if (index === -1) return this; -/** - * Sets the time of the entry. - * - * @param time - * @param forceLocalTime - */ -ZipArchiveEntry.prototype.setTime = function(time, forceLocalTime) { - if (!(time instanceof Date)) { - throw new Error('invalid entry time'); - } + state.pipes.splice(index, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; - this.time = zipUtil.dateToDos(time, forceLocalTime); -}; + dest.emit('unpipe', this, unpipeInfo); -/** - * Sets the UNIX file permissions for the entry. - * - * @param mode - */ -ZipArchiveEntry.prototype.setUnixMode = function(mode) { - mode |= this.isDirectory() ? constants.S_IFDIR : constants.S_IFREG; + return this; +}; - var extattr = 0; - extattr |= (mode << constants.SHORT_SHIFT) | (this.isDirectory() ? constants.S_DOS_D : constants.S_DOS_A); +// set up data events if they are asked for +// Ensure readable listeners eventually get something +Readable.prototype.on = function (ev, fn) { + var res = Stream.prototype.on.call(this, ev, fn); - this.setExternalAttributes(extattr); - this.mode = mode & constants.MODE_MASK; - this.platform = constants.PLATFORM_UNIX; -}; + if (ev === 'data') { + // Start flowing on next tick if stream isn't explicitly paused + if (this._readableState.flowing !== false) this.resume(); + } else if (ev === 'readable') { + var state = this._readableState; + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.emittedReadable = false; + if (!state.reading) { + pna.nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } -/** - * Sets the version of ZIP needed to extract this entry. - * - * @param minver - */ -ZipArchiveEntry.prototype.setVersionNeededToExtract = function(minver) { - this.minver = minver; + return res; }; +Readable.prototype.addListener = Readable.prototype.on; -/** - * Returns true if this entry represents a directory. - * - * @returns {boolean} - */ -ZipArchiveEntry.prototype.isDirectory = function() { - return this.getName().slice(-1) === '/'; -}; +function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); +} -/** - * Returns true if this entry represents a unix symlink, - * in which case the entry's content contains the target path - * for the symlink. - * - * @returns {boolean} - */ -ZipArchiveEntry.prototype.isUnixSymlink = function() { - return (this.getUnixMode() & UnixStat.FILE_TYPE_FLAG) === UnixStat.LINK_FLAG; +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume(this, state); + } + return this; }; -/** - * Returns true if this entry is using the ZIP64 extension of ZIP. - * - * @returns {boolean} - */ -ZipArchiveEntry.prototype.isZip64 = function() { - return this.csize > constants.ZIP64_MAGIC || this.size > constants.ZIP64_MAGIC; -}; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + pna.nextTick(resume_, stream, state); + } +} +function resume_(stream, state) { + if (!state.reading) { + debug('resume read 0'); + stream.read(0); + } -/***/ }), + state.resumeScheduled = false; + state.awaitDrain = 0; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); +} -/***/ 44432: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (false !== this._readableState.flowing) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + return this; +}; -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var inherits = (__nccwpck_require__(73837).inherits); -var crc32 = __nccwpck_require__(84794); -var {CRC32Stream} = __nccwpck_require__(5101); -var {DeflateCRC32Stream} = __nccwpck_require__(5101); +function flow(stream) { + var state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null) {} +} -var ArchiveOutputStream = __nccwpck_require__(36728); -var ZipArchiveEntry = __nccwpck_require__(3179); -var GeneralPurposeBit = __nccwpck_require__(63229); +// wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + var _this = this; -var constants = __nccwpck_require__(11704); -var util = __nccwpck_require__(95208); -var zipUtil = __nccwpck_require__(68682); + var state = this._readableState; + var paused = false; -var ZipArchiveOutputStream = module.exports = function(options) { - if (!(this instanceof ZipArchiveOutputStream)) { - return new ZipArchiveOutputStream(options); - } + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) _this.push(chunk); + } - options = this.options = this._defaults(options); + _this.push(null); + }); - ArchiveOutputStream.call(this, options); + stream.on('data', function (chunk) { + debug('wrapped data'); + if (state.decoder) chunk = state.decoder.write(chunk); - this._entry = null; - this._entries = []; - this._archive = { - centralLength: 0, - centralOffset: 0, - comment: '', - finish: false, - finished: false, - processing: false, - forceZip64: options.forceZip64, - forceLocalTime: options.forceLocalTime - }; -}; + // don't skip over falsy values in objectMode + if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; -inherits(ZipArchiveOutputStream, ArchiveOutputStream); + var ret = _this.push(chunk); + if (!ret) { + paused = true; + stream.pause(); + } + }); -ZipArchiveOutputStream.prototype._afterAppend = function(ae) { - this._entries.push(ae); + // proxy all the other methods. + // important when wrapping filters and duplexes. + for (var i in stream) { + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = function (method) { + return function () { + return stream[method].apply(stream, arguments); + }; + }(i); + } + } - if (ae.getGeneralPurposeBit().usesDataDescriptor()) { - this._writeDataDescriptor(ae); + // proxy certain important events. + for (var n = 0; n < kProxyEvents.length; n++) { + stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); } - this._archive.processing = false; - this._entry = null; + // when we try to consume some more bytes, simply unpause the + // underlying stream. + this._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; - if (this._archive.finish && !this._archive.finished) { - this._finish(); - } + return this; }; -ZipArchiveOutputStream.prototype._appendBuffer = function(ae, source, callback) { - if (source.length === 0) { - ae.setMethod(constants.METHOD_STORED); +Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._readableState.highWaterMark; } +}); - var method = ae.getMethod(); +// exposed for testing purposes only. +Readable._fromList = fromList; - if (method === constants.METHOD_STORED) { - ae.setSize(source.length); - ae.setCompressedSize(source.length); - ae.setCrc(crc32.unsigned(source)); +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered + if (state.length === 0) return null; + + var ret; + if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { + // read it all, truncate the list + if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list + ret = fromListPartial(n, state.buffer, state.decoder); } - this._writeLocalFileHeader(ae); + return ret; +} - if (method === constants.METHOD_STORED) { - this.write(source); - this._afterAppend(ae); - callback(null, ae); - return; - } else if (method === constants.METHOD_DEFLATED) { - this._smartStream(ae, callback).end(source); - return; +// Extracts only enough buffered data to satisfy the amount requested. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromListPartial(n, list, hasStrings) { + var ret; + if (n < list.head.data.length) { + // slice is the same for buffers and strings + ret = list.head.data.slice(0, n); + list.head.data = list.head.data.slice(n); + } else if (n === list.head.data.length) { + // first chunk is a perfect match + ret = list.shift(); } else { - callback(new Error('compression method ' + method + ' not implemented')); - return; + // result spans more than one buffer + ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } -}; + return ret; +} -ZipArchiveOutputStream.prototype._appendStream = function(ae, source, callback) { - ae.getGeneralPurposeBit().useDataDescriptor(true); - ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR); +// Copies a specified amount of characters from the list of buffered data +// chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBufferString(n, list) { + var p = list.head; + var c = 1; + var ret = p.data; + n -= ret.length; + while (p = p.next) { + var str = p.data; + var nb = n > str.length ? str.length : n; + if (nb === str.length) ret += str;else ret += str.slice(0, n); + n -= nb; + if (n === 0) { + if (nb === str.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = str.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} - this._writeLocalFileHeader(ae); +// Copies a specified amount of bytes from the list of buffered data chunks. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function copyFromBuffer(n, list) { + var ret = Buffer.allocUnsafe(n); + var p = list.head; + var c = 1; + p.data.copy(ret); + n -= p.data.length; + while (p = p.next) { + var buf = p.data; + var nb = n > buf.length ? buf.length : n; + buf.copy(ret, ret.length - n, 0, nb); + n -= nb; + if (n === 0) { + if (nb === buf.length) { + ++c; + if (p.next) list.head = p.next;else list.head = list.tail = null; + } else { + list.head = p; + p.data = buf.slice(nb); + } + break; + } + ++c; + } + list.length -= c; + return ret; +} - var smart = this._smartStream(ae, callback); - source.once('error', function(err) { - smart.emit('error', err); - smart.end(); - }) - source.pipe(smart); -}; +function endReadable(stream) { + var state = stream._readableState; -ZipArchiveOutputStream.prototype._defaults = function(o) { - if (typeof o !== 'object') { - o = {}; - } + // If we get here before consuming all the bytes, then that is a + // bug in node. Should never happen. + if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - if (typeof o.zlib !== 'object') { - o.zlib = {}; + if (!state.endEmitted) { + state.ended = true; + pna.nextTick(endReadableNT, state, stream); } +} - if (typeof o.zlib.level !== 'number') { - o.zlib.level = constants.ZLIB_BEST_SPEED; +function endReadableNT(state, stream) { + // Check that we didn't get one last unshift. + if (!state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.readable = false; + stream.emit('end'); } +} - o.forceZip64 = !!o.forceZip64; - o.forceLocalTime = !!o.forceLocalTime; +function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; +} - return o; -}; +/***/ }), -ZipArchiveOutputStream.prototype._finish = function() { - this._archive.centralOffset = this.offset; +/***/ 75072: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this._entries.forEach(function(ae) { - this._writeCentralFileHeader(ae); - }.bind(this)); +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - this._archive.centralLength = this.offset - this._archive.centralOffset; +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. - if (this.isZip64()) { - this._writeCentralDirectoryZip64(); - } - this._writeCentralDirectoryEnd(); - this._archive.processing = false; - this._archive.finish = true; - this._archive.finished = true; - this.end(); -}; +module.exports = Transform; -ZipArchiveOutputStream.prototype._normalizeEntry = function(ae) { - if (ae.getMethod() === -1) { - ae.setMethod(constants.METHOD_DEFLATED); - } +var Duplex = __nccwpck_require__(5706); - if (ae.getMethod() === constants.METHOD_DEFLATED) { - ae.getGeneralPurposeBit().useDataDescriptor(true); - ae.setVersionNeededToExtract(constants.MIN_VERSION_DATA_DESCRIPTOR); - } +/**/ +var util = Object.create(__nccwpck_require__(95898)); +util.inherits = __nccwpck_require__(44124); +/**/ - if (ae.getTime() === -1) { - ae.setTime(new Date(), this._archive.forceLocalTime); - } +util.inherits(Transform, Duplex); - ae._offsets = { - file: 0, - data: 0, - contents: 0, - }; -}; +function afterTransform(er, data) { + var ts = this._transformState; + ts.transforming = false; -ZipArchiveOutputStream.prototype._smartStream = function(ae, callback) { - var deflate = ae.getMethod() === constants.METHOD_DEFLATED; - var process = deflate ? new DeflateCRC32Stream(this.options.zlib) : new CRC32Stream(); - var error = null; + var cb = ts.writecb; - function handleStuff() { - var digest = process.digest().readUInt32BE(0); - ae.setCrc(digest); - ae.setSize(process.size()); - ae.setCompressedSize(process.size(true)); - this._afterAppend(ae); - callback(error, ae); + if (!cb) { + return this.emit('error', new Error('write callback called multiple times')); } - process.once('end', handleStuff.bind(this)); - process.once('error', function(err) { - error = err; - }); - - process.pipe(this, { end: false }); + ts.writechunk = null; + ts.writecb = null; - return process; -}; + if (data != null) // single equals check for both `null` and `undefined` + this.push(data); -ZipArchiveOutputStream.prototype._writeCentralDirectoryEnd = function() { - var records = this._entries.length; - var size = this._archive.centralLength; - var offset = this._archive.centralOffset; + cb(er); - if (this.isZip64()) { - records = constants.ZIP64_MAGIC_SHORT; - size = constants.ZIP64_MAGIC; - offset = constants.ZIP64_MAGIC; + var rs = this._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + this._read(rs.highWaterMark); } +} - // signature - this.write(zipUtil.getLongBytes(constants.SIG_EOCD)); +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options); - // disk numbers - this.write(constants.SHORT_ZERO); - this.write(constants.SHORT_ZERO); + Duplex.call(this, options); - // number of entries - this.write(zipUtil.getShortBytes(records)); - this.write(zipUtil.getShortBytes(records)); + this._transformState = { + afterTransform: afterTransform.bind(this), + needTransform: false, + transforming: false, + writecb: null, + writechunk: null, + writeencoding: null + }; - // length and location of CD - this.write(zipUtil.getLongBytes(size)); - this.write(zipUtil.getLongBytes(offset)); + // start out asking for a readable event once data is transformed. + this._readableState.needReadable = true; - // archive comment - var comment = this.getComment(); - var commentLength = Buffer.byteLength(comment); - this.write(zipUtil.getShortBytes(commentLength)); - this.write(comment); -}; + // we have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; -ZipArchiveOutputStream.prototype._writeCentralDirectoryZip64 = function() { - // signature - this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD)); + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; - // size of the ZIP64 EOCD record - this.write(zipUtil.getEightBytes(44)); + if (typeof options.flush === 'function') this._flush = options.flush; + } - // version made by - this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64)); + // When the writable side finishes, then flush out anything remaining. + this.on('prefinish', prefinish); +} - // version to extract - this.write(zipUtil.getShortBytes(constants.MIN_VERSION_ZIP64)); +function prefinish() { + var _this = this; - // disk numbers - this.write(constants.LONG_ZERO); - this.write(constants.LONG_ZERO); + if (typeof this._flush === 'function') { + this._flush(function (er, data) { + done(_this, er, data); + }); + } else { + done(this, null, null); + } +} - // number of entries - this.write(zipUtil.getEightBytes(this._entries.length)); - this.write(zipUtil.getEightBytes(this._entries.length)); +Transform.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex.prototype.push.call(this, chunk, encoding); +}; - // length and location of CD - this.write(zipUtil.getEightBytes(this._archive.centralLength)); - this.write(zipUtil.getEightBytes(this._archive.centralOffset)); +// This is the part where you do stuff! +// override this function in implementation classes. +// 'chunk' is an input chunk. +// +// Call `push(newChunk)` to pass along transformed output +// to the readable side. You may call 'push' zero or more times. +// +// Call `cb(err)` when you are done with this chunk. If you pass +// an error, then that'll put the hurt on the whole operation. If you +// never call cb(), then you'll never get another chunk. +Transform.prototype._transform = function (chunk, encoding, cb) { + throw new Error('_transform() is not implemented'); +}; - // extensible data sector - // not implemented at this time +Transform.prototype._write = function (chunk, encoding, cb) { + var ts = this._transformState; + ts.writecb = cb; + ts.writechunk = chunk; + ts.writeencoding = encoding; + if (!ts.transforming) { + var rs = this._readableState; + if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); + } +}; - // end of central directory locator - this.write(zipUtil.getLongBytes(constants.SIG_ZIP64_EOCD_LOC)); +// Doesn't matter what the args are here. +// _transform does all the work. +// That we got here means that the readable side wants more data. +Transform.prototype._read = function (n) { + var ts = this._transformState; - // disk number holding the ZIP64 EOCD record - this.write(constants.LONG_ZERO); + if (ts.writechunk !== null && ts.writecb && !ts.transforming) { + ts.transforming = true; + this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); + } else { + // mark that we need a transform, so that any data that comes in + // will get processed, now that we've asked for it. + ts.needTransform = true; + } +}; - // relative offset of the ZIP64 EOCD record - this.write(zipUtil.getEightBytes(this._archive.centralOffset + this._archive.centralLength)); +Transform.prototype._destroy = function (err, cb) { + var _this2 = this; - // total number of disks - this.write(zipUtil.getLongBytes(1)); + Duplex.prototype._destroy.call(this, err, function (err2) { + cb(err2); + _this2.emit('close'); + }); }; -ZipArchiveOutputStream.prototype._writeCentralFileHeader = function(ae) { - var gpb = ae.getGeneralPurposeBit(); - var method = ae.getMethod(); - var offsets = ae._offsets; +function done(stream, er, data) { + if (er) return stream.emit('error', er); - var size = ae.getSize(); - var compressedSize = ae.getCompressedSize(); + if (data != null) // single equals check for both `null` and `undefined` + stream.push(data); - if (ae.isZip64() || offsets.file > constants.ZIP64_MAGIC) { - size = constants.ZIP64_MAGIC; - compressedSize = constants.ZIP64_MAGIC; + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); - ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64); + if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); - var extraBuf = Buffer.concat([ - zipUtil.getShortBytes(constants.ZIP64_EXTRA_ID), - zipUtil.getShortBytes(24), - zipUtil.getEightBytes(ae.getSize()), - zipUtil.getEightBytes(ae.getCompressedSize()), - zipUtil.getEightBytes(offsets.file) - ], 28); + return stream.push(null); +} - ae.setExtra(extraBuf); - } +/***/ }), - // signature - this.write(zipUtil.getLongBytes(constants.SIG_CFH)); +/***/ 14960: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // version made by - this.write(zipUtil.getShortBytes((ae.getPlatform() << 8) | constants.VERSION_MADEBY)); +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - // version to extract and general bit flag - this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract())); - this.write(gpb.encode()); +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. - // compression method - this.write(zipUtil.getShortBytes(method)); - // datetime - this.write(zipUtil.getLongBytes(ae.getTimeDos())); - // crc32 checksum - this.write(zipUtil.getLongBytes(ae.getCrc())); +/**/ - // sizes - this.write(zipUtil.getLongBytes(compressedSize)); - this.write(zipUtil.getLongBytes(size)); +var pna = __nccwpck_require__(47810); +/**/ - var name = ae.getName(); - var comment = ae.getComment(); - var extra = ae.getCentralDirectoryExtra(); +module.exports = Writable; - if (gpb.usesUTF8ForNames()) { - name = Buffer.from(name); - comment = Buffer.from(comment); - } +/* */ +function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; +} - // name length - this.write(zipUtil.getShortBytes(name.length)); +// It seems a linked list but it is not +// there will be only 2 of these for each stream +function CorkedRequest(state) { + var _this = this; - // extra length - this.write(zipUtil.getShortBytes(extra.length)); + this.next = null; + this.entry = null; + this.finish = function () { + onCorkedFinish(_this, state); + }; +} +/* */ - // comments length - this.write(zipUtil.getShortBytes(comment.length)); +/**/ +var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; +/**/ - // disk number start - this.write(constants.SHORT_ZERO); +/**/ +var Duplex; +/**/ - // internal attributes - this.write(zipUtil.getShortBytes(ae.getInternalAttributes())); +Writable.WritableState = WritableState; - // external attributes - this.write(zipUtil.getLongBytes(ae.getExternalAttributes())); +/**/ +var util = Object.create(__nccwpck_require__(95898)); +util.inherits = __nccwpck_require__(44124); +/**/ - // relative offset of LFH - if (offsets.file > constants.ZIP64_MAGIC) { - this.write(zipUtil.getLongBytes(constants.ZIP64_MAGIC)); - } else { - this.write(zipUtil.getLongBytes(offsets.file)); - } +/**/ +var internalUtil = { + deprecate: __nccwpck_require__(65278) +}; +/**/ - // name - this.write(name); +/**/ +var Stream = __nccwpck_require__(58745); +/**/ - // extra - this.write(extra); +/**/ - // comment - this.write(comment); -}; +var Buffer = (__nccwpck_require__(15054).Buffer); +var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; +function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk); +} +function _isUint8Array(obj) { + return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +} -ZipArchiveOutputStream.prototype._writeDataDescriptor = function(ae) { - // signature - this.write(zipUtil.getLongBytes(constants.SIG_DD)); +/**/ - // crc32 checksum - this.write(zipUtil.getLongBytes(ae.getCrc())); +var destroyImpl = __nccwpck_require__(78999); - // sizes - if (ae.isZip64()) { - this.write(zipUtil.getEightBytes(ae.getCompressedSize())); - this.write(zipUtil.getEightBytes(ae.getSize())); - } else { - this.write(zipUtil.getLongBytes(ae.getCompressedSize())); - this.write(zipUtil.getLongBytes(ae.getSize())); - } -}; +util.inherits(Writable, Stream); -ZipArchiveOutputStream.prototype._writeLocalFileHeader = function(ae) { - var gpb = ae.getGeneralPurposeBit(); - var method = ae.getMethod(); - var name = ae.getName(); - var extra = ae.getLocalFileDataExtra(); +function nop() {} - if (ae.isZip64()) { - gpb.useDataDescriptor(true); - ae.setVersionNeededToExtract(constants.MIN_VERSION_ZIP64); - } +function WritableState(options, stream) { + Duplex = Duplex || __nccwpck_require__(5706); - if (gpb.usesUTF8ForNames()) { - name = Buffer.from(name); - } + options = options || {}; - ae._offsets.file = this.offset; + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + var isDuplex = stream instanceof Duplex; - // signature - this.write(zipUtil.getLongBytes(constants.SIG_LFH)); + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; - // version to extract and general bit flag - this.write(zipUtil.getShortBytes(ae.getVersionNeededToExtract())); - this.write(gpb.encode()); + if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; - // compression method - this.write(zipUtil.getShortBytes(method)); + // the point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write() + var hwm = options.highWaterMark; + var writableHwm = options.writableHighWaterMark; + var defaultHwm = this.objectMode ? 16 : 16 * 1024; - // datetime - this.write(zipUtil.getLongBytes(ae.getTimeDos())); + if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; - ae._offsets.data = this.offset; + // cast to ints. + this.highWaterMark = Math.floor(this.highWaterMark); - // crc32 checksum and sizes - if (gpb.usesDataDescriptor()) { - this.write(constants.LONG_ZERO); - this.write(constants.LONG_ZERO); - this.write(constants.LONG_ZERO); - } else { - this.write(zipUtil.getLongBytes(ae.getCrc())); - this.write(zipUtil.getLongBytes(ae.getCompressedSize())); - this.write(zipUtil.getLongBytes(ae.getSize())); - } + // if _final has been called + this.finalCalled = false; - // name length - this.write(zipUtil.getShortBytes(name.length)); + // drain event flag. + this.needDrain = false; + // at the start of calling end() + this.ending = false; + // when end() has been called, and returned + this.ended = false; + // when 'finish' is emitted + this.finished = false; - // extra length - this.write(zipUtil.getShortBytes(extra.length)); + // has it been destroyed + this.destroyed = false; - // name - this.write(name); + // should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + var noDecode = options.decodeStrings === false; + this.decodeStrings = !noDecode; - // extra - this.write(extra); + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = options.defaultEncoding || 'utf8'; - ae._offsets.contents = this.offset; -}; + // not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; -ZipArchiveOutputStream.prototype.getComment = function(comment) { - return this._archive.comment !== null ? this._archive.comment : ''; -}; + // a flag to see when we're in the middle of a write. + this.writing = false; -ZipArchiveOutputStream.prototype.isZip64 = function() { - return this._archive.forceZip64 || this._entries.length > constants.ZIP64_MAGIC_SHORT || this._archive.centralLength > constants.ZIP64_MAGIC || this._archive.centralOffset > constants.ZIP64_MAGIC; -}; + // when true all writes will be buffered until .uncork() call + this.corked = 0; -ZipArchiveOutputStream.prototype.setComment = function(comment) { - this._archive.comment = comment; -}; + // a flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + // a flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; -/***/ }), + // the callback that's passed to _write(chunk,cb) + this.onwrite = function (er) { + onwrite(stream, er); + }; -/***/ 25445: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -module.exports = { - ArchiveEntry: __nccwpck_require__(92240), - ZipArchiveEntry: __nccwpck_require__(3179), - ArchiveOutputStream: __nccwpck_require__(36728), - ZipArchiveOutputStream: __nccwpck_require__(44432) -}; + // the amount that is being written when _write is called. + this.writelen = 0; -/***/ }), + this.bufferedRequest = null; + this.lastBufferedRequest = null; -/***/ 95208: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted + this.pendingcb = 0; -/** - * node-compress-commons - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-compress-commons/blob/master/LICENSE-MIT - */ -var Stream = (__nccwpck_require__(12781).Stream); -var PassThrough = (__nccwpck_require__(51642).PassThrough); + // emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams + this.prefinished = false; -var util = module.exports = {}; + // True if the error was already emitted and should not be thrown again + this.errorEmitted = false; -util.isStream = function(source) { - return source instanceof Stream; -}; + // count buffered requests + this.bufferedRequestCount = 0; -util.normalizeInputSource = function(source) { - if (source === null) { - return Buffer.alloc(0); - } else if (typeof source === 'string') { - return Buffer.from(source); - } else if (util.isStream(source) && !source._readableState) { - var normalized = new PassThrough(); - source.pipe(normalized); + // allocate the first CorkedRequest, there is always + // one allocated and free to use, and we maintain at most two + this.corkedRequestsFree = new CorkedRequest(this); +} - return normalized; +WritableState.prototype.getBuffer = function getBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; } - - return source; + return out; }; -/***/ }), +(function () { + try { + Object.defineProperty(WritableState.prototype, 'buffer', { + get: internalUtil.deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') + }); + } catch (_) {} +})(); -/***/ 86891: -/***/ ((module) => { +// Test _writableState for inheritance to account for Duplex streams, +// whose prototype chain only points to Readable. +var realHasInstance; +if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { + realHasInstance = Function.prototype[Symbol.hasInstance]; + Object.defineProperty(Writable, Symbol.hasInstance, { + value: function (object) { + if (realHasInstance.call(this, object)) return true; + if (this !== Writable) return false; -module.exports = function (xs, fn) { - var res = []; - for (var i = 0; i < xs.length; i++) { - var x = fn(xs[i], i); - if (isArray(x)) res.push.apply(res, x); - else res.push(x); + return object && object._writableState instanceof WritableState; } - return res; -}; + }); +} else { + realHasInstance = function (object) { + return object instanceof this; + }; +} -var isArray = Array.isArray || function (xs) { - return Object.prototype.toString.call(xs) === '[object Array]'; -}; +function Writable(options) { + Duplex = Duplex || __nccwpck_require__(5706); + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. -/***/ }), + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { + return new Writable(options); + } -/***/ 95898: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + this._writableState = new WritableState(options, this); -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + // legacy. + this.writable = true; -// NOTE: These type checking functions intentionally don't use `instanceof` -// because it is fragile and can be easily faked with `Object.create()`. + if (options) { + if (typeof options.write === 'function') this._write = options.write; -function isArray(arg) { - if (Array.isArray) { - return Array.isArray(arg); - } - return objectToString(arg) === '[object Array]'; -} -exports.isArray = isArray; + if (typeof options.writev === 'function') this._writev = options.writev; -function isBoolean(arg) { - return typeof arg === 'boolean'; -} -exports.isBoolean = isBoolean; + if (typeof options.destroy === 'function') this._destroy = options.destroy; -function isNull(arg) { - return arg === null; -} -exports.isNull = isNull; + if (typeof options.final === 'function') this._final = options.final; + } -function isNullOrUndefined(arg) { - return arg == null; + Stream.call(this); } -exports.isNullOrUndefined = isNullOrUndefined; -function isNumber(arg) { - return typeof arg === 'number'; -} -exports.isNumber = isNumber; +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + this.emit('error', new Error('Cannot pipe, not readable')); +}; -function isString(arg) { - return typeof arg === 'string'; +function writeAfterEnd(stream, cb) { + var er = new Error('write after end'); + // TODO: defer error events consistently everywhere, not just the cb + stream.emit('error', er); + pna.nextTick(cb, er); } -exports.isString = isString; -function isSymbol(arg) { - return typeof arg === 'symbol'; -} -exports.isSymbol = isSymbol; +// Checks that a user-supplied chunk is valid, especially for the particular +// mode the stream is in. Currently this means that `null` is never accepted +// and undefined/non-string values are only allowed in object mode. +function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; -function isUndefined(arg) { - return arg === void 0; + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + pna.nextTick(cb, er); + valid = false; + } + return valid; } -exports.isUndefined = isUndefined; -function isRegExp(re) { - return objectToString(re) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; +Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + var isBuf = !state.objectMode && _isUint8Array(chunk); -function isObject(arg) { - return typeof arg === 'object' && arg !== null; -} -exports.isObject = isObject; + if (isBuf && !Buffer.isBuffer(chunk)) { + chunk = _uint8ArrayToBuffer(chunk); + } -function isDate(d) { - return objectToString(d) === '[object Date]'; -} -exports.isDate = isDate; + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } -function isError(e) { - return (objectToString(e) === '[object Error]' || e instanceof Error); -} -exports.isError = isError; + if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; -function isFunction(arg) { - return typeof arg === 'function'; -} -exports.isFunction = isFunction; + if (typeof cb !== 'function') cb = nop; -function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; -} -exports.isPrimitive = isPrimitive; + if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); + } -exports.isBuffer = __nccwpck_require__(14300).Buffer.isBuffer; + return ret; +}; -function objectToString(o) { - return Object.prototype.toString.call(o); -} +Writable.prototype.cork = function () { + var state = this._writableState; + state.corked++; +}; -/***/ }), +Writable.prototype.uncork = function () { + var state = this._writableState; -/***/ 83201: -/***/ ((__unused_webpack_module, exports) => { + if (state.corked) { + state.corked--; -/*! crc32.js (C) 2014-present SheetJS -- http://sheetjs.com */ -/* vim: set ts=2: */ -/*exported CRC32 */ -var CRC32; -(function (factory) { - /*jshint ignore:start */ - /*eslint-disable */ - if(typeof DO_NOT_EXPORT_CRC === 'undefined') { - if(true) { - factory(exports); - } else {} - } else { - factory(CRC32 = {}); - } - /*eslint-enable */ - /*jshint ignore:end */ -}(function(CRC32) { -CRC32.version = '1.2.2'; -/*global Int32Array */ -function signed_crc_table() { - var c = 0, table = new Array(256); + if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } +}; - for(var n =0; n != 256; ++n){ - c = n; - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - c = ((c&1) ? (-306674912 ^ (c >>> 1)) : (c >>> 1)); - table[n] = c; - } +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = encoding.toLowerCase(); + if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); + this._writableState.defaultEncoding = encoding; + return this; +}; - return typeof Int32Array !== 'undefined' ? new Int32Array(table) : table; +function decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; } -var T0 = signed_crc_table(); -function slice_by_16_tables(T) { - var c = 0, v = 0, n = 0, table = typeof Int32Array !== 'undefined' ? new Int32Array(4096) : new Array(4096) ; +Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { + // making it explicit this property is not enumerable + // because otherwise some prototype manipulation in + // userland will fail + enumerable: false, + get: function () { + return this._writableState.highWaterMark; + } +}); - for(n = 0; n != 256; ++n) table[n] = T[n]; - for(n = 0; n != 256; ++n) { - v = T[n]; - for(c = 256 + n; c < 4096; c += 256) v = table[c] = (v >>> 8) ^ T[v & 0xFF]; - } - var out = []; - for(n = 1; n != 16; ++n) out[n - 1] = typeof Int32Array !== 'undefined' ? table.subarray(n * 256, n * 256 + 256) : table.slice(n * 256, n * 256 + 256); - return out; -} -var TT = slice_by_16_tables(T0); -var T1 = TT[0], T2 = TT[1], T3 = TT[2], T4 = TT[3], T5 = TT[4]; -var T6 = TT[5], T7 = TT[6], T8 = TT[7], T9 = TT[8], Ta = TT[9]; -var Tb = TT[10], Tc = TT[11], Td = TT[12], Te = TT[13], Tf = TT[14]; -function crc32_bstr(bstr, seed) { - var C = seed ^ -1; - for(var i = 0, L = bstr.length; i < L;) C = (C>>>8) ^ T0[(C^bstr.charCodeAt(i++))&0xFF]; - return ~C; -} +// if we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { + if (!isBuf) { + var newChunk = decodeChunk(state, chunk, encoding); + if (chunk !== newChunk) { + isBuf = true; + encoding = 'buffer'; + chunk = newChunk; + } + } + var len = state.objectMode ? 1 : chunk.length; -function crc32_buf(B, seed) { - var C = seed ^ -1, L = B.length - 15, i = 0; - for(; i < L;) C = - Tf[B[i++] ^ (C & 255)] ^ - Te[B[i++] ^ ((C >> 8) & 255)] ^ - Td[B[i++] ^ ((C >> 16) & 255)] ^ - Tc[B[i++] ^ (C >>> 24)] ^ - Tb[B[i++]] ^ Ta[B[i++]] ^ T9[B[i++]] ^ T8[B[i++]] ^ - T7[B[i++]] ^ T6[B[i++]] ^ T5[B[i++]] ^ T4[B[i++]] ^ - T3[B[i++]] ^ T2[B[i++]] ^ T1[B[i++]] ^ T0[B[i++]]; - L += 15; - while(i < L) C = (C>>>8) ^ T0[(C^B[i++])&0xFF]; - return ~C; -} + state.length += len; -function crc32_str(str, seed) { - var C = seed ^ -1; - for(var i = 0, L = str.length, c = 0, d = 0; i < L;) { - c = str.charCodeAt(i++); - if(c < 0x80) { - C = (C>>>8) ^ T0[(C^c)&0xFF]; - } else if(c < 0x800) { - C = (C>>>8) ^ T0[(C ^ (192|((c>>6)&31)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; - } else if(c >= 0xD800 && c < 0xE000) { - c = (c&1023)+64; d = str.charCodeAt(i++)&1023; - C = (C>>>8) ^ T0[(C ^ (240|((c>>8)&7)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|((c>>2)&63)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|((d>>6)&15)|((c&3)<<4)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|(d&63)))&0xFF]; - } else { - C = (C>>>8) ^ T0[(C ^ (224|((c>>12)&15)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|((c>>6)&63)))&0xFF]; - C = (C>>>8) ^ T0[(C ^ (128|(c&63)))&0xFF]; - } - } - return ~C; -} -CRC32.table = T0; -// $FlowIgnore -CRC32.bstr = crc32_bstr; -// $FlowIgnore -CRC32.buf = crc32_buf; -// $FlowIgnore -CRC32.str = crc32_str; -})); + var ret = state.length < state.highWaterMark; + // we must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + if (state.writing || state.corked) { + var last = state.lastBufferedRequest; + state.lastBufferedRequest = { + chunk: chunk, + encoding: encoding, + isBuf: isBuf, + callback: cb, + next: null + }; + if (last) { + last.next = state.lastBufferedRequest; + } else { + state.bufferedRequest = state.lastBufferedRequest; + } + state.bufferedRequestCount += 1; + } else { + doWrite(stream, state, false, len, chunk, encoding, cb); + } -/***/ }), + return ret; +} -/***/ 94521: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); + state.sync = false; +} -"use strict"; -/** - * node-crc32-stream - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT - */ +function onwriteError(stream, state, sync, er, cb) { + --state.pendingcb; - + if (sync) { + // defer the callback if we are being called synchronously + // to avoid piling up things on the stack + pna.nextTick(cb, er); + // this can emit finish, and it will always happen + // after error + pna.nextTick(finishMaybe, stream, state); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } else { + // the caller expect this to happen before if + // it is async + cb(er); + stream._writableState.errorEmitted = true; + stream.emit('error', er); + // this can emit finish, but finish must + // always follow error + finishMaybe(stream, state); + } +} -const {Transform} = __nccwpck_require__(51642); +function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; +} -const crc32 = __nccwpck_require__(83201); +function onwrite(stream, er) { + var state = stream._writableState; + var sync = state.sync; + var cb = state.writecb; -class CRC32Stream extends Transform { - constructor(options) { - super(options); - this.checksum = Buffer.allocUnsafe(4); - this.checksum.writeInt32BE(0, 0); + onwriteStateUpdate(state); - this.rawSize = 0; - } + if (er) onwriteError(stream, state, sync, er, cb);else { + // Check if we're actually ready to finish, but don't emit yet + var finished = needFinish(state); - _transform(chunk, encoding, callback) { - if (chunk) { - this.checksum = crc32.buf(chunk, this.checksum) >>> 0; - this.rawSize += chunk.length; + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); } - callback(null, chunk); - } - - digest(encoding) { - const checksum = Buffer.allocUnsafe(4); - checksum.writeUInt32BE(this.checksum >>> 0, 0); - return encoding ? checksum.toString(encoding) : checksum; + if (sync) { + /**/ + asyncWrite(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } } +} - hex() { - return this.digest('hex').toUpperCase(); - } +function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); +} - size() { - return this.rawSize; +// Must force callback to be called on nextTick, so that we don't +// emit 'drain' before the write() consumer gets the 'false' return +// value, and has a chance to attach a 'drain' listener. +function onwriteDrain(stream, state) { + if (state.length === 0 && state.needDrain) { + state.needDrain = false; + stream.emit('drain'); } } -module.exports = CRC32Stream; +// if there's something in the buffer waiting, then process it +function clearBuffer(stream, state) { + state.bufferProcessing = true; + var entry = state.bufferedRequest; + if (stream._writev && entry && entry.next) { + // Fast case, write everything using _writev() + var l = state.bufferedRequestCount; + var buffer = new Array(l); + var holder = state.corkedRequestsFree; + holder.entry = entry; -/***/ }), + var count = 0; + var allBuffers = true; + while (entry) { + buffer[count] = entry; + if (!entry.isBuf) allBuffers = false; + entry = entry.next; + count += 1; + } + buffer.allBuffers = allBuffers; -/***/ 92563: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + doWrite(stream, state, true, state.length, buffer, '', holder.finish); -"use strict"; -/** - * node-crc32-stream - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT - */ + // doWrite is almost always async, defer these to save a bit of time + // as the hot path ends with doWrite + state.pendingcb++; + state.lastBufferedRequest = null; + if (holder.next) { + state.corkedRequestsFree = holder.next; + holder.next = null; + } else { + state.corkedRequestsFree = new CorkedRequest(state); + } + state.bufferedRequestCount = 0; + } else { + // Slow case, write chunks one-by-one + while (entry) { + var chunk = entry.chunk; + var encoding = entry.encoding; + var cb = entry.callback; + var len = state.objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, cb); + entry = entry.next; + state.bufferedRequestCount--; + // if we didn't call the onwrite immediately, then + // it means that we need to wait until it does. + // also, that means that the chunk and cb are currently + // being processed, so move the buffer counter past them. + if (state.writing) { + break; + } + } + if (entry === null) state.lastBufferedRequest = null; + } -const {DeflateRaw} = __nccwpck_require__(59796); + state.bufferedRequest = entry; + state.bufferProcessing = false; +} -const crc32 = __nccwpck_require__(83201); +Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('_write() is not implemented')); +}; -class DeflateCRC32Stream extends DeflateRaw { - constructor(options) { - super(options); +Writable.prototype._writev = null; - this.checksum = Buffer.allocUnsafe(4); - this.checksum.writeInt32BE(0, 0); +Writable.prototype.end = function (chunk, encoding, cb) { + var state = this._writableState; - this.rawSize = 0; - this.compressedSize = 0; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; } - push(chunk, encoding) { - if (chunk) { - this.compressedSize += chunk.length; - } + if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); - return super.push(chunk, encoding); + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); } - _transform(chunk, encoding, callback) { - if (chunk) { - this.checksum = crc32.buf(chunk, this.checksum) >>> 0; - this.rawSize += chunk.length; - } + // ignore unnecessary end() calls. + if (!state.ending) endWritable(this, state, cb); +}; - super._transform(chunk, encoding, callback) +function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; +} +function callFinal(stream, state) { + stream._final(function (err) { + state.pendingcb--; + if (err) { + stream.emit('error', err); + } + state.prefinished = true; + stream.emit('prefinish'); + finishMaybe(stream, state); + }); +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function') { + state.pendingcb++; + state.finalCalled = true; + pna.nextTick(callFinal, stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } } +} - digest(encoding) { - const checksum = Buffer.allocUnsafe(4); - checksum.writeUInt32BE(this.checksum >>> 0, 0); - return encoding ? checksum.toString(encoding) : checksum; +function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + prefinish(stream, state); + if (state.pendingcb === 0) { + state.finished = true; + stream.emit('finish'); + } } + return need; +} - hex() { - return this.digest('hex').toUpperCase(); +function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); } + state.ended = true; + stream.writable = false; +} - size(compressed = false) { - if (compressed) { - return this.compressedSize; - } else { - return this.rawSize; - } +function onCorkedFinish(corkReq, state, err) { + var entry = corkReq.entry; + corkReq.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; } + + // reuse the free corkReq. + state.corkedRequestsFree.next = corkReq; } -module.exports = DeflateCRC32Stream; +Object.defineProperty(Writable.prototype, 'destroyed', { + get: function () { + if (this._writableState === undefined) { + return false; + } + return this._writableState.destroyed; + }, + set: function (value) { + // we ignore the value if the stream + // has not been initialized yet + if (!this._writableState) { + return; + } + + // backward compatibility, the user is explicitly + // managing destroyed + this._writableState.destroyed = value; + } +}); +Writable.prototype.destroy = destroyImpl.destroy; +Writable.prototype._undestroy = destroyImpl.undestroy; +Writable.prototype._destroy = function (err, cb) { + this.end(); + cb(err); +}; /***/ }), -/***/ 5101: +/***/ 75454: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/** - * node-crc32-stream - * - * Copyright (c) 2014 Chris Talkington, contributors. - * Licensed under the MIT license. - * https://github.com/archiverjs/node-crc32-stream/blob/master/LICENSE-MIT - */ +function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } -module.exports = { - CRC32Stream: __nccwpck_require__(94521), - DeflateCRC32Stream: __nccwpck_require__(92563) +var Buffer = (__nccwpck_require__(15054).Buffer); +var util = __nccwpck_require__(73837); + +function copyBuffer(src, target, offset) { + src.copy(target, offset); } +module.exports = function () { + function BufferList() { + _classCallCheck(this, BufferList); -/***/ }), + this.head = null; + this.tail = null; + this.length = 0; + } -/***/ 18611: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + BufferList.prototype.push = function push(v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; -var Stream = (__nccwpck_require__(12781).Stream); -var util = __nccwpck_require__(73837); + BufferList.prototype.unshift = function unshift(v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; -module.exports = DelayedStream; -function DelayedStream() { - this.source = null; - this.dataSize = 0; - this.maxDataSize = 1024 * 1024; - this.pauseStream = true; + BufferList.prototype.shift = function shift() { + if (this.length === 0) return; + var ret = this.head.data; + if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; + --this.length; + return ret; + }; - this._maxDataSizeExceeded = false; - this._released = false; - this._bufferedEvents = []; -} -util.inherits(DelayedStream, Stream); + BufferList.prototype.clear = function clear() { + this.head = this.tail = null; + this.length = 0; + }; -DelayedStream.create = function(source, options) { - var delayedStream = new this(); + BufferList.prototype.join = function join(s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; - options = options || {}; - for (var option in options) { - delayedStream[option] = options[option]; - } + BufferList.prototype.concat = function concat(n) { + if (this.length === 0) return Buffer.alloc(0); + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + copyBuffer(p.data, ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; - delayedStream.source = source; + return BufferList; +}(); - var realEmit = source.emit; - source.emit = function() { - delayedStream._handleEmit(arguments); - return realEmit.apply(source, arguments); +if (util && util.inspect && util.inspect.custom) { + module.exports.prototype[util.inspect.custom] = function () { + var obj = util.inspect({ length: this.length }); + return this.constructor.name + ' ' + obj; }; +} - source.on('error', function() {}); - if (delayedStream.pauseStream) { - source.pause(); - } +/***/ }), - return delayedStream; -}; +/***/ 78999: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(DelayedStream.prototype, 'readable', { - configurable: true, - enumerable: true, - get: function() { - return this.source.readable; - } -}); +"use strict"; -DelayedStream.prototype.setEncoding = function() { - return this.source.setEncoding.apply(this.source, arguments); -}; -DelayedStream.prototype.resume = function() { - if (!this._released) { - this.release(); - } +/**/ - this.source.resume(); -}; +var pna = __nccwpck_require__(47810); +/**/ -DelayedStream.prototype.pause = function() { - this.source.pause(); -}; +// undocumented cb() API, needed for core, not for public API +function destroy(err, cb) { + var _this = this; -DelayedStream.prototype.release = function() { - this._released = true; + var readableDestroyed = this._readableState && this._readableState.destroyed; + var writableDestroyed = this._writableState && this._writableState.destroyed; - this._bufferedEvents.forEach(function(args) { - this.emit.apply(this, args); - }.bind(this)); - this._bufferedEvents = []; -}; + if (readableDestroyed || writableDestroyed) { + if (cb) { + cb(err); + } else if (err) { + if (!this._writableState) { + pna.nextTick(emitErrorNT, this, err); + } else if (!this._writableState.errorEmitted) { + this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, this, err); + } + } -DelayedStream.prototype.pipe = function() { - var r = Stream.prototype.pipe.apply(this, arguments); - this.resume(); - return r; -}; + return this; + } -DelayedStream.prototype._handleEmit = function(args) { - if (this._released) { - this.emit.apply(this, args); - return; + // we set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + + if (this._readableState) { + this._readableState.destroyed = true; } - if (args[0] === 'data') { - this.dataSize += args[1].length; - this._checkIfMaxDataSizeExceeded(); + // if this is a duplex stream mark the writable part as destroyed as well + if (this._writableState) { + this._writableState.destroyed = true; } - this._bufferedEvents.push(args); -}; + this._destroy(err || null, function (err) { + if (!cb && err) { + if (!_this._writableState) { + pna.nextTick(emitErrorNT, _this, err); + } else if (!_this._writableState.errorEmitted) { + _this._writableState.errorEmitted = true; + pna.nextTick(emitErrorNT, _this, err); + } + } else if (cb) { + cb(err); + } + }); -DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { - if (this._maxDataSizeExceeded) { - return; + return this; +} + +function undestroy() { + if (this._readableState) { + this._readableState.destroyed = false; + this._readableState.reading = false; + this._readableState.ended = false; + this._readableState.endEmitted = false; } - if (this.dataSize <= this.maxDataSize) { - return; + if (this._writableState) { + this._writableState.destroyed = false; + this._writableState.ended = false; + this._writableState.ending = false; + this._writableState.finalCalled = false; + this._writableState.prefinished = false; + this._writableState.finished = false; + this._writableState.errorEmitted = false; } +} - this._maxDataSizeExceeded = true; - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' - this.emit('error', new Error(message)); -}; +function emitErrorNT(self, err) { + self.emit('error', err); +} +module.exports = { + destroy: destroy, + undestroy: undestroy +}; /***/ }), -/***/ 58932: -/***/ ((__unused_webpack_module, exports) => { +/***/ 58745: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +module.exports = __nccwpck_require__(12781); -Object.defineProperty(exports, "__esModule", ({ value: true })); +/***/ }), -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) +/***/ 27818: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /* istanbul ignore next */ +module.exports = __nccwpck_require__(22399).PassThrough - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.name = 'Deprecation'; - } +/***/ }), -} +/***/ 22399: +/***/ ((module, exports, __nccwpck_require__) => { -exports.Deprecation = Deprecation; +var Stream = __nccwpck_require__(12781); +if (process.env.READABLE_STREAM === 'disable' && Stream) { + module.exports = Stream; + exports = module.exports = Stream.Readable; + exports.Readable = Stream.Readable; + exports.Writable = Stream.Writable; + exports.Duplex = Stream.Duplex; + exports.Transform = Stream.Transform; + exports.PassThrough = Stream.PassThrough; + exports.Stream = Stream; +} else { + exports = module.exports = __nccwpck_require__(99140); + exports.Stream = Stream || exports; + exports.Readable = exports; + exports.Writable = __nccwpck_require__(14960); + exports.Duplex = __nccwpck_require__(5706); + exports.Transform = __nccwpck_require__(75072); + exports.PassThrough = __nccwpck_require__(70982); +} /***/ }), -/***/ 13598: -/***/ ((module) => { - -"use strict"; - +/***/ 15054: +/***/ ((module, exports, __nccwpck_require__) => { -function _process (v, mod) { - var i - var r +/* eslint-disable node/no-deprecated-api */ +var buffer = __nccwpck_require__(14300) +var Buffer = buffer.Buffer - if (typeof mod === 'function') { - r = mod(v) - if (r !== undefined) { - v = r - } - } else if (Array.isArray(mod)) { - for (i = 0; i < mod.length; i++) { - r = mod[i](v) - if (r !== undefined) { - v = r - } - } +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} - return v +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) } -function parseKey (key, val) { - // detect negative index notation - if (key[0] === '-' && Array.isArray(val) && /^-\d+$/.test(key)) { - return val.length + parseInt(key, 10) +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) + +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') } - return key + return Buffer(arg, encodingOrOffset, length) } -function isIndex (k) { - return /^\d+$/.test(k) +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf } -function isObject (val) { - return Object.prototype.toString.call(val) === '[object Object]' +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) } -function isArrayOrObject (val) { - return Object(val) === val +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) } -function isEmptyObject (val) { - return Object.keys(val).length === 0 -} -var blacklist = ['__proto__', 'prototype', 'constructor'] -var blacklistFilter = function (part) { return blacklist.indexOf(part) === -1 } +/***/ }), -function parsePath (path, sep) { - if (path.indexOf('[') >= 0) { - path = path.replace(/\[/g, sep).replace(/]/g, '') - } +/***/ 24749: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var parts = path.split(sep) +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - var check = parts.filter(blacklistFilter) - if (check.length !== parts.length) { - throw Error('Refusing to update blacklisted property ' + path) - } - return parts -} +/**/ -var hasOwnProperty = Object.prototype.hasOwnProperty +var Buffer = (__nccwpck_require__(15054).Buffer); +/**/ -function DotObject (separator, override, useArray, useBrackets) { - if (!(this instanceof DotObject)) { - return new DotObject(separator, override, useArray, useBrackets) +var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; } +}; - if (typeof override === 'undefined') override = false - if (typeof useArray === 'undefined') useArray = true - if (typeof useBrackets === 'undefined') useBrackets = true - this.separator = separator || '.' - this.override = override - this.useArray = useArray - this.useBrackets = useBrackets - this.keepArray = false +function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } +}; - // contains touched arrays - this.cleanup = [] +// Do not cache `Buffer.isEncoding` when checking encoding names as some +// modules monkey-patch it to support additional encodings +function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; } -var dotDefault = new DotObject('.', false, true, true) -function wrap (method) { - return function () { - return dotDefault[method].apply(dotDefault, arguments) +// StringDecoder provides an interface for efficiently splitting a series of +// buffers into a series of JS strings without breaking apart multi-byte +// characters. +exports.s = StringDecoder; +function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); } -DotObject.prototype._fill = function (a, obj, v, mod) { - var k = a.shift() +StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; +}; - if (a.length > 0) { - obj[k] = obj[k] || (this.useArray && isIndex(a[0]) ? [] : {}) +StringDecoder.prototype.end = utf8End; - if (!isArrayOrObject(obj[k])) { - if (this.override) { - obj[k] = {} - } else { - if (!(isArrayOrObject(v) && isEmptyObject(v))) { - throw new Error( - 'Trying to redefine `' + k + '` which is a ' + typeof obj[k] - ) - } +// Returns only complete characters in a Buffer +StringDecoder.prototype.text = utf8Text; - return - } - } +// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer +StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; +}; - this._fill(a, obj[k], v, mod) - } else { - if (!this.override && isArrayOrObject(obj[k]) && !isEmptyObject(obj[k])) { - if (!(isArrayOrObject(v) && isEmptyObject(v))) { - throw new Error("Trying to redefine non-empty obj['" + k + "']") - } +// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a +// continuation byte. If an invalid byte is detected, -2 is returned. +function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; +} - return +// Checks at most 3 bytes at the end of a Buffer in order to detect an +// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) +// needed to complete the UTF-8 character (if applicable) are returned. +function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } - - obj[k] = _process(v, mod) + return nb; } + return 0; } -/** - * - * Converts an object with dotted-key/value pairs to it's expanded version - * - * Optionally transformed by a set of modifiers. - * - * Usage: - * - * var row = { - * 'nr': 200, - * 'doc.name': ' My Document ' - * } - * - * var mods = { - * 'doc.name': [_s.trim, _s.underscored] - * } - * - * dot.object(row, mods) - * - * @param {Object} obj - * @param {Object} mods - */ -DotObject.prototype.object = function (obj, mods) { - var self = this - - Object.keys(obj).forEach(function (k) { - var mod = mods === undefined ? null : mods[k] - // normalize array notation. - var ok = parsePath(k, self.separator).join(self.separator) - - if (ok.indexOf(self.separator) !== -1) { - self._fill(ok.split(self.separator), obj, obj[k], mod) - delete obj[k] - } else { - obj[k] = _process(obj[k], mod) +// Validates as many continuation bytes for a multi-byte UTF-8 character as +// needed or are available. If we see a non-continuation byte where we expect +// one, we "replace" the validated continuation bytes we've seen so far with +// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding +// behavior. The continuation byte check is included three times in the case +// where all of the continuation bytes for a character exist in the same buffer. +// It is also done this way as a slight performance increase instead of using a +// loop. +function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; } - }) - - return obj + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } } -/** - * @param {String} path dotted path - * @param {String} v value to be set - * @param {Object} obj object to be modified - * @param {Function|Array} mod optional modifier - */ -DotObject.prototype.str = function (path, v, obj, mod) { - var ok = parsePath(path, this.separator).join(this.separator) - - if (path.indexOf(this.separator) !== -1) { - this._fill(ok.split(this.separator), obj, v, mod) - } else { - obj[path] = _process(v, mod) +// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. +function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf, p); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; +} - return obj +// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a +// partial character, the character's bytes are buffered until the required +// number of bytes are available. +function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); } -/** - * - * Pick a value from an object using dot notation. - * - * Optionally remove the value - * - * @param {String} path - * @param {Object} obj - * @param {Boolean} remove - */ -DotObject.prototype.pick = function (path, obj, remove, reindexArray) { - var i - var keys - var val - var key - var cp +// For UTF-8, a replacement character is added when ending on a partial +// character. +function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; +} - keys = parsePath(path, this.separator) - for (i = 0; i < keys.length; i++) { - key = parseKey(keys[i], obj) - if (obj && typeof obj === 'object' && key in obj) { - if (i === keys.length - 1) { - if (remove) { - val = obj[key] - if (reindexArray && Array.isArray(obj)) { - obj.splice(key, 1) - } else { - delete obj[key] - } - if (Array.isArray(obj)) { - cp = keys.slice(0, -1).join('.') - if (this.cleanup.indexOf(cp) === -1) { - this.cleanup.push(cp) - } - } - return val - } else { - return obj[key] - } - } else { - obj = obj[key] +// UTF-16LE typically needs two bytes per character, but even if we have an even +// number of bytes available, we need to check if we end on a leading/high +// surrogate. In that case, we need to wait for the next two bytes in order to +// decode the last character properly. +function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); } - } else { - return undefined } + return r; } - if (remove && Array.isArray(obj)) { - obj = obj.filter(function (n) { - return n !== undefined - }) - } - return obj -} -/** - * - * Delete value from an object using dot notation. - * - * @param {String} path - * @param {Object} obj - * @return {any} The removed value - */ -DotObject.prototype.delete = function (path, obj) { - return this.remove(path, obj, true) + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); } -/** - * - * Remove value from an object using dot notation. - * - * Will remove multiple items if path is an array. - * In this case array indexes will be retained until all - * removals have been processed. - * - * Use dot.delete() to automatically re-index arrays. - * - * @param {String|Array} path - * @param {Object} obj - * @param {Boolean} reindexArray - * @return {any} The removed value - */ -DotObject.prototype.remove = function (path, obj, reindexArray) { - var i - - this.cleanup = [] - if (Array.isArray(path)) { - for (i = 0; i < path.length; i++) { - this.pick(path[i], obj, true, reindexArray) - } - if (!reindexArray) { - this._cleanup(obj) - } - return obj - } else { - return this.pick(path, obj, true, reindexArray) +// For UTF-16LE we do not explicitly append special replacement characters if we +// end on a partial character, we simply let v8 handle that. +function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); } + return r; } -DotObject.prototype._cleanup = function (obj) { - var ret - var i - var keys - var root - if (this.cleanup.length) { - for (i = 0; i < this.cleanup.length; i++) { - keys = this.cleanup[i].split('.') - root = keys.splice(0, -1).join('.') - ret = root ? this.pick(root, obj) : obj - ret = ret[keys[0]].filter(function (v) { - return v !== undefined - }) - this.set(this.cleanup[i], ret, obj) - } - this.cleanup = [] +function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; } + return buf.toString('base64', i, buf.length - n); } -/** - * Alias method for `dot.remove` - * - * Note: this is not an alias for dot.delete() - * - * @param {String|Array} path - * @param {Object} obj - * @param {Boolean} reindexArray - * @return {any} The removed value - */ -DotObject.prototype.del = DotObject.prototype.remove +function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; +} -/** - * - * Move a property from one place to the other. - * - * If the source path does not exist (undefined) - * the target property will not be set. - * - * @param {String} source - * @param {String} target - * @param {Object} obj - * @param {Function|Array} mods - * @param {Boolean} merge - */ -DotObject.prototype.move = function (source, target, obj, mods, merge) { - if (typeof mods === 'function' || Array.isArray(mods)) { - this.set(target, _process(this.pick(source, obj, true), mods), obj, merge) - } else { - merge = mods - this.set(target, this.pick(source, obj, true), obj, merge) - } +// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) +function simpleWrite(buf) { + return buf.toString(this.encoding); +} - return obj +function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; } -/** - * - * Transfer a property from one object to another object. - * - * If the source path does not exist (undefined) - * the property on the other object will not be set. - * - * @param {String} source - * @param {String} target - * @param {Object} obj1 - * @param {Object} obj2 - * @param {Function|Array} mods - * @param {Boolean} merge - */ -DotObject.prototype.transfer = function ( - source, - target, - obj1, - obj2, - mods, - merge -) { - if (typeof mods === 'function' || Array.isArray(mods)) { - this.set( - target, - _process(this.pick(source, obj1, true), mods), - obj2, - merge - ) - } else { - merge = mods - this.set(target, this.pick(source, obj1, true), obj2, merge) - } +/***/ }), - return obj2 -} +/***/ 35902: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var hashClear = __nccwpck_require__(11789), + hashDelete = __nccwpck_require__(60712), + hashGet = __nccwpck_require__(45395), + hashHas = __nccwpck_require__(35232), + hashSet = __nccwpck_require__(47320); /** + * Creates a hash object. * - * Copy a property from one object to another object. - * - * If the source path does not exist (undefined) - * the property on the other object will not be set. - * - * @param {String} source - * @param {String} target - * @param {Object} obj1 - * @param {Object} obj2 - * @param {Function|Array} mods - * @param {Boolean} merge + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ -DotObject.prototype.copy = function (source, target, obj1, obj2, mods, merge) { - if (typeof mods === 'function' || Array.isArray(mods)) { - this.set( - target, - _process( - // clone what is picked - JSON.parse(JSON.stringify(this.pick(source, obj1, false))), - mods - ), - obj2, - merge - ) - } else { - merge = mods - this.set(target, this.pick(source, obj1, false), obj2, merge) - } +function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; - return obj2 + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } } -/** - * - * Set a property on an object using dot notation. - * - * @param {String} path - * @param {any} val - * @param {Object} obj - * @param {Boolean} merge - */ -DotObject.prototype.set = function (path, val, obj, merge) { - var i - var k - var keys - var key +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; - // Do not operate if the value is undefined. - if (typeof val === 'undefined') { - return obj - } - keys = parsePath(path, this.separator) +module.exports = Hash; - for (i = 0; i < keys.length; i++) { - key = keys[i] - if (i === keys.length - 1) { - if (merge && isObject(val) && isObject(obj[key])) { - for (k in val) { - if (hasOwnProperty.call(val, k)) { - obj[key][k] = val[k] - } - } - } else if (merge && Array.isArray(obj[key]) && Array.isArray(val)) { - for (var j = 0; j < val.length; j++) { - obj[keys[i]].push(val[j]) - } - } else { - obj[key] = val - } - } else if ( - // force the value to be an object - !hasOwnProperty.call(obj, key) || - (!isObject(obj[key]) && !Array.isArray(obj[key])) - ) { - // initialize as array if next key is numeric - if (/^\d+$/.test(keys[i + 1])) { - obj[key] = [] - } else { - obj[key] = {} - } - } - obj = obj[key] - } - return obj -} -/** - * - * Transform an object - * - * Usage: - * - * var obj = { - * "id": 1, - * "some": { - * "thing": "else" - * } - * } - * - * var transform = { - * "id": "nr", - * "some.thing": "name" - * } - * - * var tgt = dot.transform(transform, obj) - * - * @param {Object} recipe Transform recipe - * @param {Object} obj Object to be transformed - * @param {Array} mods modifiers for the target - */ -DotObject.prototype.transform = function (recipe, obj, tgt) { - obj = obj || {} - tgt = tgt || {} - Object.keys(recipe).forEach( - function (key) { - this.set(recipe[key], this.pick(key, obj), tgt) - }.bind(this) - ) - return tgt -} +/***/ }), + +/***/ 96608: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var listCacheClear = __nccwpck_require__(69792), + listCacheDelete = __nccwpck_require__(97716), + listCacheGet = __nccwpck_require__(45789), + listCacheHas = __nccwpck_require__(59386), + listCacheSet = __nccwpck_require__(17399); /** + * Creates an list cache object. * - * Convert object to dotted-key/value pair - * - * Usage: - * - * var tgt = dot.dot(obj) - * - * or - * - * var tgt = {} - * dot.dot(obj, tgt) - * - * @param {Object} obj source object - * @param {Object} tgt target object - * @param {Array} path path array (internal) + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ -DotObject.prototype.dot = function (obj, tgt, path) { - tgt = tgt || {} - path = path || [] - var isArray = Array.isArray(obj) +function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; - Object.keys(obj).forEach( - function (key) { - var index = isArray && this.useBrackets ? '[' + key + ']' : key - if ( - isArrayOrObject(obj[key]) && - ((isObject(obj[key]) && !isEmptyObject(obj[key])) || - (Array.isArray(obj[key]) && !this.keepArray && obj[key].length !== 0)) - ) { - if (isArray && this.useBrackets) { - var previousKey = path[path.length - 1] || '' - return this.dot( - obj[key], - tgt, - path.slice(0, -1).concat(previousKey + index) - ) - } else { - return this.dot(obj[key], tgt, path.concat(index)) - } - } else { - if (isArray && this.useBrackets) { - tgt[path.join(this.separator).concat('[' + key + ']')] = obj[key] - } else { - tgt[path.concat(index).join(this.separator)] = obj[key] - } - } - }.bind(this) - ) - return tgt + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } } -DotObject.pick = wrap('pick') -DotObject.move = wrap('move') -DotObject.transfer = wrap('transfer') -DotObject.transform = wrap('transform') -DotObject.copy = wrap('copy') -DotObject.object = wrap('object') -DotObject.str = wrap('str') -DotObject.set = wrap('set') -DotObject.delete = wrap('delete') -DotObject.del = DotObject.remove = wrap('remove') -DotObject.dot = wrap('dot'); -['override', 'overwrite'].forEach(function (prop) { - Object.defineProperty(DotObject, prop, { - get: function () { - return dotDefault.override - }, - set: function (val) { - dotDefault.override = !!val - } - }) -}); -['useArray', 'keepArray', 'useBrackets'].forEach(function (prop) { - Object.defineProperty(DotObject, prop, { - get: function () { - return dotDefault[prop] - }, - set: function (val) { - dotDefault[prop] = val - } - }) -}) - -DotObject._process = _process +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; -module.exports = DotObject +module.exports = ListCache; /***/ }), -/***/ 81205: +/***/ 80881: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var once = __nccwpck_require__(1223); +var getNative = __nccwpck_require__(24479), + root = __nccwpck_require__(89882); -var noop = function() {}; +/* Built-in method references that are verified to be native. */ +var Map = getNative(root, 'Map'); -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -}; +module.exports = Map; -var isChildProcess = function(stream) { - return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 -}; -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; +/***/ }), - callback = once(callback || noop); +/***/ 80938: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); - var cancelled = false; +var mapCacheClear = __nccwpck_require__(1610), + mapCacheDelete = __nccwpck_require__(56657), + mapCacheGet = __nccwpck_require__(81372), + mapCacheHas = __nccwpck_require__(40609), + mapCacheSet = __nccwpck_require__(45582); - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; - var onfinish = function() { - writable = false; - if (!readable) callback.call(stream); - }; - - var onend = function() { - readable = false; - if (!writable) callback.call(stream); - }; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} - var onexit = function(exitCode) { - callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); - }; +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; - var onerror = function(err) { - callback.call(stream, err); - }; +module.exports = MapCache; - var onclose = function() { - process.nextTick(onclosenexttick); - }; - var onclosenexttick = function() { - if (cancelled) return; - if (readable && !(rs && (rs.ended && !rs.destroyed))) return callback.call(stream, new Error('premature close')); - if (writable && !(ws && (ws.ended && !ws.destroyed))) return callback.call(stream, new Error('premature close')); - }; +/***/ }), - var onrequest = function() { - stream.req.on('finish', onfinish); - }; +/***/ 35793: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } +var getNative = __nccwpck_require__(24479), + root = __nccwpck_require__(89882); - if (isChildProcess(stream)) stream.on('exit', onexit); - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', onerror); - stream.on('close', onclose); - - return function() { - cancelled = true; - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('exit', onexit); - stream.removeListener('end', onend); - stream.removeListener('error', onerror); - stream.removeListener('close', onclose); - }; -}; +/* Built-in method references that are verified to be native. */ +var Set = getNative(root, 'Set'); -module.exports = eos; +module.exports = Set; /***/ }), -/***/ 64334: +/***/ 72158: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var CombinedStream = __nccwpck_require__(85443); -var util = __nccwpck_require__(73837); -var path = __nccwpck_require__(71017); -var http = __nccwpck_require__(13685); -var https = __nccwpck_require__(95687); -var parseUrl = (__nccwpck_require__(57310).parse); -var fs = __nccwpck_require__(57147); -var Stream = (__nccwpck_require__(12781).Stream); -var mime = __nccwpck_require__(43583); -var asynckit = __nccwpck_require__(14812); -var populate = __nccwpck_require__(17142); - -// Public API -module.exports = FormData; - -// make it a Stream -util.inherits(FormData, CombinedStream); +var MapCache = __nccwpck_require__(80938), + setCacheAdd = __nccwpck_require__(16895), + setCacheHas = __nccwpck_require__(60804); /** - * Create readable "multipart/form-data" streams. - * Can be used to submit forms - * and file uploads to other web applications. * + * Creates an array cache object to store unique values. + * + * @private * @constructor - * @param {Object} options - Properties to be added/overriden for FormData and CombinedStream + * @param {Array} [values] The values to cache. */ -function FormData(options) { - if (!(this instanceof FormData)) { - return new FormData(options); - } - - this._overheadLength = 0; - this._valueLength = 0; - this._valuesToMeasure = []; - - CombinedStream.call(this); +function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; - options = options || {}; - for (var option in options) { - this[option] = options[option]; + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); } } -FormData.LINE_BREAK = '\r\n'; -FormData.DEFAULT_CONTENT_TYPE = 'application/octet-stream'; +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; +SetCache.prototype.has = setCacheHas; -FormData.prototype.append = function(field, value, options) { +module.exports = SetCache; - options = options || {}; - // allow filename as single option - if (typeof options == 'string') { - options = {filename: options}; - } +/***/ }), - var append = CombinedStream.prototype.append.bind(this); +/***/ 19213: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // all that streamy business can't handle numbers - if (typeof value == 'number') { - value = '' + value; - } +var root = __nccwpck_require__(89882); - // https://github.com/felixge/node-form-data/issues/38 - if (util.isArray(value)) { - // Please convert your array into string - // the way web server expects it - this._error(new Error('Arrays are not supported.')); - return; - } +/** Built-in value references. */ +var Symbol = root.Symbol; - var header = this._multiPartHeader(field, value, options); - var footer = this._multiPartFooter(); +module.exports = Symbol; - append(header); - append(value); - append(footer); - // pass along options.knownLength - this._trackLength(header, value, options); -}; +/***/ }), -FormData.prototype._trackLength = function(header, value, options) { - var valueLength = 0; +/***/ 69647: +/***/ ((module) => { - // used w/ getLengthSync(), when length is known. - // e.g. for streaming directly from a remote server, - // w/ a known file a size, and not wanting to wait for - // incoming file to finish to get its size. - if (options.knownLength != null) { - valueLength += +options.knownLength; - } else if (Buffer.isBuffer(value)) { - valueLength = value.length; - } else if (typeof value === 'string') { - valueLength = Buffer.byteLength(value); +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); } + return func.apply(thisArg, args); +} - this._valueLength += valueLength; +module.exports = apply; - // @check why add CRLF? does this account for custom/multiple CRLFs? - this._overheadLength += - Buffer.byteLength(header) + - FormData.LINE_BREAK.length; - // empty or either doesn't have path or not an http response or not a stream - if (!value || ( !value.path && !(value.readable && value.hasOwnProperty('httpVersion')) && !(value instanceof Stream))) { - return; - } +/***/ }), - // no need to bother with the length - if (!options.knownLength) { - this._valuesToMeasure.push(value); - } -}; +/***/ 17183: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -FormData.prototype._lengthRetriever = function(value, callback) { +var baseIndexOf = __nccwpck_require__(25425); - if (value.hasOwnProperty('fd')) { +/** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; +} - // take read range into a account - // `end` = Infinity –> read file till the end - // - // TODO: Looks like there is bug in Node fs.createReadStream - // it doesn't respect `end` options without `start` options - // Fix it when node fixes it. - // https://github.com/joyent/node/issues/7819 - if (value.end != undefined && value.end != Infinity && value.start != undefined) { +module.exports = arrayIncludes; - // when end specified - // no need to calculate range - // inclusive, starts with 0 - callback(null, value.end + 1 - (value.start ? value.start : 0)); - // not that fast snoopy - } else { - // still need to fetch file size from fs - fs.stat(value.path, function(err, stat) { +/***/ }), - var fileSize; +/***/ 86732: +/***/ ((module) => { - if (err) { - callback(err); - return; - } +/** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; - // update final size based on the range options - fileSize = stat.size - (value.start ? value.start : 0); - callback(null, fileSize); - }); + while (++index < length) { + if (comparator(value, array[index])) { + return true; } - - // or http response - } else if (value.hasOwnProperty('httpVersion')) { - callback(null, +value.headers['content-length']); - - // or request stream http://github.com/mikeal/request - } else if (value.hasOwnProperty('httpModule')) { - // wait till response come back - value.on('response', function(response) { - value.pause(); - callback(null, +response.headers['content-length']); - }); - value.resume(); - - // something else - } else { - callback('Unknown stream'); } -}; + return false; +} -FormData.prototype._multiPartHeader = function(field, value, options) { - // custom header specified (as string)? - // it becomes responsible for boundary - // (e.g. to handle extra CRLFs on .NET servers) - if (typeof options.header == 'string') { - return options.header; - } +module.exports = arrayIncludesWith; - var contentDisposition = this._getContentDisposition(value, options); - var contentType = this._getContentType(value, options); - var contents = ''; - var headers = { - // add custom disposition as third element or keep it two elements if not - 'Content-Disposition': ['form-data', 'name="' + field + '"'].concat(contentDisposition || []), - // if no content type. allow it to be empty array - 'Content-Type': [].concat(contentType || []) - }; +/***/ }), - // allow custom headers. - if (typeof options.header == 'object') { - populate(headers, options.header); - } +/***/ 32237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var header; - for (var prop in headers) { - if (!headers.hasOwnProperty(prop)) continue; - header = headers[prop]; +var baseTimes = __nccwpck_require__(37765), + isArguments = __nccwpck_require__(78495), + isArray = __nccwpck_require__(44869), + isBuffer = __nccwpck_require__(74190), + isIndex = __nccwpck_require__(32936), + isTypedArray = __nccwpck_require__(2496); - // skip nullish headers. - if (header == null) { - continue; - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - // convert all headers to arrays. - if (!Array.isArray(header)) { - header = [header]; - } +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - // add non-empty headers. - if (header.length) { - contents += prop + ': ' + header.join('; ') + FormData.LINE_BREAK; +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); } } + return result; +} - return '--' + this.getBoundary() + FormData.LINE_BREAK + contents + FormData.LINE_BREAK; -}; - -FormData.prototype._getContentDisposition = function(value, options) { +module.exports = arrayLikeKeys; - var filename - , contentDisposition - ; - if (typeof options.filepath === 'string') { - // custom filepath for relative paths - filename = path.normalize(options.filepath).replace(/\\/g, '/'); - } else if (options.filename || value.name || value.path) { - // custom filename take precedence - // formidable and the browser add a name property - // fs- and request- streams have path property - filename = path.basename(options.filename || value.name || value.path); - } else if (value.readable && value.hasOwnProperty('httpVersion')) { - // or try http response - filename = path.basename(value.client._httpMessage.path || ''); - } +/***/ }), - if (filename) { - contentDisposition = 'filename="' + filename + '"'; - } +/***/ 94356: +/***/ ((module) => { - return contentDisposition; -}; +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); -FormData.prototype._getContentType = function(value, options) { + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} - // use custom content-type above all - var contentType = options.contentType; +module.exports = arrayMap; - // or try `name` from formidable, browser - if (!contentType && value.name) { - contentType = mime.lookup(value.name); - } - // or try `path` from fs-, request- streams - if (!contentType && value.path) { - contentType = mime.lookup(value.path); - } +/***/ }), - // or if it's http-reponse - if (!contentType && value.readable && value.hasOwnProperty('httpVersion')) { - contentType = value.headers['content-type']; - } +/***/ 60082: +/***/ ((module) => { - // or guess it from the filepath or filename - if (!contentType && (options.filepath || options.filename)) { - contentType = mime.lookup(options.filepath || options.filename); - } +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; - // fallback to the default content type if `value` is not simple value - if (!contentType && typeof value == 'object') { - contentType = FormData.DEFAULT_CONTENT_TYPE; + while (++index < length) { + array[offset + index] = values[index]; } + return array; +} - return contentType; -}; - -FormData.prototype._multiPartFooter = function() { - return function(next) { - var footer = FormData.LINE_BREAK; +module.exports = arrayPush; - var lastPart = (this._streams.length === 0); - if (lastPart) { - footer += this._lastBoundary(); - } - next(footer); - }.bind(this); -}; +/***/ }), -FormData.prototype._lastBoundary = function() { - return '--' + this.getBoundary() + '--' + FormData.LINE_BREAK; -}; +/***/ 96752: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -FormData.prototype.getHeaders = function(userHeaders) { - var header; - var formHeaders = { - 'content-type': 'multipart/form-data; boundary=' + this.getBoundary() - }; +var eq = __nccwpck_require__(61901); - for (header in userHeaders) { - if (userHeaders.hasOwnProperty(header)) { - formHeaders[header.toLowerCase()] = userHeaders[header]; +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; } } + return -1; +} - return formHeaders; -}; +module.exports = assocIndexOf; -FormData.prototype.setBoundary = function(boundary) { - this._boundary = boundary; -}; -FormData.prototype.getBoundary = function() { - if (!this._boundary) { - this._generateBoundary(); - } +/***/ }), - return this._boundary; -}; +/***/ 21259: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -FormData.prototype.getBuffer = function() { - var dataBuffer = new Buffer.alloc( 0 ); - var boundary = this.getBoundary(); +var SetCache = __nccwpck_require__(72158), + arrayIncludes = __nccwpck_require__(17183), + arrayIncludesWith = __nccwpck_require__(86732), + arrayMap = __nccwpck_require__(94356), + baseUnary = __nccwpck_require__(59258), + cacheHas = __nccwpck_require__(72675); - // Create the form content. Add Line breaks to the end of data. - for (var i = 0, len = this._streams.length; i < len; i++) { - if (typeof this._streams[i] !== 'function') { +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; - // Add content to the buffer. - if(Buffer.isBuffer(this._streams[i])) { - dataBuffer = Buffer.concat( [dataBuffer, this._streams[i]]); - }else { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(this._streams[i])]); - } +/** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ +function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; - // Add break after content. - if (typeof this._streams[i] !== 'string' || this._streams[i].substring( 2, boundary.length + 2 ) !== boundary) { - dataBuffer = Buffer.concat( [dataBuffer, Buffer.from(FormData.LINE_BREAK)] ); + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); } } + return result; +} - // Add the footer and return the Buffer object. - return Buffer.concat( [dataBuffer, Buffer.from(this._lastBoundary())] ); -}; - -FormData.prototype._generateBoundary = function() { - // This generates a 50 character boundary similar to those used by Firefox. - // They are optimized for boyer-moore parsing. - var boundary = '--------------------------'; - for (var i = 0; i < 24; i++) { - boundary += Math.floor(Math.random() * 10).toString(16); - } +module.exports = baseDifference; - this._boundary = boundary; -}; -// Note: getLengthSync DOESN'T calculate streams length -// As workaround one can calculate file size manually -// and add it as knownLength option -FormData.prototype.getLengthSync = function() { - var knownLength = this._overheadLength + this._valueLength; +/***/ }), - // Don't get confused, there are 3 "internal" streams for each keyval pair - // so it basically checks if there is any value added to the form - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } +/***/ 87265: +/***/ ((module) => { - // https://github.com/form-data/form-data/issues/40 - if (!this.hasKnownLength()) { - // Some async length retrievers are present - // therefore synchronous length calculation is false. - // Please use getLength(callback) to get proper length - this._error(new Error('Cannot calculate proper length in synchronous way.')); +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } } + return -1; +} - return knownLength; -}; +module.exports = baseFindIndex; -// Public API to check if length of added values is known -// https://github.com/form-data/form-data/issues/196 -// https://github.com/form-data/form-data/issues/262 -FormData.prototype.hasKnownLength = function() { - var hasKnownLength = true; - if (this._valuesToMeasure.length) { - hasKnownLength = false; - } +/***/ }), - return hasKnownLength; -}; +/***/ 69588: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -FormData.prototype.getLength = function(cb) { - var knownLength = this._overheadLength + this._valueLength; +var arrayPush = __nccwpck_require__(60082), + isFlattenable = __nccwpck_require__(9299); - if (this._streams.length) { - knownLength += this._lastBoundary().length; - } +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; - if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); - return; - } + predicate || (predicate = isFlattenable); + result || (result = []); - asynckit.parallel(this._valuesToMeasure, this._lengthRetriever, function(err, values) { - if (err) { - cb(err); - return; + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; } + } + return result; +} - values.forEach(function(length) { - knownLength += length; - }); +module.exports = baseFlatten; - cb(null, knownLength); - }); -}; -FormData.prototype.submit = function(params, cb) { - var request - , options - , defaults = {method: 'post'} - ; +/***/ }), - // parse provided url if it's string - // or treat it as options object - if (typeof params == 'string') { +/***/ 97497: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - params = parseUrl(params); - options = populate({ - port: params.port, - path: params.pathname, - host: params.hostname, - protocol: params.protocol - }, defaults); +var Symbol = __nccwpck_require__(19213), + getRawTag = __nccwpck_require__(80923), + objectToString = __nccwpck_require__(14200); - // use custom params - } else { +/** `Object#toString` result references. */ +var nullTag = '[object Null]', + undefinedTag = '[object Undefined]'; - options = populate(params, defaults); - // if no port provided use default one - if (!options.port) { - options.port = options.protocol == 'https:' ? 443 : 80; - } +/** Built-in value references. */ +var symToStringTag = Symbol ? Symbol.toStringTag : undefined; + +/** + * The base implementation of `getTag` without fallbacks for buggy environments. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; } + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); +} - // put that good code in getHeaders to some use - options.headers = this.getHeaders(params.headers); +module.exports = baseGetTag; - // https if specified, fallback to http in any other case - if (options.protocol == 'https:') { - request = https.request(options); - } else { - request = http.request(options); - } - // get content length and fire away - this.getLength(function(err, length) { - if (err && err !== 'Unknown stream') { - this._error(err); - return; - } +/***/ }), - // add content length - if (length) { - request.setHeader('Content-Length', length); - } +/***/ 25425: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this.pipe(request); - if (cb) { - var onResponse; +var baseFindIndex = __nccwpck_require__(87265), + baseIsNaN = __nccwpck_require__(18048), + strictIndexOf = __nccwpck_require__(58868); - var callback = function (error, responce) { - request.removeListener('error', callback); - request.removeListener('response', onResponse); +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); +} - return cb.call(this, error, responce); - }; +module.exports = baseIndexOf; - onResponse = callback.bind(this, null); - request.on('error', callback); - request.on('response', onResponse); - } - }.bind(this)); +/***/ }), - return request; -}; +/***/ 92177: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -FormData.prototype._error = function(err) { - if (!this.error) { - this.error = err; - this.pause(); - this.emit('error', err); - } -}; +var baseGetTag = __nccwpck_require__(97497), + isObjectLike = __nccwpck_require__(85926); -FormData.prototype.toString = function () { - return '[object FormData]'; -}; +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]'; + +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ +function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; +} + +module.exports = baseIsArguments; /***/ }), -/***/ 17142: +/***/ 18048: /***/ ((module) => { -// populates missing values -module.exports = function(dst, src) { - - Object.keys(src).forEach(function(prop) - { - dst[prop] = dst[prop] || src[prop]; - }); +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} - return dst; -}; +module.exports = baseIsNaN; /***/ }), -/***/ 73186: +/***/ 50411: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -module.exports = (__nccwpck_require__(57147).constants) || __nccwpck_require__(22057) +var isFunction = __nccwpck_require__(17799), + isMasked = __nccwpck_require__(29058), + isObject = __nccwpck_require__(33334), + toSource = __nccwpck_require__(96928); +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; -/***/ }), +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; -/***/ 46863: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto = Object.prototype; -module.exports = realpath -realpath.realpath = realpath -realpath.sync = realpathSync -realpath.realpathSync = realpathSync -realpath.monkeypatch = monkeypatch -realpath.unmonkeypatch = unmonkeypatch +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; -var fs = __nccwpck_require__(57147) -var origRealpath = fs.realpath -var origRealpathSync = fs.realpathSync - -var version = process.version -var ok = /^v[0-5]\./.test(version) -var old = __nccwpck_require__(71734) - -function newError (er) { - return er && er.syscall === 'realpath' && ( - er.code === 'ELOOP' || - er.code === 'ENOMEM' || - er.code === 'ENAMETOOLONG' - ) -} +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; -function realpath (p, cache, cb) { - if (ok) { - return origRealpath(p, cache, cb) - } +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); - if (typeof cache === 'function') { - cb = cache - cache = null +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; } - origRealpath(p, cache, function (er, result) { - if (newError(er)) { - old.realpath(p, cache, cb) - } else { - cb(er, result) - } - }) + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); } -function realpathSync (p, cache) { - if (ok) { - return origRealpathSync(p, cache) - } +module.exports = baseIsNative; - try { - return origRealpathSync(p, cache) - } catch (er) { - if (newError(er)) { - return old.realpathSync(p, cache) - } else { - throw er - } - } -} -function monkeypatch () { - fs.realpath = realpath - fs.realpathSync = realpathSync -} +/***/ }), -function unmonkeypatch () { - fs.realpath = origRealpath - fs.realpathSync = origRealpathSync -} +/***/ 11528: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var baseGetTag = __nccwpck_require__(97497), + isLength = __nccwpck_require__(64530), + isObjectLike = __nccwpck_require__(85926); -/***/ }), +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + errorTag = '[object Error]', + funcTag = '[object Function]', + mapTag = '[object Map]', + numberTag = '[object Number]', + objectTag = '[object Object]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + weakMapTag = '[object WeakMap]'; + +var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = +typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = +typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = +typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = +typedArrayTags[uint32Tag] = true; +typedArrayTags[argsTag] = typedArrayTags[arrayTag] = +typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = +typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = +typedArrayTags[errorTag] = typedArrayTags[funcTag] = +typedArrayTags[mapTag] = typedArrayTags[numberTag] = +typedArrayTags[objectTag] = typedArrayTags[regexpTag] = +typedArrayTags[setTag] = typedArrayTags[stringTag] = +typedArrayTags[weakMapTag] = false; + +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ +function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; +} -/***/ 71734: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +module.exports = baseIsTypedArray; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -var pathModule = __nccwpck_require__(71017); -var isWindows = process.platform === 'win32'; -var fs = __nccwpck_require__(57147); +/***/ }), -// JavaScript implementation of realpath, ported from node pre-v6 +/***/ 90297: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var DEBUG = process.env.NODE_DEBUG && /fs/.test(process.env.NODE_DEBUG); +var isObject = __nccwpck_require__(33334), + isPrototype = __nccwpck_require__(60010), + nativeKeysIn = __nccwpck_require__(45383); -function rethrow() { - // Only enable in debug mode. A backtrace uses ~1000 bytes of heap space and - // is fairly slow to generate. - var callback; - if (DEBUG) { - var backtrace = new Error; - callback = debugCallback; - } else - callback = missingCallback; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - return callback; +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - function debugCallback(err) { - if (err) { - backtrace.message = err.message; - err = backtrace; - missingCallback(err); - } +/** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); } + var isProto = isPrototype(object), + result = []; - function missingCallback(err) { - if (err) { - if (process.throwDeprecation) - throw err; // Forgot a callback but don't know where? Use NODE_DEBUG=fs - else if (!process.noDeprecation) { - var msg = 'fs: missing callback ' + (err.stack || err.message); - if (process.traceDeprecation) - console.trace(msg); - else - console.error(msg); - } + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); } } + return result; } -function maybeCallback(cb) { - return typeof cb === 'function' ? cb : rethrow(); -} +module.exports = baseKeysIn; -var normalize = pathModule.normalize; -// Regexp that finds the next partion of a (partial) path -// result is [base_with_slash, base], e.g. ['somedir/', 'somedir'] -if (isWindows) { - var nextPartRe = /(.*?)(?:[\/\\]+|$)/g; -} else { - var nextPartRe = /(.*?)(?:[\/]+|$)/g; -} +/***/ }), -// Regex to find the device root, including trailing slash. E.g. 'c:\\'. -if (isWindows) { - var splitRootRe = /^(?:[a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/][^\\\/]+)?[\\\/]*/; -} else { - var splitRootRe = /^[\/]*/; +/***/ 42936: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var identity = __nccwpck_require__(57822), + overRest = __nccwpck_require__(12417), + setToString = __nccwpck_require__(98416); + +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); } -exports.realpathSync = function realpathSync(p, cache) { - // make p is absolute - p = pathModule.resolve(p); +module.exports = baseRest; - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return cache[p]; - } - var original = p, - seenLinks = {}, - knownHard = {}; +/***/ }), - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; +/***/ 40979: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - start(); +var constant = __nccwpck_require__(35946), + defineProperty = __nccwpck_require__(416), + identity = __nccwpck_require__(57822); - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; +/** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); +}; - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstatSync(base); - knownHard[base] = true; - } - } +module.exports = baseSetToString; - // walk down the path, swapping out linked pathparts for their real - // values - // NB: p.length changes. - while (pos < p.length) { - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - continue; - } +/***/ }), - var resolvedLink; - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // some known symbolic link. no need to stat again. - resolvedLink = cache[base]; - } else { - var stat = fs.lstatSync(base); - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - continue; - } +/***/ 37765: +/***/ ((module) => { - // read the link if it wasn't read before - // dev/ino always return 0 on windows, so skip the check. - var linkTarget = null; - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - linkTarget = seenLinks[id]; - } - } - if (linkTarget === null) { - fs.statSync(base); - linkTarget = fs.readlinkSync(base); - } - resolvedLink = pathModule.resolve(previous, linkTarget); - // track this, if given a cache. - if (cache) cache[base] = resolvedLink; - if (!isWindows) seenLinks[id] = linkTarget; - } +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); + while (++index < n) { + result[index] = iteratee(index); } + return result; +} - if (cache) cache[original] = p; +module.exports = baseTimes; - return p; -}; +/***/ }), -exports.realpath = function realpath(p, cache, cb) { - if (typeof cb !== 'function') { - cb = maybeCallback(cache); - cache = null; - } - - // make p is absolute - p = pathModule.resolve(p); - - if (cache && Object.prototype.hasOwnProperty.call(cache, p)) { - return process.nextTick(cb.bind(null, null, cache[p])); - } - - var original = p, - seenLinks = {}, - knownHard = {}; - - // current character position in p - var pos; - // the partial path so far, including a trailing slash if any - var current; - // the partial path without a trailing slash (except when pointing at a root) - var base; - // the partial path scanned in the previous round, with slash - var previous; - - start(); - - function start() { - // Skip over roots - var m = splitRootRe.exec(p); - pos = m[0].length; - current = m[0]; - base = m[0]; - previous = ''; - - // On windows, check that the root exists. On unix there is no need. - if (isWindows && !knownHard[base]) { - fs.lstat(base, function(err) { - if (err) return cb(err); - knownHard[base] = true; - LOOP(); - }); - } else { - process.nextTick(LOOP); - } - } +/***/ 59258: +/***/ ((module) => { - // walk down the path, swapping out linked pathparts for their real - // values - function LOOP() { - // stop if scanned past end of path - if (pos >= p.length) { - if (cache) cache[original] = p; - return cb(null, p); - } +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; +} - // find the next part - nextPartRe.lastIndex = pos; - var result = nextPartRe.exec(p); - previous = current; - current += result[0]; - base = previous + result[1]; - pos = nextPartRe.lastIndex; +module.exports = baseUnary; - // continue if not a symlink - if (knownHard[base] || (cache && cache[base] === base)) { - return process.nextTick(LOOP); - } - if (cache && Object.prototype.hasOwnProperty.call(cache, base)) { - // known symbolic link. no need to stat again. - return gotResolvedLink(cache[base]); - } +/***/ }), - return fs.lstat(base, gotStat); - } +/***/ 19036: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function gotStat(err, stat) { - if (err) return cb(err); +var SetCache = __nccwpck_require__(72158), + arrayIncludes = __nccwpck_require__(17183), + arrayIncludesWith = __nccwpck_require__(86732), + cacheHas = __nccwpck_require__(72675), + createSet = __nccwpck_require__(46505), + setToArray = __nccwpck_require__(49553); - // if not a symlink, skip to the next path part - if (!stat.isSymbolicLink()) { - knownHard[base] = true; - if (cache) cache[base] = base; - return process.nextTick(LOOP); - } +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE = 200; - // stat & read the link if not read before - // call gotTarget as soon as the link target is known - // dev/ino always return 0 on windows, so skip the check. - if (!isWindows) { - var id = stat.dev.toString(32) + ':' + stat.ino.toString(32); - if (seenLinks.hasOwnProperty(id)) { - return gotTarget(null, seenLinks[id], base); - } - } - fs.stat(base, function(err) { - if (err) return cb(err); +/** + * The base implementation of `_.uniqBy` without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ +function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; - fs.readlink(base, function(err, target) { - if (!isWindows) seenLinks[id] = target; - gotTarget(err, target); - }); - }); + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; } - - function gotTarget(err, target, base) { - if (err) return cb(err); - - var resolvedLink = pathModule.resolve(previous, target); - if (cache) cache[base] = resolvedLink; - gotResolvedLink(resolvedLink); + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; - function gotResolvedLink(resolvedLink) { - // resolve the link, then start over - p = pathModule.resolve(resolvedLink, p.slice(pos)); - start(); + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } } -}; + return result; +} + +module.exports = baseUniq; /***/ }), -/***/ 67356: +/***/ 72675: /***/ ((module) => { -"use strict"; +/** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function cacheHas(cache, key) { + return cache.has(key); +} +module.exports = cacheHas; -module.exports = clone -var getPrototypeOf = Object.getPrototypeOf || function (obj) { - return obj.__proto__ -} +/***/ }), -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj +/***/ 78380: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (obj instanceof Object) - var copy = { __proto__: getPrototypeOf(obj) } - else - var copy = Object.create(null) +var root = __nccwpck_require__(89882); - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; - return copy -} +module.exports = coreJsData; /***/ }), -/***/ 77758: +/***/ 46505: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var fs = __nccwpck_require__(57147) -var polyfills = __nccwpck_require__(20263) -var legacy = __nccwpck_require__(73086) -var clone = __nccwpck_require__(67356) - -var util = __nccwpck_require__(73837) +var Set = __nccwpck_require__(35793), + noop = __nccwpck_require__(51901), + setToArray = __nccwpck_require__(49553); -/* istanbul ignore next - node 0.x polyfill */ -var gracefulQueue -var previousSymbol +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0; -/* istanbul ignore else - node 0.x polyfill */ -if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { - gracefulQueue = Symbol.for('graceful-fs.queue') - // This is used in testing by future versions - previousSymbol = Symbol.for('graceful-fs.previous') -} else { - gracefulQueue = '___graceful-fs.queue' - previousSymbol = '___graceful-fs.previous' -} +/** + * Creates a set object of `values`. + * + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ +var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); +}; -function noop () {} +module.exports = createSet; -function publishQueue(context, queue) { - Object.defineProperty(context, gracefulQueue, { - get: function() { - return queue - } - }) -} -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } +/***/ }), -// Once time initialization -if (!fs[gracefulQueue]) { - // This queue can be shared by multiple loaded instances - var queue = global[gracefulQueue] || [] - publishQueue(fs, queue) +/***/ 416: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Patch fs.close/closeSync to shared queue version, because we need - // to retry() whenever a close happens *anywhere* in the program. - // This is essential when multiple graceful-fs instances are - // in play at the same time. - fs.close = (function (fs$close) { - function close (fd, cb) { - return fs$close.call(fs, fd, function (err) { - // This function uses the graceful-fs shared queue - if (!err) { - resetQueue() - } +var getNative = __nccwpck_require__(24479); - if (typeof cb === 'function') - cb.apply(this, arguments) - }) - } +var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} +}()); - Object.defineProperty(close, previousSymbol, { - value: fs$close - }) - return close - })(fs.close) +module.exports = defineProperty; - fs.closeSync = (function (fs$closeSync) { - function closeSync (fd) { - // This function uses the graceful-fs shared queue - fs$closeSync.apply(fs, arguments) - resetQueue() - } - Object.defineProperty(closeSync, previousSymbol, { - value: fs$closeSync - }) - return closeSync - })(fs.closeSync) +/***/ }), - if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(fs[gracefulQueue]) - __nccwpck_require__(39491).equal(fs[gracefulQueue].length, 0) - }) - } -} +/***/ 52085: +/***/ ((module) => { -if (!global[gracefulQueue]) { - publishQueue(global, fs[gracefulQueue]); -} +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; -} +module.exports = freeGlobal; -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null +/***/ }), - return go$readFile(path, options, cb) +/***/ 69980: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function go$readFile (path, options, cb, startTime) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } +var isKeyable = __nccwpck_require__(13308); - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; +} - return go$writeFile(path, data, options, cb) +module.exports = getMapData; - function go$writeFile (path, data, options, cb, startTime) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null +/***/ }), - return go$appendFile(path, data, options, cb) +/***/ 24479: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function go$appendFile (path, data, options, cb, startTime) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } +var baseIsNative = __nccwpck_require__(50411), + getValue = __nccwpck_require__(13542); - var fs$copyFile = fs.copyFile - if (fs$copyFile) - fs.copyFile = copyFile - function copyFile (src, dest, flags, cb) { - if (typeof flags === 'function') { - cb = flags - flags = 0 - } - return go$copyFile(src, dest, flags, cb) +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} - function go$copyFile (src, dest, flags, cb, startTime) { - return fs$copyFile(src, dest, flags, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } +module.exports = getNative; - var fs$readdir = fs.readdir - fs.readdir = readdir - var noReaddirOptionVersions = /^v[0-5]\./ - function readdir (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null - var go$readdir = noReaddirOptionVersions.test(process.version) - ? function go$readdir (path, options, cb, startTime) { - return fs$readdir(path, fs$readdirCallback( - path, options, cb, startTime - )) - } - : function go$readdir (path, options, cb, startTime) { - return fs$readdir(path, options, fs$readdirCallback( - path, options, cb, startTime - )) - } +/***/ }), - return go$readdir(path, options, cb) +/***/ 86271: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function fs$readdirCallback (path, options, cb, startTime) { - return function (err, files) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([ - go$readdir, - [path, options, cb], - err, - startTime || Date.now(), - Date.now() - ]) - else { - if (files && files.sort) - files.sort() +var overArg = __nccwpck_require__(6320); - if (typeof cb === 'function') - cb.call(this, err, files) - } - } - } - } +/** Built-in value references. */ +var getPrototype = overArg(Object.getPrototypeOf, Object); - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream - } +module.exports = getPrototype; - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - } - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } +/***/ }), - Object.defineProperty(fs, 'ReadStream', { - get: function () { - return ReadStream - }, - set: function (val) { - ReadStream = val - }, - enumerable: true, - configurable: true - }) - Object.defineProperty(fs, 'WriteStream', { - get: function () { - return WriteStream - }, - set: function (val) { - WriteStream = val - }, - enumerable: true, - configurable: true - }) +/***/ 80923: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // legacy names - var FileReadStream = ReadStream - Object.defineProperty(fs, 'FileReadStream', { - get: function () { - return FileReadStream - }, - set: function (val) { - FileReadStream = val - }, - enumerable: true, - configurable: true - }) - var FileWriteStream = WriteStream - Object.defineProperty(fs, 'FileWriteStream', { - get: function () { - return FileWriteStream - }, - set: function (val) { - FileWriteStream = val - }, - enumerable: true, - configurable: true - }) +var Symbol = __nccwpck_require__(19213); - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } +/** Built-in value references. */ +var symToStringTag = Symbol ? Symbol.toStringTag : undefined; - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } +/** + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. + */ +function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; - function createReadStream (path, options) { - return new fs.ReadStream(path, options) + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } } + return result; +} - function createWriteStream (path, options) { - return new fs.WriteStream(path, options) - } +module.exports = getRawTag; - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null - return go$open(path, flags, mode, cb) +/***/ }), - function go$open (path, flags, mode, cb, startTime) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - } - }) - } - } +/***/ 13542: +/***/ ((module) => { - return fs +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; } -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - fs[gracefulQueue].push(elem) - retry() -} +module.exports = getValue; -// keep track of the timeout between retry() calls -var retryTimer -// reset the startTime and lastTime to now -// this resets the start of the 60 second overall timeout as well as the -// delay between attempts so that we'll retry these jobs sooner -function resetQueue () { - var now = Date.now() - for (var i = 0; i < fs[gracefulQueue].length; ++i) { - // entries that are only a length of 2 are from an older version, don't - // bother modifying those since they'll be retried anyway. - if (fs[gracefulQueue][i].length > 2) { - fs[gracefulQueue][i][3] = now // startTime - fs[gracefulQueue][i][4] = now // lastTime - } - } - // call retry to make sure we're actively processing the queue - retry() +/***/ }), + +/***/ 11789: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var nativeCreate = __nccwpck_require__(93041); + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; } -function retry () { - // clear the timer and remove it to help prevent unintended concurrency - clearTimeout(retryTimer) - retryTimer = undefined +module.exports = hashClear; - if (fs[gracefulQueue].length === 0) - return - var elem = fs[gracefulQueue].shift() - var fn = elem[0] - var args = elem[1] - // these items may be unset if they were added by an older graceful-fs - var err = elem[2] - var startTime = elem[3] - var lastTime = elem[4] +/***/ }), - // if we don't have a startTime we have no way of knowing if we've waited - // long enough, so go ahead and retry this item now - if (startTime === undefined) { - debug('RETRY', fn.name, args) - fn.apply(null, args) - } else if (Date.now() - startTime >= 60000) { - // it's been more than 60 seconds total, bail now - debug('TIMEOUT', fn.name, args) - var cb = args.pop() - if (typeof cb === 'function') - cb.call(null, err) - } else { - // the amount of time between the last attempt and right now - var sinceAttempt = Date.now() - lastTime - // the amount of time between when we first tried, and when we last tried - // rounded up to at least 1 - var sinceStart = Math.max(lastTime - startTime, 1) - // backoff. wait longer than the total time we've been retrying, but only - // up to a maximum of 100ms - var desiredDelay = Math.min(sinceStart * 1.2, 100) - // it's been long enough since the last retry, do it again - if (sinceAttempt >= desiredDelay) { - debug('RETRY', fn.name, args) - fn.apply(null, args.concat([startTime])) - } else { - // if we can't do this job yet, push it to the end of the queue - // and let the next iteration check again - fs[gracefulQueue].push(elem) - } - } +/***/ 60712: +/***/ ((module) => { - // schedule our next run if one isn't already scheduled - if (retryTimer === undefined) { - retryTimer = setTimeout(retry, 0) - } +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; } +module.exports = hashDelete; + /***/ }), -/***/ 73086: +/***/ 45395: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var Stream = (__nccwpck_require__(12781).Stream) - -module.exports = legacy - -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } +var nativeCreate = __nccwpck_require__(93041); - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; - Stream.call(this); +/** Used for built-in method references. */ +var objectProto = Object.prototype; - var self = this; +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; +} - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; +module.exports = hashGet; - options = options || {}; - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } +/***/ }), - if (this.encoding) this.setEncoding(this.encoding); +/***/ 35232: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } +var nativeCreate = __nccwpck_require__(93041); - if (this.start > this.end) { - throw new Error('start must be <= end'); - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - this.pos = this.start; - } +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; - } +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); +} - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; - } +module.exports = hashHas; - self.fd = fd; - self.emit('open', fd); - self._read(); - }) - } - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); +/***/ }), - Stream.call(this); +/***/ 47320: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this.path = path; - this.fd = null; - this.writable = true; +var nativeCreate = __nccwpck_require__(93041); - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; - options = options || {}; +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; +} - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } +module.exports = hashSet; - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } - this.pos = this.start; - } +/***/ }), - this.busy = false; - this._queue = []; +/***/ 9299: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } - } +var Symbol = __nccwpck_require__(19213), + isArguments = __nccwpck_require__(78495), + isArray = __nccwpck_require__(44869); + +/** Built-in value references. */ +var spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ +function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); } +module.exports = isFlattenable; + /***/ }), -/***/ 20263: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 32936: +/***/ ((module) => { -var constants = __nccwpck_require__(22057) +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; -var origCwd = process.cwd -var cwd = null +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER : length; -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); } -try { - process.cwd() -} catch (er) {} -// This check is needed until node.js 12 is required -if (typeof process.chdir === 'function') { - var chdir = process.chdir - process.chdir = function (d) { - cwd = null - chdir.call(process, d) - } - if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) -} +module.exports = isIndex; -module.exports = patch -function patch (fs) { - // (re-)implement some things that are known busted or missing. +/***/ }), - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } +/***/ 8494: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) +var eq = __nccwpck_require__(61901), + isArrayLike = __nccwpck_require__(18017), + isIndex = __nccwpck_require__(32936), + isObject = __nccwpck_require__(33334); + +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; +} - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. +module.exports = isIterateeCall; - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) +/***/ }), - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) +/***/ 13308: +/***/ ((module) => { - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) +module.exports = isKeyable; - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) - // if lchmod/lchown do not exist, then make them no-ops - if (fs.chmod && !fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) - } - fs.lchmodSync = function () {} - } - if (fs.chown && !fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) - } - fs.lchownSync = function () {} - } +/***/ }), - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. +/***/ 29058: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = typeof fs.rename !== 'function' ? fs.rename - : (function (fs$rename) { - function rename (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - } - if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) - return rename - })(fs.rename) - } +var coreJsData = __nccwpck_require__(78380); - // if read() returns EAGAIN, then just try it again. - fs.read = typeof fs.read !== 'function' ? fs.read - : (function (fs$read) { - function read (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } - } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); - // This ensures `util.promisify` works as it does for native `fs.read`. - if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) - return read - })(fs.read) +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} - fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync - : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } - } - }})(fs.readSync) +module.exports = isMasked; - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) +/***/ }), - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } - } +/***/ 60010: +/***/ ((module) => { - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - } else if (fs.futimes) { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } - } + return value === proto; +} - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } +module.exports = isPrototype; - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } +/***/ }), - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } +/***/ 69792: +/***/ ((module) => { - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; + this.size = 0; +} - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options, cb) { - if (typeof options === 'function') { - cb = options - options = null - } - function callback (er, stats) { - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - if (cb) cb.apply(this, arguments) - } - return options ? orig.call(fs, target, options, callback) - : orig.call(fs, target, callback) - } - } +module.exports = listCacheClear; - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, options) { - var stats = options ? orig.call(fs, target, options) - : orig.call(fs, target) - if (stats) { - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - } - return stats; - } - } - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true +/***/ }), - if (er.code === "ENOSYS") - return true +/***/ 97716: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } +var assocIndexOf = __nccwpck_require__(96752); - return false +/** Used for built-in method references. */ +var arrayProto = Array.prototype; + +/** Built-in value references. */ +var splice = arrayProto.splice; + +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); } + --this.size; + return true; } +module.exports = listCacheDelete; + /***/ }), -/***/ 52492: +/***/ 45789: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var wrappy = __nccwpck_require__(62940) -var reqs = Object.create(null) -var once = __nccwpck_require__(1223) - -module.exports = wrappy(inflight) - -function inflight (key, cb) { - if (reqs[key]) { - reqs[key].push(cb) - return null - } else { - reqs[key] = [cb] - return makeres(key) - } -} +var assocIndexOf = __nccwpck_require__(96752); -function makeres (key) { - return once(function RES () { - var cbs = reqs[key] - var len = cbs.length - var args = slice(arguments) +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); - // XXX It's somewhat ambiguous whether a new callback added in this - // pass should be queued for later execution if something in the - // list of callbacks throws, or if it should just be discarded. - // However, it's such an edge case that it hardly matters, and either - // choice is likely as surprising as the other. - // As it happens, we do go ahead and schedule it for later execution. - try { - for (var i = 0; i < len; i++) { - cbs[i].apply(null, args) - } - } finally { - if (cbs.length > len) { - // added more in the interim. - // de-zalgo, just in case, but don't call again. - cbs.splice(0, len) - process.nextTick(function () { - RES.apply(null, args) - }) - } else { - delete reqs[key] - } - } - }) + return index < 0 ? undefined : data[index][1]; } -function slice (args) { - var length = args.length - var array = [] - - for (var i = 0; i < length; i++) array[i] = args[i] - return array -} +module.exports = listCacheGet; /***/ }), -/***/ 44124: +/***/ 59386: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -try { - var util = __nccwpck_require__(73837); - /* istanbul ignore next */ - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - /* istanbul ignore next */ - module.exports = __nccwpck_require__(8544); +var assocIndexOf = __nccwpck_require__(96752); + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; } +module.exports = listCacheHas; + /***/ }), -/***/ 8544: -/***/ ((module) => { +/***/ 17399: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }) - } - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - if (superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } +var assocIndexOf = __nccwpck_require__(96752); + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; } + return this; } +module.exports = listCacheSet; -/***/ }), - -/***/ 63287: -/***/ ((__unused_webpack_module, exports) => { -"use strict"; +/***/ }), +/***/ 1610: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); +var Hash = __nccwpck_require__(35902), + ListCache = __nccwpck_require__(96608), + Map = __nccwpck_require__(80881); -/*! - * is-plain-object +/** + * Removes all key-value entries from the map. * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. + * @private + * @name clear + * @memberOf MapCache */ - -function isObject(o) { - return Object.prototype.toString.call(o) === '[object Object]'; +function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; } -function isPlainObject(o) { - var ctor,prot; +module.exports = mapCacheClear; - if (isObject(o) === false) return false; - // If has modified constructor - ctor = o.constructor; - if (ctor === undefined) return true; +/***/ }), - // If has modified prototype - prot = ctor.prototype; - if (isObject(prot) === false) return false; +/***/ 56657: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } +var getMapData = __nccwpck_require__(69980); - // Most likely a plain Object - return true; +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; } -exports.isPlainObject = isPlainObject; +module.exports = mapCacheDelete; /***/ }), -/***/ 20893: -/***/ ((module) => { +/***/ 81372: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var toString = {}.toString; +var getMapData = __nccwpck_require__(69980); -module.exports = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; -}; +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} + +module.exports = mapCacheGet; /***/ }), -/***/ 84329: -/***/ ((module) => { +/***/ 40609: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -function e(e){this.message=e}e.prototype=new Error,e.prototype.name="InvalidCharacterError";var r="undefined"!=typeof window&&window.atob&&window.atob.bind(window)||function(r){var t=String(r).replace(/=+$/,"");if(t.length%4==1)throw new e("'atob' failed: The string to be decoded is not correctly encoded.");for(var n,o,a=0,i=0,c="";o=t.charAt(i++);~o&&(n=a%4?64*n+o:o,a++%4)?c+=String.fromCharCode(255&n>>(-2*a&6)):0)o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=".indexOf(o);return c};function t(e){var t=e.replace(/-/g,"+").replace(/_/g,"/");switch(t.length%4){case 0:break;case 2:t+="==";break;case 3:t+="=";break;default:throw"Illegal base64url string!"}try{return function(e){return decodeURIComponent(r(e).replace(/(.)/g,(function(e,r){var t=r.charCodeAt(0).toString(16).toUpperCase();return t.length<2&&(t="0"+t),"%"+t})))}(t)}catch(e){return r(t)}}function n(e){this.message=e}function o(e,r){if("string"!=typeof e)throw new n("Invalid token specified");var o=!0===(r=r||{}).header?0:1;try{return JSON.parse(t(e.split(".")[o]))}catch(e){throw new n("Invalid token specified: "+e.message)}}n.prototype=new Error,n.prototype.name="InvalidTokenError";const a=o;a.default=o,a.InvalidTokenError=n,module.exports=a; -//# sourceMappingURL=jwt-decode.cjs.js.map +var getMapData = __nccwpck_require__(69980); + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} + +module.exports = mapCacheHas; /***/ }), -/***/ 12084: +/***/ 45582: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var util = __nccwpck_require__(73837); -var PassThrough = __nccwpck_require__(27818); - -module.exports = { - Readable: Readable, - Writable: Writable -}; +var getMapData = __nccwpck_require__(69980); -util.inherits(Readable, PassThrough); -util.inherits(Writable, PassThrough); +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; -// Patch the given method of instance so that the callback -// is executed once, before the actual method is called the -// first time. -function beforeFirstCall(instance, method, callback) { - instance[method] = function() { - delete instance[method]; - callback.apply(this, arguments); - return this[method].apply(this, arguments); - }; + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; } -function Readable(fn, options) { - if (!(this instanceof Readable)) - return new Readable(fn, options); +module.exports = mapCacheSet; - PassThrough.call(this, options); - beforeFirstCall(this, '_read', function() { - var source = fn.call(this, options); - var emit = this.emit.bind(this, 'error'); - source.on('error', emit); - source.pipe(this); - }); +/***/ }), - this.emit('readable'); -} +/***/ 93041: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function Writable(fn, options) { - if (!(this instanceof Writable)) - return new Writable(fn, options); +var getNative = __nccwpck_require__(24479); - PassThrough.call(this, options); +/* Built-in method references that are verified to be native. */ +var nativeCreate = getNative(Object, 'create'); - beforeFirstCall(this, '_write', function() { - var destination = fn.call(this, options); - var emit = this.emit.bind(this, 'error'); - destination.on('error', emit); - this.pipe(destination); - }); +module.exports = nativeCreate; - this.emit('writable'); -} +/***/ }), +/***/ 45383: +/***/ ((module) => { -/***/ }), +/** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; +} -/***/ 5706: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +module.exports = nativeKeysIn; -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. +/***/ }), +/***/ 34643: +/***/ ((module, exports, __nccwpck_require__) => { +/* module decorator */ module = __nccwpck_require__.nmd(module); +var freeGlobal = __nccwpck_require__(52085); -/**/ +/** Detect free variable `exports`. */ +var freeExports = true && exports && !exports.nodeType && exports; -var pna = __nccwpck_require__(47810); -/**/ +/** Detect free variable `module`. */ +var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; -/**/ +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; -module.exports = Duplex; +/** Detect free variable `process` from Node.js. */ +var freeProcess = moduleExports && freeGlobal.process; -/**/ -var util = Object.create(__nccwpck_require__(95898)); -util.inherits = __nccwpck_require__(44124); -/**/ +/** Used to access faster Node.js helpers. */ +var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; -var Readable = __nccwpck_require__(99140); -var Writable = __nccwpck_require__(14960); + if (types) { + return types; + } -util.inherits(Duplex, Readable); + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} +}()); -{ - // avoid scope creep, the keys array can then be collected - var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; - } -} +module.exports = nodeUtil; -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); +/***/ }), - if (options && options.readable === false) this.readable = false; +/***/ 14200: +/***/ ((module) => { - if (options && options.writable === false) this.writable = false; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - this.allowHalfOpen = true; - if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto.toString; - this.once('end', onend); +/** + * Converts `value` to a string using `Object.prototype.toString`. + * + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + */ +function objectToString(value) { + return nativeObjectToString.call(value); } -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._writableState.highWaterMark; - } -}); - -// the no-half-open enforcer -function onend() { - // if we allow half-open state, or if the writable side ended, - // then we're ok. - if (this.allowHalfOpen || this._writableState.ended) return; +module.exports = objectToString; - // no more data can be written. - // But allow more writes to happen in this tick. - pna.nextTick(onEndNT, this); -} -function onEndNT(self) { - self.end(); -} +/***/ }), -Object.defineProperty(Duplex.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined || this._writableState === undefined) { - return false; - } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; - } +/***/ 6320: +/***/ ((module) => { - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - this._writableState.destroyed = value; - } -}); +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} -Duplex.prototype._destroy = function (err, cb) { - this.push(null); - this.end(); +module.exports = overArg; - pna.nextTick(cb, err); -}; /***/ }), -/***/ 70982: +/***/ 12417: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. - -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. +var apply = __nccwpck_require__(69647); +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; +/** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ +function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); -module.exports = PassThrough; - -var Transform = __nccwpck_require__(75072); - -/**/ -var util = Object.create(__nccwpck_require__(95898)); -util.inherits = __nccwpck_require__(44124); -/**/ - -util.inherits(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - - Transform.call(this, options); + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; } -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; +module.exports = overRest; + /***/ }), -/***/ 99140: +/***/ 89882: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. +var freeGlobal = __nccwpck_require__(52085); +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); -/**/ +module.exports = root; -var pna = __nccwpck_require__(47810); -/**/ -module.exports = Readable; +/***/ }), -/**/ -var isArray = __nccwpck_require__(20893); -/**/ +/***/ 16895: +/***/ ((module) => { -/**/ -var Duplex; -/**/ +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; -Readable.ReadableState = ReadableState; +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; +} -/**/ -var EE = (__nccwpck_require__(82361).EventEmitter); +module.exports = setCacheAdd; -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ -/**/ -var Stream = __nccwpck_require__(58745); -/**/ +/***/ }), -/**/ +/***/ 60804: +/***/ ((module) => { -var Buffer = (__nccwpck_require__(15054).Buffer); -var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); } -/**/ +module.exports = setCacheHas; -/**/ -var util = Object.create(__nccwpck_require__(95898)); -util.inherits = __nccwpck_require__(44124); -/**/ -/**/ -var debugUtil = __nccwpck_require__(73837); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; +/***/ }), + +/***/ 49553: +/***/ ((module) => { + +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; } -/**/ -var BufferList = __nccwpck_require__(75454); -var destroyImpl = __nccwpck_require__(78999); -var StringDecoder; +module.exports = setToArray; -util.inherits(Readable, Stream); -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; +/***/ }), -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); +/***/ 98416: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} +var baseSetToString = __nccwpck_require__(40979), + shortOut = __nccwpck_require__(17882); -function ReadableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(5706); +/** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var setToString = shortOut(baseSetToString); - options = options || {}; +module.exports = setToString; - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; +/***/ }), - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; +/***/ 17882: +/***/ ((module) => { - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - var hwm = options.highWaterMark; - var readableHwm = options.readableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; +/** Used to detect hot functions by number of calls within a span of milliseconds. */ +var HOT_COUNT = 800, + HOT_SPAN = 16; - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm; +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeNow = Date.now; - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); +/** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ +function shortOut(func) { + var count = 0, + lastCalled = 0; - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); - // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - this.sync = true; + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; +} - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; +module.exports = shortOut; - // has it been destroyed - this.destroyed = false; - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; +/***/ }), - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; +/***/ 58868: +/***/ ((module) => { - // if true, a maybeReadMore has been scheduled - this.readingMore = false; +/** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(24749)/* .StringDecoder */ .s); - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; + while (++index < length) { + if (array[index] === value) { + return index; + } } + return -1; } -function Readable(options) { - Duplex = Duplex || __nccwpck_require__(5706); +module.exports = strictIndexOf; - if (!(this instanceof Readable)) return new Readable(options); - this._readableState = new ReadableState(options, this); +/***/ }), - // legacy - this.readable = true; +/***/ 96928: +/***/ ((module) => { - if (options) { - if (typeof options.read === 'function') this._read = options.read; +/** Used for built-in method references. */ +var funcProto = Function.prototype; - if (typeof options.destroy === 'function') this._destroy = options.destroy; +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} } + return ''; +} - Stream.call(this); +module.exports = toSource; + + +/***/ }), + +/***/ 35946: +/***/ ((module) => { + +/** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ +function constant(value) { + return function() { + return value; + }; } -Object.defineProperty(Readable.prototype, 'destroyed', { - get: function () { - if (this._readableState === undefined) { - return false; - } - return this._readableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } +module.exports = constant; - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { - this.push(null); - cb(err); -}; +/***/ }), -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; +/***/ 3508: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; - } +var baseRest = __nccwpck_require__(42936), + eq = __nccwpck_require__(61901), + isIterateeCall = __nccwpck_require__(8494), + keysIn = __nccwpck_require__(69109); - return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); -}; +/** Used for built-in method references. */ +var objectProto = Object.prototype; -// Unshift should *always* be something directly out of read() -Readable.prototype.unshift = function (chunk) { - return readableAddChunk(this, chunk, null, true, false); -}; +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; -function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { - var state = stream._readableState; - if (chunk === null) { - state.reading = false; - onEofChunk(stream, state); - } else { - var er; - if (!skipChunkCheck) er = chunkInvalid(state, chunk); - if (er) { - stream.emit('error', er); - } else if (state.objectMode || chunk && chunk.length > 0) { - if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { - chunk = _uint8ArrayToBuffer(chunk); - } +/** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var defaults = baseRest(function(object, sources) { + object = Object(object); - if (addToFront) { - if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); - } else if (state.ended) { - stream.emit('error', new Error('stream.push() after EOF')); - } else { - state.reading = false; - if (state.decoder && !encoding) { - chunk = state.decoder.write(chunk); - if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); - } else { - addChunk(stream, state, chunk, false); - } - } - } else if (!addToFront) { - state.reading = false; - } + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; } - return needMoreData(state); -} + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; -function addChunk(stream, state, chunk, addToFront) { - if (state.flowing && state.length === 0 && !state.sync) { - stream.emit('data', chunk); - stream.read(0); - } else { - // update the buffer info. - state.length += state.objectMode ? 1 : chunk.length; - if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; - if (state.needReadable) emitReadable(stream); + if (value === undefined || + (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { + object[key] = source[key]; + } + } } - maybeReadMore(stream, state); -} -function chunkInvalid(state, chunk) { - var er; - if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - return er; -} + return object; +}); -// if it's past the high water mark, we can push in some more. -// Also, if we have no data yet, we can stand some -// more bytes. This is to work around cases where hwm=0, -// such as the repl. Also, if the push() triggered a -// readable event, and the user called read(largeNumber) such that -// needReadable was set, then we ought to push more, so that another -// 'readable' event will be triggered. -function needMoreData(state) { - return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); -} +module.exports = defaults; -Readable.prototype.isPaused = function () { - return this._readableState.flowing === false; -}; -// backwards compatibility. -Readable.prototype.setEncoding = function (enc) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(24749)/* .StringDecoder */ .s); - this._readableState.decoder = new StringDecoder(enc); - this._readableState.encoding = enc; - return this; -}; +/***/ }), -// Don't raise the hwm > 8MB -var MAX_HWM = 0x800000; -function computeNewHighWaterMark(n) { - if (n >= MAX_HWM) { - n = MAX_HWM; - } else { - // Get the next highest power of 2 to prevent increasing hwm excessively in - // tiny amounts - n--; - n |= n >>> 1; - n |= n >>> 2; - n |= n >>> 4; - n |= n >>> 8; - n |= n >>> 16; - n++; - } - return n; -} +/***/ 44031: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function howMuchToRead(n, state) { - if (n <= 0 || state.length === 0 && state.ended) return 0; - if (state.objectMode) return 1; - if (n !== n) { - // Only flow one buffer at a time - if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; - } - // If we're asking for more than the current hwm, then raise the hwm. - if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); - if (n <= state.length) return n; - // Don't have enough - if (!state.ended) { - state.needReadable = true; - return 0; - } - return state.length; -} +var baseDifference = __nccwpck_require__(21259), + baseFlatten = __nccwpck_require__(69588), + baseRest = __nccwpck_require__(42936), + isArrayLikeObject = __nccwpck_require__(87996); -// you can override either this method, or the async _read(n) below. -Readable.prototype.read = function (n) { - debug('read', n); - n = parseInt(n, 10); - var state = this._readableState; - var nOrig = n; +/** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ +var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; +}); - if (n !== 0) state.emittedReadable = false; +module.exports = difference; - // if we're doing read(0) to trigger a readable event, but we - // already have a bunch of data in the buffer, then just trigger - // the 'readable' event and move on. - if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { - debug('read: emitReadable', state.length, state.ended); - if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); - return null; - } - n = howMuchToRead(n, state); +/***/ }), - // if we've ended, and we're now clear, then finish it up. - if (n === 0 && state.ended) { - if (state.length === 0) endReadable(this); - return null; - } +/***/ 61901: +/***/ ((module) => { - // All the actual chunk generation logic needs to be - // *below* the call to _read. The reason is that in certain - // synthetic stream cases, such as passthrough streams, _read - // may be a completely synchronous operation which may change - // the state of the read buffer, providing enough data when - // before there was *not* enough. - // - // So, the steps are: - // 1. Figure out what the state of things will be after we do - // a read from the buffer. - // - // 2. If that resulting state will trigger a _read, then call _read. - // Note that this may be asynchronous, or synchronous. Yes, it is - // deeply ugly to write APIs this way, but that still doesn't mean - // that the Readable class should behave improperly, as streams are - // designed to be sync/async agnostic. - // Take note if the _read call is sync or async (ie, if the read call - // has returned yet), so that we know whether or not it's safe to emit - // 'readable' etc. - // - // 3. Actually pull the requested chunks out of the buffer and return. +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} - // if we need a readable event, then we need to do some reading. - var doRead = state.needReadable; - debug('need readable', doRead); +module.exports = eq; - // if we currently have less than the highWaterMark, then also read some - if (state.length === 0 || state.length - n < state.highWaterMark) { - doRead = true; - debug('length less than watermark', doRead); - } - // however, if we've ended, then there's no point, and if we're already - // reading, then it's unnecessary. - if (state.ended || state.reading) { - doRead = false; - debug('reading or ended', doRead); - } else if (doRead) { - debug('do read'); - state.reading = true; - state.sync = true; - // if the length is currently zero, then we *need* a readable event. - if (state.length === 0) state.needReadable = true; - // call internal read method - this._read(state.highWaterMark); - state.sync = false; - // If _read pushed data synchronously, then `reading` will be false, - // and we need to re-evaluate how much data we can return to the user. - if (!state.reading) n = howMuchToRead(nOrig, state); - } +/***/ }), - var ret; - if (n > 0) ret = fromList(n, state);else ret = null; +/***/ 42394: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (ret === null) { - state.needReadable = true; - n = 0; - } else { - state.length -= n; - } +var baseFlatten = __nccwpck_require__(69588); - if (state.length === 0) { - // If we have nothing in the buffer, then we want to know - // as soon as we *do* get something into the buffer. - if (!state.ended) state.needReadable = true; +/** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ +function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; +} - // If we tried to read() past the EOF, then emit end on the next tick. - if (nOrig !== n && state.ended) endReadable(this); - } +module.exports = flatten; - if (ret !== null) this.emit('data', ret); - return ret; -}; +/***/ }), -function onEofChunk(stream, state) { - if (state.ended) return; - if (state.decoder) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) { - state.buffer.push(chunk); - state.length += state.objectMode ? 1 : chunk.length; - } - } - state.ended = true; +/***/ 57822: +/***/ ((module) => { - // emit 'readable' now to make sure it gets picked up. - emitReadable(stream); +/** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ +function identity(value) { + return value; } -// Don't emit readable right away in sync mode, because this can trigger -// another read() call => stack overflow. This way, it might trigger -// a nextTick recursion warning, but that's not so bad. -function emitReadable(stream) { - var state = stream._readableState; - state.needReadable = false; - if (!state.emittedReadable) { - debug('emitReadable', state.flowing); - state.emittedReadable = true; - if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream); - } -} +module.exports = identity; -function emitReadable_(stream) { - debug('emit readable'); - stream.emit('readable'); - flow(stream); -} -// at this point, the user has presumably seen the 'readable' event, -// and called read() to consume some data. that may have triggered -// in turn another _read(n) call, in which case reading = true if -// it's in progress. -// However, if we're not ended, or reading, and the length < hwm, -// then go ahead and try to read some more preemptively. -function maybeReadMore(stream, state) { - if (!state.readingMore) { - state.readingMore = true; - pna.nextTick(maybeReadMore_, stream, state); - } -} +/***/ }), -function maybeReadMore_(stream, state) { - var len = state.length; - while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { - debug('maybeReadMore read 0'); - stream.read(0); - if (len === state.length) - // didn't get any data, stop spinning. - break;else len = state.length; - } - state.readingMore = false; -} +/***/ 78495: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// abstract method. to be overridden in specific implementation classes. -// call cb(er, data) where data is <= n in length. -// for virtual (non-string, non-buffer) streams, "length" is somewhat -// arbitrary, and perhaps not very meaningful. -Readable.prototype._read = function (n) { - this.emit('error', new Error('_read() is not implemented')); -}; +var baseIsArguments = __nccwpck_require__(92177), + isObjectLike = __nccwpck_require__(85926); -Readable.prototype.pipe = function (dest, pipeOpts) { - var src = this; - var state = this._readableState; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - switch (state.pipesCount) { - case 0: - state.pipes = dest; - break; - case 1: - state.pipes = [state.pipes, dest]; - break; - default: - state.pipes.push(dest); - break; - } - state.pipesCount += 1; - debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; - var endFn = doEnd ? onend : unpipe; - if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn); +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && + !propertyIsEnumerable.call(value, 'callee'); +}; - dest.on('unpipe', onunpipe); - function onunpipe(readable, unpipeInfo) { - debug('onunpipe'); - if (readable === src) { - if (unpipeInfo && unpipeInfo.hasUnpiped === false) { - unpipeInfo.hasUnpiped = true; - cleanup(); - } - } - } +module.exports = isArguments; - function onend() { - debug('onend'); - dest.end(); - } - // when the dest drains, it reduces the awaitDrain counter - // on the source. This would be more elegant with a .once() - // handler in flow(), but adding and removing repeatedly is - // too slow. - var ondrain = pipeOnDrain(src); - dest.on('drain', ondrain); +/***/ }), - var cleanedUp = false; - function cleanup() { - debug('cleanup'); - // cleanup event handlers once the pipe is broken - dest.removeListener('close', onclose); - dest.removeListener('finish', onfinish); - dest.removeListener('drain', ondrain); - dest.removeListener('error', onerror); - dest.removeListener('unpipe', onunpipe); - src.removeListener('end', onend); - src.removeListener('end', unpipe); - src.removeListener('data', ondata); +/***/ 44869: +/***/ ((module) => { - cleanedUp = true; +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - // if the reader is waiting for a drain event from this - // specific writer, then it would cause it to never start - // flowing again. - // So, if this is awaiting a drain, then we just call it now. - // If we don't know, then assume that we are waiting for one. - if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); - } +module.exports = isArray; - // If the user pushes more data while we're writing to dest then we'll end up - // in ondata again. However, we only want to increase awaitDrain once because - // dest will only emit one 'drain' event for the multiple writes. - // => Introduce a guard on increasing awaitDrain. - var increasedAwaitDrain = false; - src.on('data', ondata); - function ondata(chunk) { - debug('ondata'); - increasedAwaitDrain = false; - var ret = dest.write(chunk); - if (false === ret && !increasedAwaitDrain) { - // If the user unpiped during `dest.write()`, it is possible - // to get stuck in a permanently paused state if that write - // also returned false. - // => Check whether `dest` is still a piping destination. - if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { - debug('false write response, pause', state.awaitDrain); - state.awaitDrain++; - increasedAwaitDrain = true; - } - src.pause(); - } - } - // if the dest has an error, then stop piping into it. - // however, don't suppress the throwing behavior for this. - function onerror(er) { - debug('onerror', er); - unpipe(); - dest.removeListener('error', onerror); - if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); - } +/***/ }), - // Make sure our error handler is attached before userland ones. - prependListener(dest, 'error', onerror); +/***/ 18017: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Both close and finish should trigger unpipe, but only once. - function onclose() { - dest.removeListener('finish', onfinish); - unpipe(); - } - dest.once('close', onclose); - function onfinish() { - debug('onfinish'); - dest.removeListener('close', onclose); - unpipe(); - } - dest.once('finish', onfinish); +var isFunction = __nccwpck_require__(17799), + isLength = __nccwpck_require__(64530); - function unpipe() { - debug('unpipe'); - src.unpipe(dest); - } +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} - // tell the dest that it's being piped to - dest.emit('pipe', src); +module.exports = isArrayLike; - // start the flow if it hasn't been started already. - if (!state.flowing) { - debug('pipe resume'); - src.resume(); - } - return dest; -}; +/***/ }), -function pipeOnDrain(src) { - return function () { - var state = src._readableState; - debug('pipeOnDrain', state.awaitDrain); - if (state.awaitDrain) state.awaitDrain--; - if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { - state.flowing = true; - flow(src); - } - }; -} +/***/ 87996: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Readable.prototype.unpipe = function (dest) { - var state = this._readableState; - var unpipeInfo = { hasUnpiped: false }; +var isArrayLike = __nccwpck_require__(18017), + isObjectLike = __nccwpck_require__(85926); - // if we're not piping anywhere, then do nothing. - if (state.pipesCount === 0) return this; +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} - // just one destination. most common case. - if (state.pipesCount === 1) { - // passed in one, but it's not the right one. - if (dest && dest !== state.pipes) return this; +module.exports = isArrayLikeObject; - if (!dest) dest = state.pipes; - // got a match. - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; - if (dest) dest.emit('unpipe', this, unpipeInfo); - return this; - } +/***/ }), - // slow case. multiple pipe destinations. +/***/ 74190: +/***/ ((module, exports, __nccwpck_require__) => { - if (!dest) { - // remove all. - var dests = state.pipes; - var len = state.pipesCount; - state.pipes = null; - state.pipesCount = 0; - state.flowing = false; +/* module decorator */ module = __nccwpck_require__.nmd(module); +var root = __nccwpck_require__(89882), + stubFalse = __nccwpck_require__(67744); - for (var i = 0; i < len; i++) { - dests[i].emit('unpipe', this, { hasUnpiped: false }); - }return this; - } +/** Detect free variable `exports`. */ +var freeExports = true && exports && !exports.nodeType && exports; - // try to find the right one. - var index = indexOf(state.pipes, dest); - if (index === -1) return this; +/** Detect free variable `module`. */ +var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; - state.pipes.splice(index, 1); - state.pipesCount -= 1; - if (state.pipesCount === 1) state.pipes = state.pipes[0]; +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; - dest.emit('unpipe', this, unpipeInfo); +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined; - return this; -}; +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; -// set up data events if they are asked for -// Ensure readable listeners eventually get something -Readable.prototype.on = function (ev, fn) { - var res = Stream.prototype.on.call(this, ev, fn); +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; - if (ev === 'data') { - // Start flowing on next tick if stream isn't explicitly paused - if (this._readableState.flowing !== false) this.resume(); - } else if (ev === 'readable') { - var state = this._readableState; - if (!state.endEmitted && !state.readableListening) { - state.readableListening = state.needReadable = true; - state.emittedReadable = false; - if (!state.reading) { - pna.nextTick(nReadingNextTick, this); - } else if (state.length) { - emitReadable(this); - } - } - } +module.exports = isBuffer; - return res; -}; -Readable.prototype.addListener = Readable.prototype.on; -function nReadingNextTick(self) { - debug('readable nexttick read 0'); - self.read(0); -} +/***/ }), -// pause() and resume() are remnants of the legacy readable stream API -// If the user uses them, then switch into old mode. -Readable.prototype.resume = function () { - var state = this._readableState; - if (!state.flowing) { - debug('resume'); - state.flowing = true; - resume(this, state); - } - return this; -}; +/***/ 17799: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function resume(stream, state) { - if (!state.resumeScheduled) { - state.resumeScheduled = true; - pna.nextTick(resume_, stream, state); +var baseGetTag = __nccwpck_require__(97497), + isObject = __nccwpck_require__(33334); + +/** `Object#toString` result references. */ +var asyncTag = '[object AsyncFunction]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + if (!isObject(value)) { + return false; } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } -function resume_(stream, state) { - if (!state.reading) { - debug('resume read 0'); - stream.read(0); - } +module.exports = isFunction; - state.resumeScheduled = false; - state.awaitDrain = 0; - stream.emit('resume'); - flow(stream); - if (state.flowing && !state.reading) stream.read(0); -} -Readable.prototype.pause = function () { - debug('call pause flowing=%j', this._readableState.flowing); - if (false !== this._readableState.flowing) { - debug('pause'); - this._readableState.flowing = false; - this.emit('pause'); - } - return this; -}; +/***/ }), -function flow(stream) { - var state = stream._readableState; - debug('flow', state.flowing); - while (state.flowing && stream.read() !== null) {} +/***/ 64530: +/***/ ((module) => { + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } -// wrap an old-style stream as the async data source. -// This is *not* part of the readable stream interface. -// It is an ugly unfortunate mess of history. -Readable.prototype.wrap = function (stream) { - var _this = this; +module.exports = isLength; - var state = this._readableState; - var paused = false; - stream.on('end', function () { - debug('wrapped end'); - if (state.decoder && !state.ended) { - var chunk = state.decoder.end(); - if (chunk && chunk.length) _this.push(chunk); - } +/***/ }), - _this.push(null); - }); +/***/ 33334: +/***/ ((module) => { - stream.on('data', function (chunk) { - debug('wrapped data'); - if (state.decoder) chunk = state.decoder.write(chunk); +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} - // don't skip over falsy values in objectMode - if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; +module.exports = isObject; - var ret = _this.push(chunk); - if (!ret) { - paused = true; - stream.pause(); - } - }); - // proxy all the other methods. - // important when wrapping filters and duplexes. - for (var i in stream) { - if (this[i] === undefined && typeof stream[i] === 'function') { - this[i] = function (method) { - return function () { - return stream[method].apply(stream, arguments); - }; - }(i); - } - } +/***/ }), - // proxy certain important events. - for (var n = 0; n < kProxyEvents.length; n++) { - stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n])); - } +/***/ 85926: +/***/ ((module) => { - // when we try to consume some more bytes, simply unpause the - // underlying stream. - this._read = function (n) { - debug('wrapped _read', n); - if (paused) { - paused = false; - stream.resume(); - } - }; +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} - return this; -}; +module.exports = isObjectLike; -Object.defineProperty(Readable.prototype, 'readableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._readableState.highWaterMark; - } -}); -// exposed for testing purposes only. -Readable._fromList = fromList; +/***/ }), -// Pluck off n bytes from an array of buffers. -// Length is the combined lengths of all the buffers in the list. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromList(n, state) { - // nothing buffered - if (state.length === 0) return null; +/***/ 46169: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var ret; - if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { - // read it all, truncate the list - if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); - state.buffer.clear(); - } else { - // read part of list - ret = fromListPartial(n, state.buffer, state.decoder); - } +var baseGetTag = __nccwpck_require__(97497), + getPrototype = __nccwpck_require__(86271), + isObjectLike = __nccwpck_require__(85926); - return ret; -} +/** `Object#toString` result references. */ +var objectTag = '[object Object]'; -// Extracts only enough buffered data to satisfy the amount requested. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function fromListPartial(n, list, hasStrings) { - var ret; - if (n < list.head.data.length) { - // slice is the same for buffers and strings - ret = list.head.data.slice(0, n); - list.head.data = list.head.data.slice(n); - } else if (n === list.head.data.length) { - // first chunk is a perfect match - ret = list.shift(); - } else { - // result spans more than one buffer - ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); - } - return ret; -} +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto = Object.prototype; -// Copies a specified amount of characters from the list of buffered data -// chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBufferString(n, list) { - var p = list.head; - var c = 1; - var ret = p.data; - n -= ret.length; - while (p = p.next) { - var str = p.data; - var nb = n > str.length ? str.length : n; - if (nb === str.length) ret += str;else ret += str.slice(0, n); - n -= nb; - if (n === 0) { - if (nb === str.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = str.slice(nb); - } - break; - } - ++c; - } - list.length -= c; - return ret; -} +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; -// Copies a specified amount of bytes from the list of buffered data chunks. -// This function is designed to be inlinable, so please take care when making -// changes to the function body. -function copyFromBuffer(n, list) { - var ret = Buffer.allocUnsafe(n); - var p = list.head; - var c = 1; - p.data.copy(ret); - n -= p.data.length; - while (p = p.next) { - var buf = p.data; - var nb = n > buf.length ? buf.length : n; - buf.copy(ret, ret.length - n, 0, nb); - n -= nb; - if (n === 0) { - if (nb === buf.length) { - ++c; - if (p.next) list.head = p.next;else list.head = list.tail = null; - } else { - list.head = p; - p.data = buf.slice(nb); - } - break; - } - ++c; +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; + +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); + +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag) { + return false; } - list.length -= c; - return ret; + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; } -function endReadable(stream) { - var state = stream._readableState; +module.exports = isPlainObject; - // If we get here before consuming all the bytes, then that is a - // bug in node. Should never happen. - if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); - if (!state.endEmitted) { - state.ended = true; - pna.nextTick(endReadableNT, state, stream); - } -} +/***/ }), -function endReadableNT(state, stream) { - // Check that we didn't get one last unshift. - if (!state.endEmitted && state.length === 0) { - state.endEmitted = true; - stream.readable = false; - stream.emit('end'); - } -} +/***/ 2496: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var baseIsTypedArray = __nccwpck_require__(11528), + baseUnary = __nccwpck_require__(59258), + nodeUtil = __nccwpck_require__(34643); + +/* Node.js helper references. */ +var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + +module.exports = isTypedArray; -function indexOf(xs, x) { - for (var i = 0, l = xs.length; i < l; i++) { - if (xs[i] === x) return i; - } - return -1; -} /***/ }), -/***/ 75072: +/***/ 69109: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. +var arrayLikeKeys = __nccwpck_require__(32237), + baseKeysIn = __nccwpck_require__(90297), + isArrayLike = __nccwpck_require__(18017); -// a transform stream is a readable/writable stream where you do -// something with the data. Sometimes it's called a "filter", -// but that's not a great name for it, since that implies a thing where -// some bits pass through, and others are simply ignored. (That would -// be a valid example of a transform, of course.) -// -// While the output is causally related to the input, it's not a -// necessarily symmetric or synchronous transformation. For example, -// a zlib stream might take multiple plain-text writes(), and then -// emit a single compressed chunk some time in the future. -// -// Here's how this works: -// -// The Transform stream has all the aspects of the readable and writable -// stream classes. When you write(chunk), that calls _write(chunk,cb) -// internally, and returns false if there's a lot of pending writes -// buffered up. When you call read(), that calls _read(n) until -// there's enough pending readable data buffered up. -// -// In a transform stream, the written data is placed in a buffer. When -// _read(n) is called, it transforms the queued up data, calling the -// buffered _write cb's as it consumes chunks. If consuming a single -// written chunk would result in multiple output chunks, then the first -// outputted bit calls the readcb, and subsequent chunks just go into -// the read buffer, and will cause it to emit 'readable' if necessary. -// -// This way, back-pressure is actually determined by the reading side, -// since _read has to be called to start processing a new chunk. However, -// a pathological inflate type of transform can cause excessive buffering -// here. For example, imagine a stream where every byte of input is -// interpreted as an integer from 0-255, and then results in that many -// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in -// 1kb of data being output. In this case, you could write a very small -// amount of input, and end up with a very large amount of output. In -// such a pathological inflating mechanism, there'd be no way to tell -// the system to stop doing the transform. A single 4MB write could -// cause the system to run out of memory. -// -// However, even in such a pathological case, only a single written chunk -// would be consumed, and then the rest would wait (un-transformed) until -// the results of the previous transformed chunk were consumed. - - - -module.exports = Transform; +/** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ +function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); +} -var Duplex = __nccwpck_require__(5706); +module.exports = keysIn; -/**/ -var util = Object.create(__nccwpck_require__(95898)); -util.inherits = __nccwpck_require__(44124); -/**/ -util.inherits(Transform, Duplex); +/***/ }), -function afterTransform(er, data) { - var ts = this._transformState; - ts.transforming = false; +/***/ 51901: +/***/ ((module) => { - var cb = ts.writecb; +/** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ +function noop() { + // No operation performed. +} - if (!cb) { - return this.emit('error', new Error('write callback called multiple times')); - } +module.exports = noop; - ts.writechunk = null; - ts.writecb = null; - if (data != null) // single equals check for both `null` and `undefined` - this.push(data); +/***/ }), - cb(er); +/***/ 67744: +/***/ ((module) => { - var rs = this._readableState; - rs.reading = false; - if (rs.needReadable || rs.length < rs.highWaterMark) { - this._read(rs.highWaterMark); - } +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; } -function Transform(options) { - if (!(this instanceof Transform)) return new Transform(options); +module.exports = stubFalse; - Duplex.call(this, options); - this._transformState = { - afterTransform: afterTransform.bind(this), - needTransform: false, - transforming: false, - writecb: null, - writechunk: null, - writeencoding: null - }; +/***/ }), - // start out asking for a readable event once data is transformed. - this._readableState.needReadable = true; +/***/ 11620: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // we have implemented the _read method, and done the other things - // that Readable wants before the first _read call, so unset the - // sync guard flag. - this._readableState.sync = false; +var baseFlatten = __nccwpck_require__(69588), + baseRest = __nccwpck_require__(42936), + baseUniq = __nccwpck_require__(19036), + isArrayLikeObject = __nccwpck_require__(87996); - if (options) { - if (typeof options.transform === 'function') this._transform = options.transform; +/** + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. + * @example + * + * _.union([2], [1, 2]); + * // => [2, 1] + */ +var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); +}); - if (typeof options.flush === 'function') this._flush = options.flush; - } +module.exports = union; - // When the writable side finishes, then flush out anything remaining. - this.on('prefinish', prefinish); -} -function prefinish() { - var _this = this; +/***/ }), - if (typeof this._flush === 'function') { - this._flush(function (er, data) { - done(_this, er, data); - }); - } else { - done(this, null, null); - } -} +/***/ 47426: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Transform.prototype.push = function (chunk, encoding) { - this._transformState.needTransform = false; - return Duplex.prototype.push.call(this, chunk, encoding); -}; +/*! + * mime-db + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015-2022 Douglas Christopher Wilson + * MIT Licensed + */ -// This is the part where you do stuff! -// override this function in implementation classes. -// 'chunk' is an input chunk. -// -// Call `push(newChunk)` to pass along transformed output -// to the readable side. You may call 'push' zero or more times. -// -// Call `cb(err)` when you are done with this chunk. If you pass -// an error, then that'll put the hurt on the whole operation. If you -// never call cb(), then you'll never get another chunk. -Transform.prototype._transform = function (chunk, encoding, cb) { - throw new Error('_transform() is not implemented'); -}; +/** + * Module exports. + */ -Transform.prototype._write = function (chunk, encoding, cb) { - var ts = this._transformState; - ts.writecb = cb; - ts.writechunk = chunk; - ts.writeencoding = encoding; - if (!ts.transforming) { - var rs = this._readableState; - if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); - } -}; +module.exports = __nccwpck_require__(53765) -// Doesn't matter what the args are here. -// _transform does all the work. -// That we got here means that the readable side wants more data. -Transform.prototype._read = function (n) { - var ts = this._transformState; - if (ts.writechunk !== null && ts.writecb && !ts.transforming) { - ts.transforming = true; - this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); - } else { - // mark that we need a transform, so that any data that comes in - // will get processed, now that we've asked for it. - ts.needTransform = true; - } -}; +/***/ }), -Transform.prototype._destroy = function (err, cb) { - var _this2 = this; +/***/ 43583: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Duplex.prototype._destroy.call(this, err, function (err2) { - cb(err2); - _this2.emit('close'); - }); -}; +"use strict"; +/*! + * mime-types + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ -function done(stream, er, data) { - if (er) return stream.emit('error', er); - if (data != null) // single equals check for both `null` and `undefined` - stream.push(data); - // if there's nothing in the write buffer, then that means - // that nothing more will ever be provided - if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0'); +/** + * Module dependencies. + * @private + */ - if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming'); +var db = __nccwpck_require__(47426) +var extname = (__nccwpck_require__(71017).extname) - return stream.push(null); -} +/** + * Module variables. + * @private + */ -/***/ }), +var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ +var TEXT_TYPE_REGEXP = /^text\//i -/***/ 14960: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Module exports. + * @public + */ -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. +exports.charset = charset +exports.charsets = { lookup: charset } +exports.contentType = contentType +exports.extension = extension +exports.extensions = Object.create(null) +exports.lookup = lookup +exports.types = Object.create(null) -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. +// Populate the extensions/types maps +populateMaps(exports.extensions, exports.types) +/** + * Get the default charset for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ +function charset (type) { + if (!type || typeof type !== 'string') { + return false + } -/**/ + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) + var mime = match && db[match[1].toLowerCase()] -var pna = __nccwpck_require__(47810); -/**/ + if (mime && mime.charset) { + return mime.charset + } -module.exports = Writable; + // default text/* to utf-8 + if (match && TEXT_TYPE_REGEXP.test(match[1])) { + return 'UTF-8' + } -/* */ -function WriteReq(chunk, encoding, cb) { - this.chunk = chunk; - this.encoding = encoding; - this.callback = cb; - this.next = null; + return false } -// It seems a linked list but it is not -// there will be only 2 of these for each stream -function CorkedRequest(state) { - var _this = this; +/** + * Create a full Content-Type header given a MIME type or extension. + * + * @param {string} str + * @return {boolean|string} + */ - this.next = null; - this.entry = null; - this.finish = function () { - onCorkedFinish(_this, state); - }; -} -/* */ +function contentType (str) { + // TODO: should this even be in this module? + if (!str || typeof str !== 'string') { + return false + } -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick; -/**/ + var mime = str.indexOf('/') === -1 + ? exports.lookup(str) + : str -/**/ -var Duplex; -/**/ + if (!mime) { + return false + } -Writable.WritableState = WritableState; + // TODO: use content-type or other module + if (mime.indexOf('charset') === -1) { + var charset = exports.charset(mime) + if (charset) mime += '; charset=' + charset.toLowerCase() + } -/**/ -var util = Object.create(__nccwpck_require__(95898)); -util.inherits = __nccwpck_require__(44124); -/**/ + return mime +} -/**/ -var internalUtil = { - deprecate: __nccwpck_require__(65278) -}; -/**/ +/** + * Get the default extension for a MIME type. + * + * @param {string} type + * @return {boolean|string} + */ -/**/ -var Stream = __nccwpck_require__(58745); -/**/ +function extension (type) { + if (!type || typeof type !== 'string') { + return false + } -/**/ + // TODO: use media-typer + var match = EXTRACT_TYPE_REGEXP.exec(type) -var Buffer = (__nccwpck_require__(15054).Buffer); -var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; + // get extensions + var exts = match && exports.extensions[match[1].toLowerCase()] + + if (!exts || !exts.length) { + return false + } + + return exts[0] } -/**/ +/** + * Lookup the MIME type for a file path/extension. + * + * @param {string} path + * @return {boolean|string} + */ -var destroyImpl = __nccwpck_require__(78999); +function lookup (path) { + if (!path || typeof path !== 'string') { + return false + } -util.inherits(Writable, Stream); + // get the extension ("ext" or ".ext" or full path) + var extension = extname('x.' + path) + .toLowerCase() + .substr(1) -function nop() {} + if (!extension) { + return false + } -function WritableState(options, stream) { - Duplex = Duplex || __nccwpck_require__(5706); + return exports.types[extension] || false +} - options = options || {}; +/** + * Populate the extensions and types maps. + * @private + */ - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - var isDuplex = stream instanceof Duplex; +function populateMaps (extensions, types) { + // source preference (least -> most) + var preference = ['nginx', 'apache', undefined, 'iana'] - // object stream flag to indicate whether or not this stream - // contains buffers or objects. - this.objectMode = !!options.objectMode; + Object.keys(db).forEach(function forEachMimeType (type) { + var mime = db[type] + var exts = mime.extensions - if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; + if (!exts || !exts.length) { + return + } - // the point at which write() starts returning false - // Note: 0 is a valid value, means that we always return false if - // the entire buffer is not flushed immediately on write() - var hwm = options.highWaterMark; - var writableHwm = options.writableHighWaterMark; - var defaultHwm = this.objectMode ? 16 : 16 * 1024; + // mime -> extensions + extensions[type] = exts - if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm; + // extension -> mime + for (var i = 0; i < exts.length; i++) { + var extension = exts[i] - // cast to ints. - this.highWaterMark = Math.floor(this.highWaterMark); + if (types[extension]) { + var from = preference.indexOf(db[types[extension]].source) + var to = preference.indexOf(mime.source) - // if _final has been called - this.finalCalled = false; + if (types[extension] !== 'application/octet-stream' && + (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { + // skip the remapping + continue + } + } - // drain event flag. - this.needDrain = false; - // at the start of calling end() - this.ending = false; - // when end() has been called, and returned - this.ended = false; - // when 'finish' is emitted - this.finished = false; + // set the extension -> mime + types[extension] = type + } + }) +} - // has it been destroyed - this.destroyed = false; - // should we decode strings into buffers before passing to _write? - // this is here so that some node-core streams can optimize string - // handling at a lower level. - var noDecode = options.decodeStrings === false; - this.decodeStrings = !noDecode; +/***/ }), - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; +/***/ 66186: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // not an actual buffer we keep track of, but a measurement - // of how much we're waiting to get pushed to some underlying - // socket or file. - this.length = 0; +var path = __nccwpck_require__(71017); +var fs = __nccwpck_require__(57147); +var _0777 = parseInt('0777', 8); - // a flag to see when we're in the middle of a write. - this.writing = false; +module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; - // when true all writes will be buffered until .uncork() call - this.corked = 0; +function mkdirP (p, opts, f, made) { + if (typeof opts === 'function') { + f = opts; + opts = {}; + } + else if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; + + var cb = f || /* istanbul ignore next */ function () {}; + p = path.resolve(p); + + xfs.mkdir(p, mode, function (er) { + if (!er) { + made = made || p; + return cb(null, made); + } + switch (er.code) { + case 'ENOENT': + /* istanbul ignore if */ + if (path.dirname(p) === p) return cb(er); + mkdirP(path.dirname(p), opts, function (er, made) { + /* istanbul ignore if */ + if (er) cb(er, made); + else mkdirP(p, opts, cb, made); + }); + break; - // a flag to be able to tell if the onwrite cb is called immediately, - // or on a later tick. We set this to true at first, because any - // actions that shouldn't happen until "later" should generally also - // not happen before the first write call. - this.sync = true; + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + xfs.stat(p, function (er2, stat) { + // if the stat fails, then that's super weird. + // let the original error be the failure reason. + if (er2 || !stat.isDirectory()) cb(er, made) + else cb(null, made); + }); + break; + } + }); +} - // a flag to know if we're processing previously buffered items, which - // may call the _write() callback in the same tick, so that we don't - // end up in an overlapped onwrite situation. - this.bufferProcessing = false; +mkdirP.sync = function sync (p, opts, made) { + if (!opts || typeof opts !== 'object') { + opts = { mode: opts }; + } + + var mode = opts.mode; + var xfs = opts.fs || fs; + + if (mode === undefined) { + mode = _0777 + } + if (!made) made = null; - // the callback that's passed to _write(chunk,cb) - this.onwrite = function (er) { - onwrite(stream, er); - }; + p = path.resolve(p); - // the callback that the user supplies to write(chunk,encoding,cb) - this.writecb = null; + try { + xfs.mkdirSync(p, mode); + made = made || p; + } + catch (err0) { + switch (err0.code) { + case 'ENOENT' : + made = sync(path.dirname(p), opts, made); + sync(p, opts, made); + break; - // the amount that is being written when _write is called. - this.writelen = 0; + // In the case of any other error, just see if there's a dir + // there already. If so, then hooray! If not, then something + // is borked. + default: + var stat; + try { + stat = xfs.statSync(p); + } + catch (err1) /* istanbul ignore next */ { + throw err0; + } + /* istanbul ignore if */ + if (!stat.isDirectory()) throw err0; + break; + } + } - this.bufferedRequest = null; - this.lastBufferedRequest = null; + return made; +}; - // number of pending user-supplied write callbacks - // this must be 0 before 'finish' can be emitted - this.pendingcb = 0; - // emit prefinish if the only thing we're waiting for is _write cbs - // This is relevant for synchronous Transform streams - this.prefinished = false; +/***/ }), - // True if the error was already emitted and should not be thrown again - this.errorEmitted = false; +/***/ 80467: +/***/ ((module, exports, __nccwpck_require__) => { - // count buffered requests - this.bufferedRequestCount = 0; +"use strict"; - // allocate the first CorkedRequest, there is always - // one allocated and free to use, and we maintain at most two - this.corkedRequestsFree = new CorkedRequest(this); -} -WritableState.prototype.getBuffer = function getBuffer() { - var current = this.bufferedRequest; - var out = []; - while (current) { - out.push(current); - current = current.next; - } - return out; -}; +Object.defineProperty(exports, "__esModule", ({ value: true })); -(function () { - try { - Object.defineProperty(WritableState.prototype, 'buffer', { - get: internalUtil.deprecate(function () { - return this.getBuffer(); - }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') - }); - } catch (_) {} -})(); +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -// Test _writableState for inheritance to account for Duplex streams, -// whose prototype chain only points to Readable. -var realHasInstance; -if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { - realHasInstance = Function.prototype[Symbol.hasInstance]; - Object.defineProperty(Writable, Symbol.hasInstance, { - value: function (object) { - if (realHasInstance.call(this, object)) return true; - if (this !== Writable) return false; +var Stream = _interopDefault(__nccwpck_require__(12781)); +var http = _interopDefault(__nccwpck_require__(13685)); +var Url = _interopDefault(__nccwpck_require__(57310)); +var whatwgUrl = _interopDefault(__nccwpck_require__(28665)); +var https = _interopDefault(__nccwpck_require__(95687)); +var zlib = _interopDefault(__nccwpck_require__(59796)); - return object && object._writableState instanceof WritableState; - } - }); -} else { - realHasInstance = function (object) { - return object instanceof this; - }; -} +// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js -function Writable(options) { - Duplex = Duplex || __nccwpck_require__(5706); +// fix for "Readable" isn't a named export issue +const Readable = Stream.Readable; - // Writable ctor is applied to Duplexes, too. - // `realHasInstance` is necessary because using plain `instanceof` - // would return false, as no `_writableState` property is attached. +const BUFFER = Symbol('buffer'); +const TYPE = Symbol('type'); - // Trying to use the custom `instanceof` for Writable here will also break the - // Node.js LazyTransform implementation, which has a non-trivial getter for - // `_writableState` that would lead to infinite recursion. - if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { - return new Writable(options); - } +class Blob { + constructor() { + this[TYPE] = ''; - this._writableState = new WritableState(options, this); + const blobParts = arguments[0]; + const options = arguments[1]; - // legacy. - this.writable = true; + const buffers = []; + let size = 0; - if (options) { - if (typeof options.write === 'function') this._write = options.write; + if (blobParts) { + const a = blobParts; + const length = Number(a.length); + for (let i = 0; i < length; i++) { + const element = a[i]; + let buffer; + if (element instanceof Buffer) { + buffer = element; + } else if (ArrayBuffer.isView(element)) { + buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); + } else if (element instanceof ArrayBuffer) { + buffer = Buffer.from(element); + } else if (element instanceof Blob) { + buffer = element[BUFFER]; + } else { + buffer = Buffer.from(typeof element === 'string' ? element : String(element)); + } + size += buffer.length; + buffers.push(buffer); + } + } - if (typeof options.writev === 'function') this._writev = options.writev; + this[BUFFER] = Buffer.concat(buffers); - if (typeof options.destroy === 'function') this._destroy = options.destroy; + let type = options && options.type !== undefined && String(options.type).toLowerCase(); + if (type && !/[^\u0020-\u007E]/.test(type)) { + this[TYPE] = type; + } + } + get size() { + return this[BUFFER].length; + } + get type() { + return this[TYPE]; + } + text() { + return Promise.resolve(this[BUFFER].toString()); + } + arrayBuffer() { + const buf = this[BUFFER]; + const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + return Promise.resolve(ab); + } + stream() { + const readable = new Readable(); + readable._read = function () {}; + readable.push(this[BUFFER]); + readable.push(null); + return readable; + } + toString() { + return '[object Blob]'; + } + slice() { + const size = this.size; - if (typeof options.final === 'function') this._final = options.final; - } + const start = arguments[0]; + const end = arguments[1]; + let relativeStart, relativeEnd; + if (start === undefined) { + relativeStart = 0; + } else if (start < 0) { + relativeStart = Math.max(size + start, 0); + } else { + relativeStart = Math.min(start, size); + } + if (end === undefined) { + relativeEnd = size; + } else if (end < 0) { + relativeEnd = Math.max(size + end, 0); + } else { + relativeEnd = Math.min(end, size); + } + const span = Math.max(relativeEnd - relativeStart, 0); - Stream.call(this); + const buffer = this[BUFFER]; + const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); + const blob = new Blob([], { type: arguments[2] }); + blob[BUFFER] = slicedBuffer; + return blob; + } } -// Otherwise people can pipe Writable streams, which is just wrong. -Writable.prototype.pipe = function () { - this.emit('error', new Error('Cannot pipe, not readable')); -}; - -function writeAfterEnd(stream, cb) { - var er = new Error('write after end'); - // TODO: defer error events consistently everywhere, not just the cb - stream.emit('error', er); - pna.nextTick(cb, er); -} +Object.defineProperties(Blob.prototype, { + size: { enumerable: true }, + type: { enumerable: true }, + slice: { enumerable: true } +}); -// Checks that a user-supplied chunk is valid, especially for the particular -// mode the stream is in. Currently this means that `null` is never accepted -// and undefined/non-string values are only allowed in object mode. -function validChunk(stream, state, chunk, cb) { - var valid = true; - var er = false; +Object.defineProperty(Blob.prototype, Symbol.toStringTag, { + value: 'Blob', + writable: false, + enumerable: false, + configurable: true +}); - if (chunk === null) { - er = new TypeError('May not write null values to stream'); - } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { - er = new TypeError('Invalid non-string/buffer chunk'); - } - if (er) { - stream.emit('error', er); - pna.nextTick(cb, er); - valid = false; - } - return valid; -} +/** + * fetch-error.js + * + * FetchError interface for operational errors + */ -Writable.prototype.write = function (chunk, encoding, cb) { - var state = this._writableState; - var ret = false; - var isBuf = !state.objectMode && _isUint8Array(chunk); +/** + * Create FetchError instance + * + * @param String message Error message for human + * @param String type Error type for machine + * @param String systemError For Node.js system error + * @return FetchError + */ +function FetchError(message, type, systemError) { + Error.call(this, message); - if (isBuf && !Buffer.isBuffer(chunk)) { - chunk = _uint8ArrayToBuffer(chunk); - } + this.message = message; + this.type = type; - if (typeof encoding === 'function') { - cb = encoding; - encoding = null; + // when err.type is `system`, err.code contains system error code + if (systemError) { + this.code = this.errno = systemError.code; } - if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; - - if (typeof cb !== 'function') cb = nop; + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); +} - if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { - state.pendingcb++; - ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); - } +FetchError.prototype = Object.create(Error.prototype); +FetchError.prototype.constructor = FetchError; +FetchError.prototype.name = 'FetchError'; - return ret; -}; +let convert; +try { + convert = (__nccwpck_require__(22877).convert); +} catch (e) {} -Writable.prototype.cork = function () { - var state = this._writableState; +const INTERNALS = Symbol('Body internals'); - state.corked++; -}; +// fix an issue where "PassThrough" isn't a named export for node <10 +const PassThrough = Stream.PassThrough; -Writable.prototype.uncork = function () { - var state = this._writableState; +/** + * Body mixin + * + * Ref: https://fetch.spec.whatwg.org/#body + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +function Body(body) { + var _this = this; - if (state.corked) { - state.corked--; + var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, + _ref$size = _ref.size; - if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); - } -}; + let size = _ref$size === undefined ? 0 : _ref$size; + var _ref$timeout = _ref.timeout; + let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; -Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { - // node::ParseEncoding() requires lower case. - if (typeof encoding === 'string') encoding = encoding.toLowerCase(); - if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); - this._writableState.defaultEncoding = encoding; - return this; -}; + if (body == null) { + // body is undefined or null + body = null; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + body = Buffer.from(body.toString()); + } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + body = Buffer.from(body); + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); + } else if (body instanceof Stream) ; else { + // none of the above + // coerce to string then buffer + body = Buffer.from(String(body)); + } + this[INTERNALS] = { + body, + disturbed: false, + error: null + }; + this.size = size; + this.timeout = timeout; -function decodeChunk(state, chunk, encoding) { - if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer.from(chunk, encoding); - } - return chunk; + if (body instanceof Stream) { + body.on('error', function (err) { + const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); + _this[INTERNALS].error = error; + }); + } } -Object.defineProperty(Writable.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function () { - return this._writableState.highWaterMark; - } -}); +Body.prototype = { + get body() { + return this[INTERNALS].body; + }, -// if we're already writing something, then just put this -// in the queue, and wait our turn. Otherwise, call _write -// If we return false, then we need a drain event, so set that flag. -function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { - if (!isBuf) { - var newChunk = decodeChunk(state, chunk, encoding); - if (chunk !== newChunk) { - isBuf = true; - encoding = 'buffer'; - chunk = newChunk; - } - } - var len = state.objectMode ? 1 : chunk.length; + get bodyUsed() { + return this[INTERNALS].disturbed; + }, - state.length += len; + /** + * Decode response as ArrayBuffer + * + * @return Promise + */ + arrayBuffer() { + return consumeBody.call(this).then(function (buf) { + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); + }); + }, - var ret = state.length < state.highWaterMark; - // we must ensure that previous needDrain will not be reset to false. - if (!ret) state.needDrain = true; + /** + * Return raw response as Blob + * + * @return Promise + */ + blob() { + let ct = this.headers && this.headers.get('content-type') || ''; + return consumeBody.call(this).then(function (buf) { + return Object.assign( + // Prevent copying + new Blob([], { + type: ct.toLowerCase() + }), { + [BUFFER]: buf + }); + }); + }, - if (state.writing || state.corked) { - var last = state.lastBufferedRequest; - state.lastBufferedRequest = { - chunk: chunk, - encoding: encoding, - isBuf: isBuf, - callback: cb, - next: null - }; - if (last) { - last.next = state.lastBufferedRequest; - } else { - state.bufferedRequest = state.lastBufferedRequest; - } - state.bufferedRequestCount += 1; - } else { - doWrite(stream, state, false, len, chunk, encoding, cb); - } - - return ret; -} - -function doWrite(stream, state, writev, len, chunk, encoding, cb) { - state.writelen = len; - state.writecb = cb; - state.writing = true; - state.sync = true; - if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); - state.sync = false; -} - -function onwriteError(stream, state, sync, er, cb) { - --state.pendingcb; + /** + * Decode response as json + * + * @return Promise + */ + json() { + var _this2 = this; - if (sync) { - // defer the callback if we are being called synchronously - // to avoid piling up things on the stack - pna.nextTick(cb, er); - // this can emit finish, and it will always happen - // after error - pna.nextTick(finishMaybe, stream, state); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - } else { - // the caller expect this to happen before if - // it is async - cb(er); - stream._writableState.errorEmitted = true; - stream.emit('error', er); - // this can emit finish, but finish must - // always follow error - finishMaybe(stream, state); - } -} + return consumeBody.call(this).then(function (buffer) { + try { + return JSON.parse(buffer.toString()); + } catch (err) { + return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); + } + }); + }, -function onwriteStateUpdate(state) { - state.writing = false; - state.writecb = null; - state.length -= state.writelen; - state.writelen = 0; -} + /** + * Decode response as text + * + * @return Promise + */ + text() { + return consumeBody.call(this).then(function (buffer) { + return buffer.toString(); + }); + }, -function onwrite(stream, er) { - var state = stream._writableState; - var sync = state.sync; - var cb = state.writecb; + /** + * Decode response as buffer (non-spec api) + * + * @return Promise + */ + buffer() { + return consumeBody.call(this); + }, - onwriteStateUpdate(state); + /** + * Decode response as text, while automatically detecting the encoding and + * trying to decode to UTF-8 (non-spec api) + * + * @return Promise + */ + textConverted() { + var _this3 = this; - if (er) onwriteError(stream, state, sync, er, cb);else { - // Check if we're actually ready to finish, but don't emit yet - var finished = needFinish(state); + return consumeBody.call(this).then(function (buffer) { + return convertBody(buffer, _this3.headers); + }); + } +}; - if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { - clearBuffer(stream, state); - } +// In browsers, all properties are enumerable. +Object.defineProperties(Body.prototype, { + body: { enumerable: true }, + bodyUsed: { enumerable: true }, + arrayBuffer: { enumerable: true }, + blob: { enumerable: true }, + json: { enumerable: true }, + text: { enumerable: true } +}); - if (sync) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } else { - afterWrite(stream, state, finished, cb); - } - } -} +Body.mixIn = function (proto) { + for (const name of Object.getOwnPropertyNames(Body.prototype)) { + // istanbul ignore else: future proof + if (!(name in proto)) { + const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); + Object.defineProperty(proto, name, desc); + } + } +}; -function afterWrite(stream, state, finished, cb) { - if (!finished) onwriteDrain(stream, state); - state.pendingcb--; - cb(); - finishMaybe(stream, state); -} +/** + * Consume and convert an entire Body to a Buffer. + * + * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body + * + * @return Promise + */ +function consumeBody() { + var _this4 = this; -// Must force callback to be called on nextTick, so that we don't -// emit 'drain' before the write() consumer gets the 'false' return -// value, and has a chance to attach a 'drain' listener. -function onwriteDrain(stream, state) { - if (state.length === 0 && state.needDrain) { - state.needDrain = false; - stream.emit('drain'); - } -} + if (this[INTERNALS].disturbed) { + return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); + } -// if there's something in the buffer waiting, then process it -function clearBuffer(stream, state) { - state.bufferProcessing = true; - var entry = state.bufferedRequest; + this[INTERNALS].disturbed = true; - if (stream._writev && entry && entry.next) { - // Fast case, write everything using _writev() - var l = state.bufferedRequestCount; - var buffer = new Array(l); - var holder = state.corkedRequestsFree; - holder.entry = entry; + if (this[INTERNALS].error) { + return Body.Promise.reject(this[INTERNALS].error); + } - var count = 0; - var allBuffers = true; - while (entry) { - buffer[count] = entry; - if (!entry.isBuf) allBuffers = false; - entry = entry.next; - count += 1; - } - buffer.allBuffers = allBuffers; + let body = this.body; - doWrite(stream, state, true, state.length, buffer, '', holder.finish); + // body is null + if (body === null) { + return Body.Promise.resolve(Buffer.alloc(0)); + } - // doWrite is almost always async, defer these to save a bit of time - // as the hot path ends with doWrite - state.pendingcb++; - state.lastBufferedRequest = null; - if (holder.next) { - state.corkedRequestsFree = holder.next; - holder.next = null; - } else { - state.corkedRequestsFree = new CorkedRequest(state); - } - state.bufferedRequestCount = 0; - } else { - // Slow case, write chunks one-by-one - while (entry) { - var chunk = entry.chunk; - var encoding = entry.encoding; - var cb = entry.callback; - var len = state.objectMode ? 1 : chunk.length; + // body is blob + if (isBlob(body)) { + body = body.stream(); + } - doWrite(stream, state, false, len, chunk, encoding, cb); - entry = entry.next; - state.bufferedRequestCount--; - // if we didn't call the onwrite immediately, then - // it means that we need to wait until it does. - // also, that means that the chunk and cb are currently - // being processed, so move the buffer counter past them. - if (state.writing) { - break; - } - } + // body is buffer + if (Buffer.isBuffer(body)) { + return Body.Promise.resolve(body); + } - if (entry === null) state.lastBufferedRequest = null; - } + // istanbul ignore if: should never happen + if (!(body instanceof Stream)) { + return Body.Promise.resolve(Buffer.alloc(0)); + } - state.bufferedRequest = entry; - state.bufferProcessing = false; -} + // body is stream + // get ready to actually consume the body + let accum = []; + let accumBytes = 0; + let abort = false; -Writable.prototype._write = function (chunk, encoding, cb) { - cb(new Error('_write() is not implemented')); -}; + return new Body.Promise(function (resolve, reject) { + let resTimeout; -Writable.prototype._writev = null; + // allow timeout on slow response body + if (_this4.timeout) { + resTimeout = setTimeout(function () { + abort = true; + reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); + }, _this4.timeout); + } -Writable.prototype.end = function (chunk, encoding, cb) { - var state = this._writableState; + // handle stream errors + body.on('error', function (err) { + if (err.name === 'AbortError') { + // if the request was aborted, reject with this Error + abort = true; + reject(err); + } else { + // other errors, such as incorrect content-encoding + reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); + } + }); - if (typeof chunk === 'function') { - cb = chunk; - chunk = null; - encoding = null; - } else if (typeof encoding === 'function') { - cb = encoding; - encoding = null; - } + body.on('data', function (chunk) { + if (abort || chunk === null) { + return; + } - if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); + if (_this4.size && accumBytes + chunk.length > _this4.size) { + abort = true; + reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); + return; + } - // .end() fully uncorks - if (state.corked) { - state.corked = 1; - this.uncork(); - } + accumBytes += chunk.length; + accum.push(chunk); + }); - // ignore unnecessary end() calls. - if (!state.ending) endWritable(this, state, cb); -}; + body.on('end', function () { + if (abort) { + return; + } -function needFinish(state) { - return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; -} -function callFinal(stream, state) { - stream._final(function (err) { - state.pendingcb--; - if (err) { - stream.emit('error', err); - } - state.prefinished = true; - stream.emit('prefinish'); - finishMaybe(stream, state); - }); -} -function prefinish(stream, state) { - if (!state.prefinished && !state.finalCalled) { - if (typeof stream._final === 'function') { - state.pendingcb++; - state.finalCalled = true; - pna.nextTick(callFinal, stream, state); - } else { - state.prefinished = true; - stream.emit('prefinish'); - } - } -} + clearTimeout(resTimeout); -function finishMaybe(stream, state) { - var need = needFinish(state); - if (need) { - prefinish(stream, state); - if (state.pendingcb === 0) { - state.finished = true; - stream.emit('finish'); - } - } - return need; + try { + resolve(Buffer.concat(accum, accumBytes)); + } catch (err) { + // handle streams that have accumulated too much data (issue #414) + reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); + } + }); + }); } -function endWritable(stream, state, cb) { - state.ending = true; - finishMaybe(stream, state); - if (cb) { - if (state.finished) pna.nextTick(cb);else stream.once('finish', cb); - } - state.ended = true; - stream.writable = false; -} +/** + * Detect buffer encoding and convert to target encoding + * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding + * + * @param Buffer buffer Incoming buffer + * @param String encoding Target encoding + * @return String + */ +function convertBody(buffer, headers) { + if (typeof convert !== 'function') { + throw new Error('The package `encoding` must be installed to use the textConverted() function'); + } -function onCorkedFinish(corkReq, state, err) { - var entry = corkReq.entry; - corkReq.entry = null; - while (entry) { - var cb = entry.callback; - state.pendingcb--; - cb(err); - entry = entry.next; - } + const ct = headers.get('content-type'); + let charset = 'utf-8'; + let res, str; - // reuse the free corkReq. - state.corkedRequestsFree.next = corkReq; -} + // header + if (ct) { + res = /charset=([^;]*)/i.exec(ct); + } -Object.defineProperty(Writable.prototype, 'destroyed', { - get: function () { - if (this._writableState === undefined) { - return false; - } - return this._writableState.destroyed; - }, - set: function (value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._writableState) { - return; - } + // no charset in content type, peek at response body for at most 1024 bytes + str = buffer.slice(0, 1024).toString(); - // backward compatibility, the user is explicitly - // managing destroyed - this._writableState.destroyed = value; - } -}); + // html5 + if (!res && str) { + res = / { + // xml + if (!res && str) { + res = /<\?xml.+?encoding=(['"])(.+?)\1/i.exec(str); + } -"use strict"; + // found charset + if (res) { + charset = res.pop(); + // prevent decode issues when sites use incorrect encoding + // ref: https://hsivonen.fi/encoding-menu/ + if (charset === 'gb2312' || charset === 'gbk') { + charset = 'gb18030'; + } + } -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } + // turn raw buffers into a single utf-8 buffer + return convert(buffer, 'UTF-8', charset).toString(); +} -var Buffer = (__nccwpck_require__(15054).Buffer); -var util = __nccwpck_require__(73837); +/** + * Detect a URLSearchParams object + * ref: https://github.com/bitinn/node-fetch/issues/296#issuecomment-307598143 + * + * @param Object obj Object to detect by type or brand + * @return String + */ +function isURLSearchParams(obj) { + // Duck-typing as a necessary condition. + if (typeof obj !== 'object' || typeof obj.append !== 'function' || typeof obj.delete !== 'function' || typeof obj.get !== 'function' || typeof obj.getAll !== 'function' || typeof obj.has !== 'function' || typeof obj.set !== 'function') { + return false; + } -function copyBuffer(src, target, offset) { - src.copy(target, offset); + // Brand-checking and more duck-typing as optional condition. + return obj.constructor.name === 'URLSearchParams' || Object.prototype.toString.call(obj) === '[object URLSearchParams]' || typeof obj.sort === 'function'; } -module.exports = function () { - function BufferList() { - _classCallCheck(this, BufferList); +/** + * Check if `obj` is a W3C `Blob` object (which `File` inherits from) + * @param {*} obj + * @return {boolean} + */ +function isBlob(obj) { + return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]); +} - this.head = null; - this.tail = null; - this.length = 0; - } +/** + * Clone body given Res/Req instance + * + * @param Mixed instance Response or Request instance + * @return Mixed + */ +function clone(instance) { + let p1, p2; + let body = instance.body; - BufferList.prototype.push = function push(v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; + // don't allow cloning a used body + if (instance.bodyUsed) { + throw new Error('cannot clone body after it is used'); + } - BufferList.prototype.unshift = function unshift(v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; - - BufferList.prototype.shift = function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; + // check that body is a stream and not form-data object + // note: we can't clone the form-data object without having it as a dependency + if (body instanceof Stream && typeof body.getBoundary !== 'function') { + // tee instance body + p1 = new PassThrough(); + p2 = new PassThrough(); + body.pipe(p1); + body.pipe(p2); + // set instance body to teed body and return the other teed body + instance[INTERNALS].body = p1; + body = p2; + } - BufferList.prototype.clear = function clear() { - this.head = this.tail = null; - this.length = 0; - }; + return body; +} - BufferList.prototype.join = function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; +/** + * Performs the operation "extract a `Content-Type` value from |object|" as + * specified in the specification: + * https://fetch.spec.whatwg.org/#concept-bodyinit-extract + * + * This function assumes that instance.body is present. + * + * @param Mixed instance Any options.body input + */ +function extractContentType(body) { + if (body === null) { + // body is null + return null; + } else if (typeof body === 'string') { + // body is string + return 'text/plain;charset=UTF-8'; + } else if (isURLSearchParams(body)) { + // body is a URLSearchParams + return 'application/x-www-form-urlencoded;charset=UTF-8'; + } else if (isBlob(body)) { + // body is blob + return body.type || null; + } else if (Buffer.isBuffer(body)) { + // body is buffer + return null; + } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { + // body is ArrayBuffer + return null; + } else if (ArrayBuffer.isView(body)) { + // body is ArrayBufferView + return null; + } else if (typeof body.getBoundary === 'function') { + // detect form data input from form-data module + return `multipart/form-data;boundary=${body.getBoundary()}`; + } else if (body instanceof Stream) { + // body is stream + // can't really do much about this + return null; + } else { + // Body constructor defaults other things to string + return 'text/plain;charset=UTF-8'; + } +} - BufferList.prototype.concat = function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - return ret; - }; +/** + * The Fetch Standard treats this as if "total bytes" is a property on the body. + * For us, we have to explicitly get it with a function. + * + * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes + * + * @param Body instance Instance of Body + * @return Number? Number of bytes, or null if not possible + */ +function getTotalBytes(instance) { + const body = instance.body; - return BufferList; -}(); -if (util && util.inspect && util.inspect.custom) { - module.exports.prototype[util.inspect.custom] = function () { - var obj = util.inspect({ length: this.length }); - return this.constructor.name + ' ' + obj; - }; + if (body === null) { + // body is null + return 0; + } else if (isBlob(body)) { + return body.size; + } else if (Buffer.isBuffer(body)) { + // body is buffer + return body.length; + } else if (body && typeof body.getLengthSync === 'function') { + // detect form data input from form-data module + if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x + body.hasKnownLength && body.hasKnownLength()) { + // 2.x + return body.getLengthSync(); + } + return null; + } else { + // body is stream + return null; + } } -/***/ }), +/** + * Write a Body to a Node.js WritableStream (e.g. http.Request) object. + * + * @param Body instance Instance of Body + * @return Void + */ +function writeToStream(dest, instance) { + const body = instance.body; -/***/ 78999: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; + if (body === null) { + // body is null + dest.end(); + } else if (isBlob(body)) { + body.stream().pipe(dest); + } else if (Buffer.isBuffer(body)) { + // body is buffer + dest.write(body); + dest.end(); + } else { + // body is stream + body.pipe(dest); + } +} +// expose Promise +Body.Promise = global.Promise; -/**/ +/** + * headers.js + * + * Headers class offers convenient helpers + */ -var pna = __nccwpck_require__(47810); -/**/ +const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/; +const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/; -// undocumented cb() API, needed for core, not for public API -function destroy(err, cb) { - var _this = this; +function validateName(name) { + name = `${name}`; + if (invalidTokenRegex.test(name) || name === '') { + throw new TypeError(`${name} is not a legal HTTP header name`); + } +} - var readableDestroyed = this._readableState && this._readableState.destroyed; - var writableDestroyed = this._writableState && this._writableState.destroyed; +function validateValue(value) { + value = `${value}`; + if (invalidHeaderCharRegex.test(value)) { + throw new TypeError(`${value} is not a legal HTTP header value`); + } +} - if (readableDestroyed || writableDestroyed) { - if (cb) { - cb(err); - } else if (err) { - if (!this._writableState) { - pna.nextTick(emitErrorNT, this, err); - } else if (!this._writableState.errorEmitted) { - this._writableState.errorEmitted = true; - pna.nextTick(emitErrorNT, this, err); - } - } +/** + * Find the key in the map object given a header name. + * + * Returns undefined if not found. + * + * @param String name Header name + * @return String|Undefined + */ +function find(map, name) { + name = name.toLowerCase(); + for (const key in map) { + if (key.toLowerCase() === name) { + return key; + } + } + return undefined; +} - return this; - } +const MAP = Symbol('map'); +class Headers { + /** + * Headers class + * + * @param Object headers Response headers + * @return Void + */ + constructor() { + let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; - // we set destroyed to true before firing error callbacks in order - // to make it re-entrance safe in case destroy() is called within callbacks + this[MAP] = Object.create(null); - if (this._readableState) { - this._readableState.destroyed = true; - } + if (init instanceof Headers) { + const rawHeaders = init.raw(); + const headerNames = Object.keys(rawHeaders); - // if this is a duplex stream mark the writable part as destroyed as well - if (this._writableState) { - this._writableState.destroyed = true; - } + for (const headerName of headerNames) { + for (const value of rawHeaders[headerName]) { + this.append(headerName, value); + } + } - this._destroy(err || null, function (err) { - if (!cb && err) { - if (!_this._writableState) { - pna.nextTick(emitErrorNT, _this, err); - } else if (!_this._writableState.errorEmitted) { - _this._writableState.errorEmitted = true; - pna.nextTick(emitErrorNT, _this, err); - } - } else if (cb) { - cb(err); - } - }); + return; + } - return this; -} + // We don't worry about converting prop to ByteString here as append() + // will handle it. + if (init == null) ; else if (typeof init === 'object') { + const method = init[Symbol.iterator]; + if (method != null) { + if (typeof method !== 'function') { + throw new TypeError('Header pairs must be iterable'); + } -function undestroy() { - if (this._readableState) { - this._readableState.destroyed = false; - this._readableState.reading = false; - this._readableState.ended = false; - this._readableState.endEmitted = false; - } + // sequence> + // Note: per spec we have to first exhaust the lists then process them + const pairs = []; + for (const pair of init) { + if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { + throw new TypeError('Each header pair must be iterable'); + } + pairs.push(Array.from(pair)); + } - if (this._writableState) { - this._writableState.destroyed = false; - this._writableState.ended = false; - this._writableState.ending = false; - this._writableState.finalCalled = false; - this._writableState.prefinished = false; - this._writableState.finished = false; - this._writableState.errorEmitted = false; - } -} + for (const pair of pairs) { + if (pair.length !== 2) { + throw new TypeError('Each header pair must be a name/value tuple'); + } + this.append(pair[0], pair[1]); + } + } else { + // record + for (const key of Object.keys(init)) { + const value = init[key]; + this.append(key, value); + } + } + } else { + throw new TypeError('Provided initializer must be an object'); + } + } -function emitErrorNT(self, err) { - self.emit('error', err); -} + /** + * Return combined header value given name + * + * @param String name Header name + * @return Mixed + */ + get(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key === undefined) { + return null; + } -module.exports = { - destroy: destroy, - undestroy: undestroy -}; + return this[MAP][key].join(', '); + } -/***/ }), + /** + * Iterate over all headers + * + * @param Function callback Executed for each item with parameters (value, name, thisArg) + * @param Boolean thisArg `this` context for callback function + * @return Void + */ + forEach(callback) { + let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; -/***/ 58745: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + let pairs = getHeaders(this); + let i = 0; + while (i < pairs.length) { + var _pairs$i = pairs[i]; + const name = _pairs$i[0], + value = _pairs$i[1]; -module.exports = __nccwpck_require__(12781); + callback.call(thisArg, value, name, this); + pairs = getHeaders(this); + i++; + } + } + /** + * Overwrite header values given name + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + set(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + this[MAP][key !== undefined ? key : name] = [value]; + } -/***/ }), + /** + * Append a value onto existing header + * + * @param String name Header name + * @param String value Header value + * @return Void + */ + append(name, value) { + name = `${name}`; + value = `${value}`; + validateName(name); + validateValue(value); + const key = find(this[MAP], name); + if (key !== undefined) { + this[MAP][key].push(value); + } else { + this[MAP][name] = [value]; + } + } -/***/ 27818: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * Check for header name existence + * + * @param String name Header name + * @return Boolean + */ + has(name) { + name = `${name}`; + validateName(name); + return find(this[MAP], name) !== undefined; + } -module.exports = __nccwpck_require__(22399).PassThrough + /** + * Delete all header values given name + * + * @param String name Header name + * @return Void + */ + delete(name) { + name = `${name}`; + validateName(name); + const key = find(this[MAP], name); + if (key !== undefined) { + delete this[MAP][key]; + } + } + /** + * Return raw headers (non-spec api) + * + * @return Object + */ + raw() { + return this[MAP]; + } -/***/ }), + /** + * Get an iterator on keys. + * + * @return Iterator + */ + keys() { + return createHeadersIterator(this, 'key'); + } -/***/ 22399: -/***/ ((module, exports, __nccwpck_require__) => { + /** + * Get an iterator on values. + * + * @return Iterator + */ + values() { + return createHeadersIterator(this, 'value'); + } -var Stream = __nccwpck_require__(12781); -if (process.env.READABLE_STREAM === 'disable' && Stream) { - module.exports = Stream; - exports = module.exports = Stream.Readable; - exports.Readable = Stream.Readable; - exports.Writable = Stream.Writable; - exports.Duplex = Stream.Duplex; - exports.Transform = Stream.Transform; - exports.PassThrough = Stream.PassThrough; - exports.Stream = Stream; -} else { - exports = module.exports = __nccwpck_require__(99140); - exports.Stream = Stream || exports; - exports.Readable = exports; - exports.Writable = __nccwpck_require__(14960); - exports.Duplex = __nccwpck_require__(5706); - exports.Transform = __nccwpck_require__(75072); - exports.PassThrough = __nccwpck_require__(70982); + /** + * Get an iterator on entries. + * + * This is the default iterator of the Headers object. + * + * @return Iterator + */ + [Symbol.iterator]() { + return createHeadersIterator(this, 'key+value'); + } } +Headers.prototype.entries = Headers.prototype[Symbol.iterator]; +Object.defineProperty(Headers.prototype, Symbol.toStringTag, { + value: 'Headers', + writable: false, + enumerable: false, + configurable: true +}); -/***/ }), +Object.defineProperties(Headers.prototype, { + get: { enumerable: true }, + forEach: { enumerable: true }, + set: { enumerable: true }, + append: { enumerable: true }, + has: { enumerable: true }, + delete: { enumerable: true }, + keys: { enumerable: true }, + values: { enumerable: true }, + entries: { enumerable: true } +}); -/***/ 15054: -/***/ ((module, exports, __nccwpck_require__) => { +function getHeaders(headers) { + let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; -/* eslint-disable node/no-deprecated-api */ -var buffer = __nccwpck_require__(14300) -var Buffer = buffer.Buffer + const keys = Object.keys(headers[MAP]).sort(); + return keys.map(kind === 'key' ? function (k) { + return k.toLowerCase(); + } : kind === 'value' ? function (k) { + return headers[MAP][k].join(', '); + } : function (k) { + return [k.toLowerCase(), headers[MAP][k].join(', ')]; + }); +} -// alternative to using Object.keys for old browsers -function copyProps (src, dst) { - for (var key in src) { - dst[key] = src[key] - } -} -if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { - module.exports = buffer -} else { - // Copy properties from require('buffer') - copyProps(buffer, exports) - exports.Buffer = SafeBuffer -} +const INTERNAL = Symbol('internal'); -function SafeBuffer (arg, encodingOrOffset, length) { - return Buffer(arg, encodingOrOffset, length) +function createHeadersIterator(target, kind) { + const iterator = Object.create(HeadersIteratorPrototype); + iterator[INTERNAL] = { + target, + kind, + index: 0 + }; + return iterator; } -// Copy static methods from Buffer -copyProps(Buffer, SafeBuffer) +const HeadersIteratorPrototype = Object.setPrototypeOf({ + next() { + // istanbul ignore if + if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { + throw new TypeError('Value of `this` is not a HeadersIterator'); + } -SafeBuffer.from = function (arg, encodingOrOffset, length) { - if (typeof arg === 'number') { - throw new TypeError('Argument must not be a number') - } - return Buffer(arg, encodingOrOffset, length) -} + var _INTERNAL = this[INTERNAL]; + const target = _INTERNAL.target, + kind = _INTERNAL.kind, + index = _INTERNAL.index; -SafeBuffer.alloc = function (size, fill, encoding) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - var buf = Buffer(size) - if (fill !== undefined) { - if (typeof encoding === 'string') { - buf.fill(fill, encoding) - } else { - buf.fill(fill) - } - } else { - buf.fill(0) - } - return buf -} + const values = getHeaders(target, kind); + const len = values.length; + if (index >= len) { + return { + value: undefined, + done: true + }; + } -SafeBuffer.allocUnsafe = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return Buffer(size) -} + this[INTERNAL].index = index + 1; -SafeBuffer.allocUnsafeSlow = function (size) { - if (typeof size !== 'number') { - throw new TypeError('Argument must be a number') - } - return buffer.SlowBuffer(size) -} + return { + value: values[index], + done: false + }; + } +}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); +Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { + value: 'HeadersIterator', + writable: false, + enumerable: false, + configurable: true +}); -/***/ }), +/** + * Export the Headers object in a form that Node.js can consume. + * + * @param Headers headers + * @return Object + */ +function exportNodeCompatibleHeaders(headers) { + const obj = Object.assign({ __proto__: null }, headers[MAP]); -/***/ 24749: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // http.request() only supports string as Host header. This hack makes + // specifying custom Host header possible. + const hostHeaderKey = find(headers[MAP], 'Host'); + if (hostHeaderKey !== undefined) { + obj[hostHeaderKey] = obj[hostHeaderKey][0]; + } -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + return obj; +} +/** + * Create a Headers object from an object of headers, ignoring those that do + * not conform to HTTP grammar productions. + * + * @param Object obj Object of headers + * @return Headers + */ +function createHeadersLenient(obj) { + const headers = new Headers(); + for (const name of Object.keys(obj)) { + if (invalidTokenRegex.test(name)) { + continue; + } + if (Array.isArray(obj[name])) { + for (const val of obj[name]) { + if (invalidHeaderCharRegex.test(val)) { + continue; + } + if (headers[MAP][name] === undefined) { + headers[MAP][name] = [val]; + } else { + headers[MAP][name].push(val); + } + } + } else if (!invalidHeaderCharRegex.test(obj[name])) { + headers[MAP][name] = [obj[name]]; + } + } + return headers; +} +const INTERNALS$1 = Symbol('Response internals'); -/**/ +// fix an issue where "STATUS_CODES" aren't a named export for node <10 +const STATUS_CODES = http.STATUS_CODES; -var Buffer = (__nccwpck_require__(15054).Buffer); -/**/ +/** + * Response class + * + * @param Stream body Readable stream + * @param Object opts Response options + * @return Void + */ +class Response { + constructor() { + let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; + let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; -var isEncoding = Buffer.isEncoding || function (encoding) { - encoding = '' + encoding; - switch (encoding && encoding.toLowerCase()) { - case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': - return true; - default: - return false; - } -}; + Body.call(this, body, opts); -function _normalizeEncoding(enc) { - if (!enc) return 'utf8'; - var retried; - while (true) { - switch (enc) { - case 'utf8': - case 'utf-8': - return 'utf8'; - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return 'utf16le'; - case 'latin1': - case 'binary': - return 'latin1'; - case 'base64': - case 'ascii': - case 'hex': - return enc; - default: - if (retried) return; // undefined - enc = ('' + enc).toLowerCase(); - retried = true; - } - } -}; + const status = opts.status || 200; + const headers = new Headers(opts.headers); -// Do not cache `Buffer.isEncoding` when checking encoding names as some -// modules monkey-patch it to support additional encodings -function normalizeEncoding(enc) { - var nenc = _normalizeEncoding(enc); - if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); - return nenc || enc; -} + if (body != null && !headers.has('Content-Type')) { + const contentType = extractContentType(body); + if (contentType) { + headers.append('Content-Type', contentType); + } + } -// StringDecoder provides an interface for efficiently splitting a series of -// buffers into a series of JS strings without breaking apart multi-byte -// characters. -exports.s = StringDecoder; -function StringDecoder(encoding) { - this.encoding = normalizeEncoding(encoding); - var nb; - switch (this.encoding) { - case 'utf16le': - this.text = utf16Text; - this.end = utf16End; - nb = 4; - break; - case 'utf8': - this.fillLast = utf8FillLast; - nb = 4; - break; - case 'base64': - this.text = base64Text; - this.end = base64End; - nb = 3; - break; - default: - this.write = simpleWrite; - this.end = simpleEnd; - return; - } - this.lastNeed = 0; - this.lastTotal = 0; - this.lastChar = Buffer.allocUnsafe(nb); -} + this[INTERNALS$1] = { + url: opts.url, + status, + statusText: opts.statusText || STATUS_CODES[status], + headers, + counter: opts.counter + }; + } -StringDecoder.prototype.write = function (buf) { - if (buf.length === 0) return ''; - var r; - var i; - if (this.lastNeed) { - r = this.fillLast(buf); - if (r === undefined) return ''; - i = this.lastNeed; - this.lastNeed = 0; - } else { - i = 0; - } - if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); - return r || ''; -}; + get url() { + return this[INTERNALS$1].url || ''; + } -StringDecoder.prototype.end = utf8End; + get status() { + return this[INTERNALS$1].status; + } -// Returns only complete characters in a Buffer -StringDecoder.prototype.text = utf8Text; + /** + * Convenience property representing if the request ended normally + */ + get ok() { + return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; + } -// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer -StringDecoder.prototype.fillLast = function (buf) { - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); - this.lastNeed -= buf.length; -}; + get redirected() { + return this[INTERNALS$1].counter > 0; + } -// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a -// continuation byte. If an invalid byte is detected, -2 is returned. -function utf8CheckByte(byte) { - if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; - return byte >> 6 === 0x02 ? -1 : -2; -} + get statusText() { + return this[INTERNALS$1].statusText; + } -// Checks at most 3 bytes at the end of a Buffer in order to detect an -// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) -// needed to complete the UTF-8 character (if applicable) are returned. -function utf8CheckIncomplete(self, buf, i) { - var j = buf.length - 1; - if (j < i) return 0; - var nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 1; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) self.lastNeed = nb - 2; - return nb; - } - if (--j < i || nb === -2) return 0; - nb = utf8CheckByte(buf[j]); - if (nb >= 0) { - if (nb > 0) { - if (nb === 2) nb = 0;else self.lastNeed = nb - 3; - } - return nb; - } - return 0; -} + get headers() { + return this[INTERNALS$1].headers; + } -// Validates as many continuation bytes for a multi-byte UTF-8 character as -// needed or are available. If we see a non-continuation byte where we expect -// one, we "replace" the validated continuation bytes we've seen so far with -// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding -// behavior. The continuation byte check is included three times in the case -// where all of the continuation bytes for a character exist in the same buffer. -// It is also done this way as a slight performance increase instead of using a -// loop. -function utf8CheckExtraBytes(self, buf, p) { - if ((buf[0] & 0xC0) !== 0x80) { - self.lastNeed = 0; - return '\ufffd'; - } - if (self.lastNeed > 1 && buf.length > 1) { - if ((buf[1] & 0xC0) !== 0x80) { - self.lastNeed = 1; - return '\ufffd'; - } - if (self.lastNeed > 2 && buf.length > 2) { - if ((buf[2] & 0xC0) !== 0x80) { - self.lastNeed = 2; - return '\ufffd'; - } - } - } + /** + * Clone this response + * + * @return Response + */ + clone() { + return new Response(clone(this), { + url: this.url, + status: this.status, + statusText: this.statusText, + headers: this.headers, + ok: this.ok, + redirected: this.redirected + }); + } } -// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. -function utf8FillLast(buf) { - var p = this.lastTotal - this.lastNeed; - var r = utf8CheckExtraBytes(this, buf, p); - if (r !== undefined) return r; - if (this.lastNeed <= buf.length) { - buf.copy(this.lastChar, p, 0, this.lastNeed); - return this.lastChar.toString(this.encoding, 0, this.lastTotal); - } - buf.copy(this.lastChar, p, 0, buf.length); - this.lastNeed -= buf.length; -} +Body.mixIn(Response.prototype); -// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a -// partial character, the character's bytes are buffered until the required -// number of bytes are available. -function utf8Text(buf, i) { - var total = utf8CheckIncomplete(this, buf, i); - if (!this.lastNeed) return buf.toString('utf8', i); - this.lastTotal = total; - var end = buf.length - (total - this.lastNeed); - buf.copy(this.lastChar, 0, end); - return buf.toString('utf8', i, end); -} +Object.defineProperties(Response.prototype, { + url: { enumerable: true }, + status: { enumerable: true }, + ok: { enumerable: true }, + redirected: { enumerable: true }, + statusText: { enumerable: true }, + headers: { enumerable: true }, + clone: { enumerable: true } +}); -// For UTF-8, a replacement character is added when ending on a partial -// character. -function utf8End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + '\ufffd'; - return r; -} +Object.defineProperty(Response.prototype, Symbol.toStringTag, { + value: 'Response', + writable: false, + enumerable: false, + configurable: true +}); -// UTF-16LE typically needs two bytes per character, but even if we have an even -// number of bytes available, we need to check if we end on a leading/high -// surrogate. In that case, we need to wait for the next two bytes in order to -// decode the last character properly. -function utf16Text(buf, i) { - if ((buf.length - i) % 2 === 0) { - var r = buf.toString('utf16le', i); - if (r) { - var c = r.charCodeAt(r.length - 1); - if (c >= 0xD800 && c <= 0xDBFF) { - this.lastNeed = 2; - this.lastTotal = 4; - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - return r.slice(0, -1); - } - } - return r; - } - this.lastNeed = 1; - this.lastTotal = 2; - this.lastChar[0] = buf[buf.length - 1]; - return buf.toString('utf16le', i, buf.length - 1); -} +const INTERNALS$2 = Symbol('Request internals'); +const URL = Url.URL || whatwgUrl.URL; -// For UTF-16LE we do not explicitly append special replacement characters if we -// end on a partial character, we simply let v8 handle that. -function utf16End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) { - var end = this.lastTotal - this.lastNeed; - return r + this.lastChar.toString('utf16le', 0, end); - } - return r; -} +// fix an issue where "format", "parse" aren't a named export for node <10 +const parse_url = Url.parse; +const format_url = Url.format; -function base64Text(buf, i) { - var n = (buf.length - i) % 3; - if (n === 0) return buf.toString('base64', i); - this.lastNeed = 3 - n; - this.lastTotal = 3; - if (n === 1) { - this.lastChar[0] = buf[buf.length - 1]; - } else { - this.lastChar[0] = buf[buf.length - 2]; - this.lastChar[1] = buf[buf.length - 1]; - } - return buf.toString('base64', i, buf.length - n); -} +/** + * Wrapper around `new URL` to handle arbitrary URLs + * + * @param {string} urlStr + * @return {void} + */ +function parseURL(urlStr) { + /* + Check whether the URL is absolute or not + Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 + Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 + */ + if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { + urlStr = new URL(urlStr).toString(); + } -function base64End(buf) { - var r = buf && buf.length ? this.write(buf) : ''; - if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); - return r; + // Fallback to old implementation for arbitrary URLs + return parse_url(urlStr); } -// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) -function simpleWrite(buf) { - return buf.toString(this.encoding); -} +const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; -function simpleEnd(buf) { - return buf && buf.length ? this.write(buf) : ''; +/** + * Check if a value is an instance of Request. + * + * @param Mixed input + * @return Boolean + */ +function isRequest(input) { + return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; } -/***/ }), - -/***/ 11289: -/***/ ((module) => { +function isAbortSignal(signal) { + const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); + return !!(proto && proto.constructor.name === 'AbortSignal'); +} /** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Request class + * + * @param Mixed input Url or Request instance + * @param Object init Custom options + * @return Void */ +class Request { + constructor(input) { + let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; + let parsedURL; -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; + // normalize input + if (!isRequest(input)) { + if (input && input.href) { + // in order to support Node.js' Url objects; though WHATWG's URL objects + // will fall into this branch also (since their `toString()` will return + // `href` property anyway) + parsedURL = parseURL(input.href); + } else { + // coerce input to a string before attempting to parse + parsedURL = parseURL(`${input}`); + } + input = {}; + } else { + parsedURL = parseURL(input.url); + } -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; + let method = init.method || input.method || 'GET'; + method = method.toUpperCase(); -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ -function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); -} + if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { + throw new TypeError('Request with GET/HEAD method cannot have body'); + } -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); + let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} + Body.call(this, inputBody, { + timeout: init.timeout || input.timeout || 0, + size: init.size || input.size || 0 + }); -/** Used for built-in method references. */ -var objectProto = Object.prototype; + const headers = new Headers(init.headers || input.headers || {}); -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + if (inputBody != null && !headers.has('Content-Type')) { + const contentType = extractContentType(inputBody); + if (contentType) { + headers.append('Content-Type', contentType); + } + } -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + let signal = isRequest(input) ? input.signal : null; + if ('signal' in init) signal = init.signal; -/** Built-in value references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable; + if (signal != null && !isAbortSignal(signal)) { + throw new TypeError('Expected signal to be an instanceof AbortSignal'); + } -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; + this[INTERNALS$2] = { + method, + redirect: init.redirect || input.redirect || 'follow', + headers, + parsedURL, + signal + }; -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; + // node-fetch-only options + this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; + this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; + this.counter = init.counter || input.counter || 0; + this.agent = init.agent || input.agent; + } - var length = result.length, - skipIndexes = !!length; + get method() { + return this[INTERNALS$2].method; + } - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } - } - return result; -} + get url() { + return format_url(this[INTERNALS$2].parsedURL); + } -/** - * Used by `_.defaults` to customize its `_.assignIn` use. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. - */ -function assignInDefaults(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; - } - return objValue; -} + get headers() { + return this[INTERNALS$2].headers; + } -/** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - object[key] = value; - } -} + get redirect() { + return this[INTERNALS$2].redirect; + } -/** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; + get signal() { + return this[INTERNALS$2].signal; + } - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; + /** + * Clone this request + * + * @return Request + */ + clone() { + return new Request(this); + } } -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); +Body.mixIn(Request.prototype); - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; -} +Object.defineProperty(Request.prototype, Symbol.toStringTag, { + value: 'Request', + writable: false, + enumerable: false, + configurable: true +}); + +Object.defineProperties(Request.prototype, { + method: { enumerable: true }, + url: { enumerable: true }, + headers: { enumerable: true }, + redirect: { enumerable: true }, + clone: { enumerable: true }, + signal: { enumerable: true } +}); /** - * Copies properties of `source` to `object`. + * Convert a Request to Node.js http request options. * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. + * @param Request A Request instance + * @return Object The options object to be passed to http.request */ -function copyObject(source, props, object, customizer) { - object || (object = {}); +function getNodeRequestOptions(request) { + const parsedURL = request[INTERNALS$2].parsedURL; + const headers = new Headers(request[INTERNALS$2].headers); - var index = -1, - length = props.length; + // fetch step 1.3 + if (!headers.has('Accept')) { + headers.set('Accept', '*/*'); + } - while (++index < length) { - var key = props[index]; + // Basic fetch + if (!parsedURL.protocol || !parsedURL.hostname) { + throw new TypeError('Only absolute URLs are supported'); + } - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; + if (!/^https?:$/.test(parsedURL.protocol)) { + throw new TypeError('Only HTTP(S) protocols are supported'); + } - assignValue(object, key, newValue === undefined ? source[key] : newValue); - } - return object; -} + if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { + throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); + } -/** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ -function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; + // HTTP-network-or-cache fetch steps 2.4-2.7 + let contentLengthValue = null; + if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { + contentLengthValue = '0'; + } + if (request.body != null) { + const totalBytes = getTotalBytes(request); + if (typeof totalBytes === 'number') { + contentLengthValue = String(totalBytes); + } + } + if (contentLengthValue) { + headers.set('Content-Length', contentLengthValue); + } - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; + // HTTP-network-or-cache fetch step 2.11 + if (!headers.has('User-Agent')) { + headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); + } - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); -} + // HTTP-network-or-cache fetch step 2.15 + if (request.compress && !headers.has('Accept-Encoding')) { + headers.set('Accept-Encoding', 'gzip,deflate'); + } -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); + let agent = request.agent; + if (typeof agent === 'function') { + agent = agent(parsedURL); + } + + // HTTP-network fetch step 4.2 + // chunked encoding is handled by Node.js + + return Object.assign({}, parsedURL, { + method: request.method, + headers: exportNodeCompatibleHeaders(headers), + agent + }); } /** - * Checks if the given arguments are from an iteratee call. + * abort-error.js * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. + * AbortError interface for cancelled requests */ -function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; -} /** - * Checks if `value` is likely a prototype object. + * Create AbortError instance * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + * @param String message Error message for human + * @return AbortError */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; +function AbortError(message) { + Error.call(this, message); - return value === proto; -} + this.type = 'aborted'; + this.message = message; -/** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; + // hide custom error implementation details from end-users + Error.captureStackTrace(this, this.constructor); } -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); -} +AbortError.prototype = Object.create(Error.prototype); +AbortError.prototype.constructor = AbortError; +AbortError.prototype.name = 'AbortError'; + +const URL$1 = Url.URL || whatwgUrl.URL; + +// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 +const PassThrough$1 = Stream.PassThrough; + +const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { + const orig = new URL$1(original).hostname; + const dest = new URL$1(destination).hostname; + + return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); +}; /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true + * isSameProtocol reports whether the two provided URLs use the same protocol. * - * _.isArguments([1, 2, 3]); - * // => false + * Both domains must already be in canonical form. + * @param {string|URL} original + * @param {string|URL} destination */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} +const isSameProtocol = function isSameProtocol(destination, original) { + const orig = new URL$1(original).protocol; + const dest = new URL$1(destination).protocol; + + return orig === dest; +}; /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false + * Fetch function * - * _.isArray(_.noop); - * // => false + * @param Mixed url Absolute url or Request instance + * @param Object opts Fetch options + * @return Promise */ -var isArray = Array.isArray; +function fetch(url, opts) { -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} + // allow custom promise + if (!fetch.Promise) { + throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); + } -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} + Body.Promise = fetch.Promise; -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} + // wrap http.request into fetch + return new fetch.Promise(function (resolve, reject) { + // build request object + const request = new Request(url, opts); + const options = getNodeRequestOptions(request); -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} + const send = (options.protocol === 'https:' ? https : http).request; + const signal = request.signal; -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} + let response = null; -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} + const abort = function abort() { + let error = new AbortError('The user aborted a request.'); + reject(error); + if (request.body && request.body instanceof Stream.Readable) { + destroyStream(request.body, error); + } + if (!response || !response.body) return; + response.body.emit('error', error); + }; -/** - * This method is like `_.assignIn` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extendWith - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ -var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); -}); + if (signal && signal.aborted) { + abort(); + return; + } -/** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example - * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ -var defaults = baseRest(function(args) { - args.push(undefined, assignInDefaults); - return apply(assignInWith, undefined, args); -}); + const abortAndFinalize = function abortAndFinalize() { + abort(); + finalize(); + }; -/** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ -function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); -} + // send request + const req = send(options); + let reqTimeout; -module.exports = defaults; + if (signal) { + signal.addEventListener('abort', abortAndFinalize); + } + function finalize() { + req.abort(); + if (signal) signal.removeEventListener('abort', abortAndFinalize); + clearTimeout(reqTimeout); + } -/***/ }), + if (request.timeout) { + req.once('socket', function (socket) { + reqTimeout = setTimeout(function () { + reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); + finalize(); + }, request.timeout); + }); + } -/***/ 89764: -/***/ ((module) => { + req.on('error', function (err) { + reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + if (response && response.body) { + destroyStream(response.body, err); + } -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE = 200; + finalize(); + }); -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED = '__lodash_hash_undefined__'; + fixResponseChunkedTransferBadEnding(req, function (err) { + if (signal && signal.aborted) { + return; + } -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; + if (response && response.body) { + destroyStream(response.body, err); + } + }); -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; + /* c8 ignore next 18 */ + if (parseInt(process.version.substring(1)) < 14) { + // Before Node.js 14, pipeline() does not fully support async iterators and does not always + // properly handle when the socket close/end events are out of order. + req.on('socket', function (s) { + s.addListener('close', function (hadError) { + // if a data listener is still present we didn't end cleanly + const hasDataListener = s.listenerCount('data') > 0; -/** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ -var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; + // if end happened before close but the socket didn't emit an error, do it now + if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + response.body.emit('error', err); + } + }); + }); + } -/** Used to detect host constructors (Safari). */ -var reIsHostCtor = /^\[object .+?Constructor\]$/; + req.on('response', function (res) { + clearTimeout(reqTimeout); -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + const headers = createHeadersLenient(res.headers); -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + // HTTP fetch step 5 + if (fetch.isRedirect(res.statusCode)) { + // HTTP fetch step 5.2 + const location = headers.get('Location'); -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); + // HTTP fetch step 5.3 + let locationURL = null; + try { + locationURL = location === null ? null : new URL$1(location, request.url).toString(); + } catch (err) { + // error here can only be invalid URL in Location: header + // do not throw when options.redirect == manual + // let the user extract the errorneous redirect URL + if (request.redirect !== 'manual') { + reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); + finalize(); + return; + } + } -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ -function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); -} + // HTTP fetch step 5.5 + switch (request.redirect) { + case 'error': + reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); + finalize(); + return; + case 'manual': + // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. + if (locationURL !== null) { + // handle corrupted header + try { + headers.set('Location', locationURL); + } catch (err) { + // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request + reject(err); + } + } + break; + case 'follow': + // HTTP-redirect fetch step 2 + if (locationURL === null) { + break; + } -/** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ -function arrayIncludes(array, value) { - var length = array ? array.length : 0; - return !!length && baseIndexOf(array, value, 0) > -1; -} + // HTTP-redirect fetch step 5 + if (request.counter >= request.follow) { + reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); + finalize(); + return; + } -/** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ -function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array ? array.length : 0; + // HTTP-redirect fetch step 6 (counter increment) + // Create a new Request object. + const requestOpts = { + headers: new Headers(request.headers), + follow: request.follow, + counter: request.counter + 1, + agent: request.agent, + compress: request.compress, + method: request.method, + body: request.body, + signal: request.signal, + timeout: request.timeout, + size: request.size + }; - while (++index < length) { - if (comparator(value, array[index])) { - return true; - } - } - return false; -} + if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { + for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { + requestOpts.headers.delete(name); + } + } -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array ? array.length : 0, - result = Array(length); + // HTTP-redirect fetch step 9 + if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { + reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); + finalize(); + return; + } - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} + // HTTP-redirect fetch step 11 + if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { + requestOpts.method = 'GET'; + requestOpts.body = undefined; + requestOpts.headers.delete('content-length'); + } -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ -function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; + // HTTP-redirect fetch step 15 + resolve(fetch(new Request(locationURL, requestOpts))); + finalize(); + return; + } + } - while (++index < length) { - array[offset + index] = values[index]; - } - return array; -} + // prepare response + res.once('end', function () { + if (signal) signal.removeEventListener('abort', abortAndFinalize); + }); + let body = res.pipe(new PassThrough$1()); -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); + const response_options = { + url: request.url, + status: res.statusCode, + statusText: res.statusMessage, + headers: headers, + size: request.size, + timeout: request.timeout, + counter: request.counter + }; - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; -} + // HTTP-network fetch step 12.1.1.3 + const codings = headers.get('Content-Encoding'); -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - if (value !== value) { - return baseFindIndex(array, baseIsNaN, fromIndex); - } - var index = fromIndex - 1, - length = array.length; + // HTTP-network fetch step 12.1.1.4: handle content codings - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; -} + // in following scenarios we ignore compression support + // 1. compression support is disabled + // 2. HEAD request + // 3. no Content-Encoding header + // 4. no content response (204) + // 5. content not modified response (304) + if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { + response = new Response(body, response_options); + resolve(response); + return; + } -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; + // For Node v6+ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + const zlibOptions = { + flush: zlib.Z_SYNC_FLUSH, + finishFlush: zlib.Z_SYNC_FLUSH + }; + + // for gzip + if (codings == 'gzip' || codings == 'x-gzip') { + body = body.pipe(zlib.createGunzip(zlibOptions)); + response = new Response(body, response_options); + resolve(response); + return; + } + + // for deflate + if (codings == 'deflate' || codings == 'x-deflate') { + // handle the infamous raw deflate response from old servers + // a hack for old IIS and Apache servers + const raw = res.pipe(new PassThrough$1()); + raw.once('data', function (chunk) { + // see http://stackoverflow.com/questions/37519828 + if ((chunk[0] & 0x0F) === 0x08) { + body = body.pipe(zlib.createInflate()); + } else { + body = body.pipe(zlib.createInflateRaw()); + } + response = new Response(body, response_options); + resolve(response); + }); + raw.on('end', function () { + // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. + if (!response) { + response = new Response(body, response_options); + resolve(response); + } + }); + return; + } + + // for br + if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { + body = body.pipe(zlib.createBrotliDecompress()); + response = new Response(body, response_options); + resolve(response); + return; + } + + // otherwise, use response as-is + response = new Response(body, response_options); + resolve(response); + }); + + writeToStream(req, request); + }); } +function fixResponseChunkedTransferBadEnding(request, errorCallback) { + let socket; -/** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ -function baseUnary(func) { - return function(value) { - return func(value); - }; + request.on('socket', function (s) { + socket = s; + }); + + request.on('response', function (response) { + const headers = response.headers; + + if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { + response.once('close', function (hadError) { + // tests for socket presence, as in some situations the + // the 'socket' event is not triggered for the request + // (happens in deno), avoids `TypeError` + // if a data listener is still present we didn't end cleanly + const hasDataListener = socket && socket.listenerCount('data') > 0; + + if (hasDataListener && !hadError) { + const err = new Error('Premature close'); + err.code = 'ERR_STREAM_PREMATURE_CLOSE'; + errorCallback(err); + } + }); + } + }); } -/** - * Checks if a cache value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function cacheHas(cache, key) { - return cache.has(key); +function destroyStream(stream, err) { + if (stream.destroy) { + stream.destroy(err); + } else { + // node < 8 + stream.emit('error', err); + stream.end(); + } } /** - * Gets the value at `key` of `object`. + * Redirect code matching * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. + * @param Number code Status code + * @return Boolean */ -function getValue(object, key) { - return object == null ? undefined : object[key]; -} +fetch.isRedirect = function (code) { + return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; +}; -/** - * Checks if `value` is a host object in IE < 9. +// expose Promise +fetch.Promise = global.Promise; + +module.exports = exports = fetch; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports["default"] = exports; +exports.Headers = Headers; +exports.Request = Request; +exports.Response = Response; +exports.FetchError = FetchError; +exports.AbortError = AbortError; + + +/***/ }), + +/***/ 55388: +/***/ ((module) => { + +/*! + * normalize-path * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + * Copyright (c) 2014-2018, Jon Schlinkert. + * Released under the MIT License. */ -function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} - } - return result; -} -/** Used for built-in method references. */ -var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; +module.exports = function(path, stripTrailing) { + if (typeof path !== 'string') { + throw new TypeError('expected path to be a string'); + } -/** Used to detect overreaching core-js shims. */ -var coreJsData = root['__core-js_shared__']; + if (path === '\\' || path === '/') return '/'; -/** Used to detect methods masquerading as native. */ -var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; -}()); + var len = path.length; + if (len <= 1) return path; -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; + // ensure that win32 namespaces has two leading slashes, so that the path is + // handled properly by the win32 version of path.parse() after being normalized + // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces + var prefix = ''; + if (len > 4 && path[3] === '\\') { + var ch = path[2]; + if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') { + path = path.slice(2); + prefix = '//'; + } + } -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + var segs = path.split(/[/\\]+/); + if (stripTrailing !== false && segs[segs.length - 1] === '') { + segs.pop(); + } + return prefix + segs.join('/'); +}; -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; -/** Used to detect if a method is native. */ -var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); +/***/ }), -/** Built-in value references. */ -var Symbol = root.Symbol, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; +/***/ 1223: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; +var wrappy = __nccwpck_require__(62940) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) -/* Built-in method references that are verified to be native. */ -var Map = getNative(root, 'Map'), - nativeCreate = getNative(Object, 'create'); +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) -/** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Hash(entries) { - var index = -1, - length = entries ? entries.length : 0; + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) } + f.called = false + return f } -/** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ -function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f } -/** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function hashDelete(key) { - return this.has(key) && delete this.__data__[key]; + +/***/ }), + +/***/ 47810: +/***/ ((module) => { + +"use strict"; + + +if (typeof process === 'undefined' || + !process.version || + process.version.indexOf('v0.') === 0 || + process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { + module.exports = { nextTick: nextTick }; +} else { + module.exports = process } -/** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; +function nextTick(fn, arg1, arg2, arg3) { + if (typeof fn !== 'function') { + throw new TypeError('"callback" argument must be a function'); + } + var len = arguments.length; + var args, i; + switch (len) { + case 0: + case 1: + return process.nextTick(fn); + case 2: + return process.nextTick(function afterTickOne() { + fn.call(null, arg1); + }); + case 3: + return process.nextTick(function afterTickTwo() { + fn.call(null, arg1, arg2); + }); + case 4: + return process.nextTick(function afterTickThree() { + fn.call(null, arg1, arg2, arg3); + }); + default: + args = new Array(len - 1); + i = 0; + while (i < args.length) { + args[i++] = arguments[i]; + } + return process.nextTick(function afterTick() { + fn.apply(null, args); + }); } - return hasOwnProperty.call(data, key) ? data[key] : undefined; } -/** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); -} -/** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ -function hashSet(key, value) { - var data = this.__data__; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; -} -// Add methods to `Hash`. -Hash.prototype.clear = hashClear; -Hash.prototype['delete'] = hashDelete; -Hash.prototype.get = hashGet; -Hash.prototype.has = hashHas; -Hash.prototype.set = hashSet; +/***/ }), -/** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function ListCache(entries) { - var index = -1, - length = entries ? entries.length : 0; +/***/ 45676: +/***/ ((module) => { - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} +// for now just expose the builtin process global from node.js +module.exports = global.process; -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ -function listCacheClear() { - this.__data__ = []; -} -/** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); +/***/ }), - if (index < 0) { - return false; +/***/ 5322: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = (typeof process !== 'undefined' && typeof process.nextTick === 'function') + ? process.nextTick.bind(process) + : __nccwpck_require__(71031) + + +/***/ }), + +/***/ 71031: +/***/ ((module) => { + +module.exports = typeof queueMicrotask === 'function' ? queueMicrotask : (fn) => Promise.resolve().then(fn) + + +/***/ }), + +/***/ 80289: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +const { SymbolDispose } = __nccwpck_require__(89629) +const { AbortError, codes } = __nccwpck_require__(80529) +const { isNodeStream, isWebStream, kControllerErrorFunction } = __nccwpck_require__(27981) +const eos = __nccwpck_require__(76080) +const { ERR_INVALID_ARG_TYPE } = codes +let addAbortListener + +// This method is inlined here for readable-stream +// It also does not allow for signal to not exist on the stream +// https://github.com/nodejs/node/pull/36061#discussion_r533718029 +const validateAbortSignal = (signal, name) => { + if (typeof signal !== 'object' || !('aborted' in signal)) { + throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); +} +module.exports.addAbortSignal = function addAbortSignal(signal, stream) { + validateAbortSignal(signal, 'signal') + if (!isNodeStream(stream) && !isWebStream(stream)) { + throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream) + } + return module.exports.addAbortSignalNoValidate(signal, stream) +} +module.exports.addAbortSignalNoValidate = function (signal, stream) { + if (typeof signal !== 'object' || !('aborted' in signal)) { + return stream + } + const onAbort = isNodeStream(stream) + ? () => { + stream.destroy( + new AbortError(undefined, { + cause: signal.reason + }) + ) + } + : () => { + stream[kControllerErrorFunction]( + new AbortError(undefined, { + cause: signal.reason + }) + ) + } + if (signal.aborted) { + onAbort() } else { - splice.call(data, index, 1); + addAbortListener = addAbortListener || (__nccwpck_require__(46959).addAbortListener) + const disposable = addAbortListener(signal, onAbort) + eos(stream, disposable[SymbolDispose]) } - return true; + return stream } -/** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - return index < 0 ? undefined : data[index][1]; -} +/***/ }), -/** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; -} +/***/ 52746: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ -function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); +"use strict"; - if (index < 0) { - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; -} -// Add methods to `ListCache`. -ListCache.prototype.clear = listCacheClear; -ListCache.prototype['delete'] = listCacheDelete; -ListCache.prototype.get = listCacheGet; -ListCache.prototype.has = listCacheHas; -ListCache.prototype.set = listCacheSet; +const { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array } = __nccwpck_require__(89629) +const { Buffer } = __nccwpck_require__(14300) +const { inspect } = __nccwpck_require__(46959) +module.exports = class BufferList { + constructor() { + this.head = null + this.tail = null + this.length = 0 + } + push(v) { + const entry = { + data: v, + next: null + } + if (this.length > 0) this.tail.next = entry + else this.head = entry + this.tail = entry + ++this.length + } + unshift(v) { + const entry = { + data: v, + next: this.head + } + if (this.length === 0) this.tail = entry + this.head = entry + ++this.length + } + shift() { + if (this.length === 0) return + const ret = this.head.data + if (this.length === 1) this.head = this.tail = null + else this.head = this.head.next + --this.length + return ret + } + clear() { + this.head = this.tail = null + this.length = 0 + } + join(s) { + if (this.length === 0) return '' + let p = this.head + let ret = '' + p.data + while ((p = p.next) !== null) ret += s + p.data + return ret + } + concat(n) { + if (this.length === 0) return Buffer.alloc(0) + const ret = Buffer.allocUnsafe(n >>> 0) + let p = this.head + let i = 0 + while (p) { + TypedArrayPrototypeSet(ret, p.data, i) + i += p.data.length + p = p.next + } + return ret + } -/** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function MapCache(entries) { - var index = -1, - length = entries ? entries.length : 0; + // Consumes a specified amount of bytes or characters from the buffered data. + consume(n, hasStrings) { + const data = this.head.data + if (n < data.length) { + // `slice` is the same for buffers and strings. + const slice = data.slice(0, n) + this.head.data = data.slice(n) + return slice + } + if (n === data.length) { + // First chunk is a perfect match. + return this.shift() + } + // Result spans more than one buffer. + return hasStrings ? this._getString(n) : this._getBuffer(n) + } + first() { + return this.head.data + } + *[SymbolIterator]() { + for (let p = this.head; p; p = p.next) { + yield p.data + } + } - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); + // Consumes a specified amount of characters from the buffered data. + _getString(n) { + let ret = '' + let p = this.head + let c = 0 + do { + const str = p.data + if (n > str.length) { + ret += str + n -= str.length + } else { + if (n === str.length) { + ret += str + ++c + if (p.next) this.head = p.next + else this.head = this.tail = null + } else { + ret += StringPrototypeSlice(str, 0, n) + this.head = p + p.data = StringPrototypeSlice(str, n) + } + break + } + ++c + } while ((p = p.next) !== null) + this.length -= c + return ret } -} -/** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ -function mapCacheClear() { - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; -} + // Consumes a specified amount of bytes from the buffered data. + _getBuffer(n) { + const ret = Buffer.allocUnsafe(n) + const retLen = n + let p = this.head + let c = 0 + do { + const buf = p.data + if (n > buf.length) { + TypedArrayPrototypeSet(ret, buf, retLen - n) + n -= buf.length + } else { + if (n === buf.length) { + TypedArrayPrototypeSet(ret, buf, retLen - n) + ++c + if (p.next) this.head = p.next + else this.head = this.tail = null + } else { + TypedArrayPrototypeSet(ret, new Uint8Array(buf.buffer, buf.byteOffset, n), retLen - n) + this.head = p + p.data = buf.slice(n) + } + break + } + ++c + } while ((p = p.next) !== null) + this.length -= c + return ret + } -/** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function mapCacheDelete(key) { - return getMapData(this, key)['delete'](key); + // Make sure the linked list only shows the minimal necessary information. + [Symbol.for('nodejs.util.inspect.custom')](_, options) { + return inspect(this, { + ...options, + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + }) + } } -/** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function mapCacheGet(key) { - return getMapData(this, key).get(key); -} -/** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function mapCacheHas(key) { - return getMapData(this, key).has(key); -} +/***/ }), -/** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ -function mapCacheSet(key, value) { - getMapData(this, key).set(key, value); - return this; -} +/***/ 63129: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Add methods to `MapCache`. -MapCache.prototype.clear = mapCacheClear; -MapCache.prototype['delete'] = mapCacheDelete; -MapCache.prototype.get = mapCacheGet; -MapCache.prototype.has = mapCacheHas; -MapCache.prototype.set = mapCacheSet; +"use strict"; -/** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ -function SetCache(values) { - var index = -1, - length = values ? values.length : 0; - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); +const { pipeline } = __nccwpck_require__(76989) +const Duplex = __nccwpck_require__(72613) +const { destroyer } = __nccwpck_require__(97049) +const { + isNodeStream, + isReadable, + isWritable, + isWebStream, + isTransformStream, + isWritableStream, + isReadableStream +} = __nccwpck_require__(27981) +const { + AbortError, + codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS } +} = __nccwpck_require__(80529) +const eos = __nccwpck_require__(76080) +module.exports = function compose(...streams) { + if (streams.length === 0) { + throw new ERR_MISSING_ARGS('streams') + } + if (streams.length === 1) { + return Duplex.from(streams[0]) + } + const orgStreams = [...streams] + if (typeof streams[0] === 'function') { + streams[0] = Duplex.from(streams[0]) + } + if (typeof streams[streams.length - 1] === 'function') { + const idx = streams.length - 1 + streams[idx] = Duplex.from(streams[idx]) + } + for (let n = 0; n < streams.length; ++n) { + if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) { + // TODO(ronag): Add checks for non streams. + continue + } + if ( + n < streams.length - 1 && + !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n])) + ) { + throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be readable') + } + if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) { + throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be writable') + } + } + let ondrain + let onfinish + let onreadable + let onclose + let d + function onfinished(err) { + const cb = onclose + onclose = null + if (cb) { + cb(err) + } else if (err) { + d.destroy(err) + } else if (!readable && !writable) { + d.destroy() + } + } + const head = streams[0] + const tail = pipeline(streams, onfinished) + const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head)) + const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail)) + + // TODO(ronag): Avoid double buffering. + // Implement Writable/Readable/Duplex traits. + // See, https://github.com/nodejs/node/pull/33515. + d = new Duplex({ + // TODO (ronag): highWaterMark? + writableObjectMode: !!(head !== null && head !== undefined && head.writableObjectMode), + readableObjectMode: !!(tail !== null && tail !== undefined && tail.readableObjectMode), + writable, + readable + }) + if (writable) { + if (isNodeStream(head)) { + d._write = function (chunk, encoding, callback) { + if (head.write(chunk, encoding)) { + callback() + } else { + ondrain = callback + } + } + d._final = function (callback) { + head.end() + onfinish = callback + } + head.on('drain', function () { + if (ondrain) { + const cb = ondrain + ondrain = null + cb() + } + }) + } else if (isWebStream(head)) { + const writable = isTransformStream(head) ? head.writable : head + const writer = writable.getWriter() + d._write = async function (chunk, encoding, callback) { + try { + await writer.ready + writer.write(chunk).catch(() => {}) + callback() + } catch (err) { + callback(err) + } + } + d._final = async function (callback) { + try { + await writer.ready + writer.close().catch(() => {}) + onfinish = callback + } catch (err) { + callback(err) + } + } + } + const toRead = isTransformStream(tail) ? tail.readable : tail + eos(toRead, () => { + if (onfinish) { + const cb = onfinish + onfinish = null + cb() + } + }) + } + if (readable) { + if (isNodeStream(tail)) { + tail.on('readable', function () { + if (onreadable) { + const cb = onreadable + onreadable = null + cb() + } + }) + tail.on('end', function () { + d.push(null) + }) + d._read = function () { + while (true) { + const buf = tail.read() + if (buf === null) { + onreadable = d._read + return + } + if (!d.push(buf)) { + return + } + } + } + } else if (isWebStream(tail)) { + const readable = isTransformStream(tail) ? tail.readable : tail + const reader = readable.getReader() + d._read = async function () { + while (true) { + try { + const { value, done } = await reader.read() + if (!d.push(value)) { + return + } + if (done) { + d.push(null) + return + } + } catch { + return + } + } + } + } } + d._destroy = function (err, callback) { + if (!err && onclose !== null) { + err = new AbortError() + } + onreadable = null + ondrain = null + onfinish = null + if (onclose === null) { + callback(err) + } else { + onclose = callback + if (isNodeStream(tail)) { + destroyer(tail, err) + } + } + } + return d } -/** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ -function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; -} -/** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ -function setCacheHas(value) { - return this.__data__.has(value); -} +/***/ }), -// Add methods to `SetCache`. -SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; -SetCache.prototype.has = setCacheHas; +/***/ 97049: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; +"use strict"; + + +/* replacement start */ + +const process = __nccwpck_require__(45676) + +/* replacement end */ + +const { + aggregateTwoErrors, + codes: { ERR_MULTIPLE_CALLBACK }, + AbortError +} = __nccwpck_require__(80529) +const { Symbol } = __nccwpck_require__(89629) +const { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = __nccwpck_require__(27981) +const kDestroy = Symbol('kDestroy') +const kConstruct = Symbol('kConstruct') +function checkError(err, w, r) { + if (err) { + // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 + err.stack // eslint-disable-line no-unused-expressions + + if (w && !w.errored) { + w.errored = err + } + if (r && !r.errored) { + r.errored = err } } - return -1; } -/** - * The base implementation of methods like `_.difference` without support - * for excluding multiple arrays or iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - */ -function baseDifference(array, values, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - isCommon = true, - length = array.length, - result = [], - valuesLength = values.length; - - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap(values, baseUnary(iteratee)); +// Backwards compat. cb() is undocumented and unused in core but +// unfortunately might be used by modules. +function destroy(err, cb) { + const r = this._readableState + const w = this._writableState + // With duplex streams we use the writable side for state. + const s = w || r + if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) { + if (typeof cb === 'function') { + cb() + } + return this } - if (comparator) { - includes = arrayIncludesWith; - isCommon = false; + + // We set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + checkError(err, w, r) + if (w) { + w.destroyed = true } - else if (values.length >= LARGE_ARRAY_SIZE) { - includes = cacheHas; - isCommon = false; - values = new SetCache(values); + if (r) { + r.destroyed = true } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; - } - } - result.push(value); + // If still constructing then defer calling _destroy. + if (!s.constructed) { + this.once(kDestroy, function (er) { + _destroy(this, aggregateTwoErrors(er, err), cb) + }) + } else { + _destroy(this, err, cb) + } + return this +} +function _destroy(self, err, cb) { + let called = false + function onDestroy(err) { + if (called) { + return } - else if (!includes(values, computed, comparator)) { - result.push(value); + called = true + const r = self._readableState + const w = self._writableState + checkError(err, w, r) + if (w) { + w.closed = true + } + if (r) { + r.closed = true + } + if (typeof cb === 'function') { + cb(err) + } + if (err) { + process.nextTick(emitErrorCloseNT, self, err) + } else { + process.nextTick(emitCloseNT, self) } } - return result; + try { + self._destroy(err || null, onDestroy) + } catch (err) { + onDestroy(err) + } } +function emitErrorCloseNT(self, err) { + emitErrorNT(self, err) + emitCloseNT(self) +} +function emitCloseNT(self) { + const r = self._readableState + const w = self._writableState + if (w) { + w.closeEmitted = true + } + if (r) { + r.closeEmitted = true + } + if ((w !== null && w !== undefined && w.emitClose) || (r !== null && r !== undefined && r.emitClose)) { + self.emit('close') + } +} +function emitErrorNT(self, err) { + const r = self._readableState + const w = self._writableState + if ((w !== null && w !== undefined && w.errorEmitted) || (r !== null && r !== undefined && r.errorEmitted)) { + return + } + if (w) { + w.errorEmitted = true + } + if (r) { + r.errorEmitted = true + } + self.emit('error', err) +} +function undestroy() { + const r = this._readableState + const w = this._writableState + if (r) { + r.constructed = true + r.closed = false + r.closeEmitted = false + r.destroyed = false + r.errored = null + r.errorEmitted = false + r.reading = false + r.ended = r.readable === false + r.endEmitted = r.readable === false + } + if (w) { + w.constructed = true + w.destroyed = false + w.closed = false + w.closeEmitted = false + w.errored = null + w.errorEmitted = false + w.finalCalled = false + w.prefinished = false + w.ended = w.writable === false + w.ending = w.writable === false + w.finished = w.writable === false + } +} +function errorOrDestroy(stream, err, sync) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. -/** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ -function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; - - predicate || (predicate = isFlattenable); - result || (result = []); + const r = stream._readableState + const w = stream._writableState + if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) { + return this + } + if ((r !== null && r !== undefined && r.autoDestroy) || (w !== null && w !== undefined && w.autoDestroy)) + stream.destroy(err) + else if (err) { + // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 + err.stack // eslint-disable-line no-unused-expressions - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; + if (w && !w.errored) { + w.errored = err + } + if (r && !r.errored) { + r.errored = err + } + if (sync) { + process.nextTick(emitErrorNT, stream, err) + } else { + emitErrorNT(stream, err) } } - return result; } - -/** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ -function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; +function construct(stream, cb) { + if (typeof stream._construct !== 'function') { + return } - var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); + const r = stream._readableState + const w = stream._writableState + if (r) { + r.constructed = false + } + if (w) { + w.constructed = false + } + stream.once(kConstruct, cb) + if (stream.listenerCount(kConstruct) > 1) { + // Duplex + return + } + process.nextTick(constructNT, stream) } - -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; +function constructNT(stream) { + let called = false + function onConstruct(err) { + if (called) { + errorOrDestroy(stream, err !== null && err !== undefined ? err : new ERR_MULTIPLE_CALLBACK()) + return } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; + called = true + const r = stream._readableState + const w = stream._writableState + const s = w || r + if (r) { + r.constructed = true } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; + if (w) { + w.constructed = true + } + if (s.destroyed) { + stream.emit(kDestroy, err) + } else if (err) { + errorOrDestroy(stream, err, true) + } else { + process.nextTick(emitConstructNT, stream) + } + } + try { + stream._construct((err) => { + process.nextTick(onConstruct, err) + }) + } catch (err) { + process.nextTick(onConstruct, err) + } } - -/** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ -function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; +function emitConstructNT(stream) { + stream.emit(kConstruct) } - -/** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ -function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; +function isRequest(stream) { + return (stream === null || stream === undefined ? undefined : stream.setHeader) && typeof stream.abort === 'function' } - -/** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ -function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); +function emitCloseLegacy(stream) { + stream.emit('close') +} +function emitErrorCloseLegacy(stream, err) { + stream.emit('error', err) + process.nextTick(emitCloseLegacy, stream) } -/** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ -function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); -} - -/** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ -function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); -} +// Normalize destroy for legacy. +function destroyer(stream, err) { + if (!stream || isDestroyed(stream)) { + return + } + if (!err && !isFinished(stream)) { + err = new AbortError() + } -/** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to process. - * @returns {string} Returns the source code. - */ -function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} + // TODO: Remove isRequest branches. + if (isServerRequest(stream)) { + stream.socket = null + stream.destroy(err) + } else if (isRequest(stream)) { + stream.abort() + } else if (isRequest(stream.req)) { + stream.req.abort() + } else if (typeof stream.destroy === 'function') { + stream.destroy(err) + } else if (typeof stream.close === 'function') { + // TODO: Don't lose err? + stream.close() + } else if (err) { + process.nextTick(emitErrorCloseLegacy, stream, err) + } else { + process.nextTick(emitCloseLegacy, stream) + } + if (!stream.destroyed) { + stream[kIsDestroyed] = true } - return ''; +} +module.exports = { + construct, + destroyer, + destroy, + undestroy, + errorOrDestroy } -/** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order of result values is determined by the - * order they occur in the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example - * - * _.difference([2, 1], [2, 3]); - * // => [1] - */ -var difference = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) - : []; -}); -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); -} +/***/ }), -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} +/***/ 72613: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} +// a duplex stream is just a stream that is both readable and writable. +// Since JS doesn't have multiple prototype inheritance, this class +// prototypically inherits from Readable, and then parasitically from +// Writable. -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +const { + ObjectDefineProperties, + ObjectGetOwnPropertyDescriptor, + ObjectKeys, + ObjectSetPrototypeOf +} = __nccwpck_require__(89629) +module.exports = Duplex +const Readable = __nccwpck_require__(57920) +const Writable = __nccwpck_require__(48488) +ObjectSetPrototypeOf(Duplex.prototype, Readable.prototype) +ObjectSetPrototypeOf(Duplex, Readable) +{ + const keys = ObjectKeys(Writable.prototype) + // Allow the keys array to be GC'ed. + for (let i = 0; i < keys.length; i++) { + const method = keys[i] + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method] + } } - -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); +function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options) + Readable.call(this, options) + Writable.call(this, options) + if (options) { + this.allowHalfOpen = options.allowHalfOpen !== false + if (options.readable === false) { + this._readableState.readable = false + this._readableState.ended = true + this._readableState.endEmitted = true + } + if (options.writable === false) { + this._writableState.writable = false + this._writableState.ending = true + this._writableState.ended = true + this._writableState.finished = true + } + } else { + this.allowHalfOpen = true + } } +ObjectDefineProperties(Duplex.prototype, { + writable: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writable') + }, + writableHighWaterMark: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableHighWaterMark') + }, + writableObjectMode: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableObjectMode') + }, + writableBuffer: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableBuffer') + }, + writableLength: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableLength') + }, + writableFinished: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableFinished') + }, + writableCorked: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableCorked') + }, + writableEnded: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableEnded') + }, + writableNeedDrain: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableNeedDrain') + }, + destroyed: { + __proto__: null, + get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false + } + return this._readableState.destroyed && this._writableState.destroyed + }, + set(value) { + // Backward compatibility, the user is explicitly + // managing destroyed. + if (this._readableState && this._writableState) { + this._readableState.destroyed = value + this._writableState.destroyed = value + } + } + } +}) +let webStreamsAdapters -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +// Lazy to avoid circular references +function lazyWebStreams() { + if (webStreamsAdapters === undefined) webStreamsAdapters = {} + return webStreamsAdapters +} +Duplex.fromWeb = function (pair, options) { + return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options) +} +Duplex.toWeb = function (duplex) { + return lazyWebStreams().newReadableWritablePairFromDuplex(duplex) +} +let duplexify +Duplex.from = function (body) { + if (!duplexify) { + duplexify = __nccwpck_require__(86350) + } + return duplexify(body, 'body') } - -module.exports = difference; /***/ }), -/***/ 48919: -/***/ ((module) => { - -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ +/***/ 86350: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; +/* replacement start */ -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; +const process = __nccwpck_require__(45676) -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; +/* replacement end */ -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; +;('use strict') +const bufferModule = __nccwpck_require__(14300) +const { + isReadable, + isWritable, + isIterable, + isNodeStream, + isReadableNodeStream, + isWritableNodeStream, + isDuplexNodeStream, + isReadableStream, + isWritableStream +} = __nccwpck_require__(27981) +const eos = __nccwpck_require__(76080) +const { + AbortError, + codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE } +} = __nccwpck_require__(80529) +const { destroyer } = __nccwpck_require__(97049) +const Duplex = __nccwpck_require__(72613) +const Readable = __nccwpck_require__(57920) +const Writable = __nccwpck_require__(48488) +const { createDeferredPromise } = __nccwpck_require__(46959) +const from = __nccwpck_require__(39082) +const Blob = globalThis.Blob || bufferModule.Blob +const isBlob = + typeof Blob !== 'undefined' + ? function isBlob(b) { + return b instanceof Blob + } + : function isBlob(b) { + return false + } +const AbortController = globalThis.AbortController || (__nccwpck_require__(61659).AbortController) +const { FunctionPrototypeCall } = __nccwpck_require__(89629) -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); +// This is needed for pre node 17. +class Duplexify extends Duplex { + constructor(options) { + super(options) -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ -function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; + // https://github.com/nodejs/node/pull/34385 - while (++index < length) { - array[offset + index] = values[index]; + if ((options === null || options === undefined ? undefined : options.readable) === false) { + this._readableState.readable = false + this._readableState.ended = true + this._readableState.endEmitted = true + } + if ((options === null || options === undefined ? undefined : options.writable) === false) { + this._writableState.writable = false + this._writableState.ending = true + this._writableState.ended = true + this._writableState.finished = true + } } - return array; } - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; - -/** Built-in value references. */ -var Symbol = root.Symbol, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; - -/** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ -function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; - - predicate || (predicate = isFlattenable); - result || (result = []); - - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; +module.exports = function duplexify(body, name) { + if (isDuplexNodeStream(body)) { + return body + } + if (isReadableNodeStream(body)) { + return _duplexify({ + readable: body + }) + } + if (isWritableNodeStream(body)) { + return _duplexify({ + writable: body + }) + } + if (isNodeStream(body)) { + return _duplexify({ + writable: false, + readable: false + }) + } + if (isReadableStream(body)) { + return _duplexify({ + readable: Readable.fromWeb(body) + }) + } + if (isWritableStream(body)) { + return _duplexify({ + writable: Writable.fromWeb(body) + }) + } + if (typeof body === 'function') { + const { value, write, final, destroy } = fromAsyncGen(body) + if (isIterable(value)) { + return from(Duplexify, value, { + // TODO (ronag): highWaterMark? + objectMode: true, + write, + final, + destroy + }) + } + const then = value === null || value === undefined ? undefined : value.then + if (typeof then === 'function') { + let d + const promise = FunctionPrototypeCall( + then, + value, + (val) => { + if (val != null) { + throw new ERR_INVALID_RETURN_VALUE('nully', 'body', val) + } + }, + (err) => { + destroyer(d, err) + } + ) + return (d = new Duplexify({ + // TODO (ronag): highWaterMark? + objectMode: true, + readable: false, + write, + final(cb) { + final(async () => { + try { + await promise + process.nextTick(cb, null) + } catch (err) { + process.nextTick(cb, err) + } + }) + }, + destroy + })) } + throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or AsyncFunction', name, value) } - return result; + if (isBlob(body)) { + return duplexify(body.arrayBuffer()) + } + if (isIterable(body)) { + return from(Duplexify, body, { + // TODO (ronag): highWaterMark? + objectMode: true, + writable: false + }) + } + if ( + isReadableStream(body === null || body === undefined ? undefined : body.readable) && + isWritableStream(body === null || body === undefined ? undefined : body.writable) + ) { + return Duplexify.fromWeb(body) + } + if ( + typeof (body === null || body === undefined ? undefined : body.writable) === 'object' || + typeof (body === null || body === undefined ? undefined : body.readable) === 'object' + ) { + const readable = + body !== null && body !== undefined && body.readable + ? isReadableNodeStream(body === null || body === undefined ? undefined : body.readable) + ? body === null || body === undefined + ? undefined + : body.readable + : duplexify(body.readable) + : undefined + const writable = + body !== null && body !== undefined && body.writable + ? isWritableNodeStream(body === null || body === undefined ? undefined : body.writable) + ? body === null || body === undefined + ? undefined + : body.writable + : duplexify(body.writable) + : undefined + return _duplexify({ + readable, + writable + }) + } + const then = body === null || body === undefined ? undefined : body.then + if (typeof then === 'function') { + let d + FunctionPrototypeCall( + then, + body, + (val) => { + if (val != null) { + d.push(val) + } + d.push(null) + }, + (err) => { + destroyer(d, err) + } + ) + return (d = new Duplexify({ + objectMode: true, + writable: false, + read() {} + })) + } + throw new ERR_INVALID_ARG_TYPE( + name, + [ + 'Blob', + 'ReadableStream', + 'WritableStream', + 'Stream', + 'Iterable', + 'AsyncIterable', + 'Function', + '{ readable, writable } pair', + 'Promise' + ], + body + ) } - -/** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ -function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); +function fromAsyncGen(fn) { + let { promise, resolve } = createDeferredPromise() + const ac = new AbortController() + const signal = ac.signal + const value = fn( + (async function* () { + while (true) { + const _promise = promise + promise = null + const { chunk, done, cb } = await _promise + process.nextTick(cb) + if (done) return + if (signal.aborted) + throw new AbortError(undefined, { + cause: signal.reason + }) + ;({ promise, resolve } = createDeferredPromise()) + yield chunk + } + })(), + { + signal + } + ) + return { + value, + write(chunk, encoding, cb) { + const _resolve = resolve + resolve = null + _resolve({ + chunk, + done: false, + cb + }) + }, + final(cb) { + const _resolve = resolve + resolve = null + _resolve({ + done: true, + cb + }) + }, + destroy(err, cb) { + ac.abort() + cb(err) + } + } } +function _duplexify(pair) { + const r = pair.readable && typeof pair.readable.read !== 'function' ? Readable.wrap(pair.readable) : pair.readable + const w = pair.writable + let readable = !!isReadable(r) + let writable = !!isWritable(w) + let ondrain + let onfinish + let onreadable + let onclose + let d + function onfinished(err) { + const cb = onclose + onclose = null + if (cb) { + cb(err) + } else if (err) { + d.destroy(err) + } + } -/** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ -function flatten(array) { - var length = array ? array.length : 0; - return length ? baseFlatten(array, 1) : []; + // TODO(ronag): Avoid double buffering. + // Implement Writable/Readable/Duplex traits. + // See, https://github.com/nodejs/node/pull/33515. + d = new Duplexify({ + // TODO (ronag): highWaterMark? + readableObjectMode: !!(r !== null && r !== undefined && r.readableObjectMode), + writableObjectMode: !!(w !== null && w !== undefined && w.writableObjectMode), + readable, + writable + }) + if (writable) { + eos(w, (err) => { + writable = false + if (err) { + destroyer(r, err) + } + onfinished(err) + }) + d._write = function (chunk, encoding, callback) { + if (w.write(chunk, encoding)) { + callback() + } else { + ondrain = callback + } + } + d._final = function (callback) { + w.end() + onfinish = callback + } + w.on('drain', function () { + if (ondrain) { + const cb = ondrain + ondrain = null + cb() + } + }) + w.on('finish', function () { + if (onfinish) { + const cb = onfinish + onfinish = null + cb() + } + }) + } + if (readable) { + eos(r, (err) => { + readable = false + if (err) { + destroyer(r, err) + } + onfinished(err) + }) + r.on('readable', function () { + if (onreadable) { + const cb = onreadable + onreadable = null + cb() + } + }) + r.on('end', function () { + d.push(null) + }) + d._read = function () { + while (true) { + const buf = r.read() + if (buf === null) { + onreadable = d._read + return + } + if (!d.push(buf)) { + return + } + } + } + } + d._destroy = function (err, callback) { + if (!err && onclose !== null) { + err = new AbortError() + } + onreadable = null + ondrain = null + onfinish = null + if (onclose === null) { + callback(err) + } else { + onclose = callback + destroyer(w, err) + destroyer(r, err) + } + } + return d } -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; +/***/ }), -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} +/***/ 76080: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} +/* replacement start */ -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} +const process = __nccwpck_require__(45676) -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} +/* replacement end */ +// Ported from https://github.com/mafintosh/end-of-stream with +// permission from the author, Mathias Buus (@mafintosh). -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} +;('use strict') +const { AbortError, codes } = __nccwpck_require__(80529) +const { ERR_INVALID_ARG_TYPE, ERR_STREAM_PREMATURE_CLOSE } = codes +const { kEmptyObject, once } = __nccwpck_require__(46959) +const { validateAbortSignal, validateFunction, validateObject, validateBoolean } = __nccwpck_require__(669) +const { Promise, PromisePrototypeThen, SymbolDispose } = __nccwpck_require__(89629) +const { + isClosed, + isReadable, + isReadableNodeStream, + isReadableStream, + isReadableFinished, + isReadableErrored, + isWritable, + isWritableNodeStream, + isWritableStream, + isWritableFinished, + isWritableErrored, + isNodeStream, + willEmitClose: _willEmitClose, + kIsClosedPromise +} = __nccwpck_require__(27981) +let addAbortListener +function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function' +} +const nop = () => {} +function eos(stream, options, callback) { + var _options$readable, _options$writable + if (arguments.length === 2) { + callback = options + options = kEmptyObject + } else if (options == null) { + options = kEmptyObject + } else { + validateObject(options, 'options') + } + validateFunction(callback, 'callback') + validateAbortSignal(options.signal, 'options.signal') + callback = once(callback) + if (isReadableStream(stream) || isWritableStream(stream)) { + return eosWeb(stream, options, callback) + } + if (!isNodeStream(stream)) { + throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream) + } + const readable = + (_options$readable = options.readable) !== null && _options$readable !== undefined + ? _options$readable + : isReadableNodeStream(stream) + const writable = + (_options$writable = options.writable) !== null && _options$writable !== undefined + ? _options$writable + : isWritableNodeStream(stream) + const wState = stream._writableState + const rState = stream._readableState + const onlegacyfinish = () => { + if (!stream.writable) { + onfinish() + } + } + + // TODO (ronag): Improve soft detection to include core modules and + // common ecosystem modules that do properly emit 'close' but fail + // this generic check. + let willEmitClose = + _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable + let writableFinished = isWritableFinished(stream, false) + const onfinish = () => { + writableFinished = true + // Stream should not be destroyed here. If it is that + // means that user space is doing something differently and + // we cannot trust willEmitClose. + if (stream.destroyed) { + willEmitClose = false + } + if (willEmitClose && (!stream.readable || readable)) { + return + } + if (!readable || readableFinished) { + callback.call(stream) + } + } + let readableFinished = isReadableFinished(stream, false) + const onend = () => { + readableFinished = true + // Stream should not be destroyed here. If it is that + // means that user space is doing something differently and + // we cannot trust willEmitClose. + if (stream.destroyed) { + willEmitClose = false + } + if (willEmitClose && (!stream.writable || writable)) { + return + } + if (!writable || writableFinished) { + callback.call(stream) + } + } + const onerror = (err) => { + callback.call(stream, err) + } + let closed = isClosed(stream) + const onclose = () => { + closed = true + const errored = isWritableErrored(stream) || isReadableErrored(stream) + if (errored && typeof errored !== 'boolean') { + return callback.call(stream, errored) + } + if (readable && !readableFinished && isReadableNodeStream(stream, true)) { + if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()) + } + if (writable && !writableFinished) { + if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()) + } + callback.call(stream) + } + const onclosed = () => { + closed = true + const errored = isWritableErrored(stream) || isReadableErrored(stream) + if (errored && typeof errored !== 'boolean') { + return callback.call(stream, errored) + } + callback.call(stream) + } + const onrequest = () => { + stream.req.on('finish', onfinish) + } + if (isRequest(stream)) { + stream.on('complete', onfinish) + if (!willEmitClose) { + stream.on('abort', onclose) + } + if (stream.req) { + onrequest() + } else { + stream.on('request', onrequest) + } + } else if (writable && !wState) { + // legacy streams + stream.on('end', onlegacyfinish) + stream.on('close', onlegacyfinish) + } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; + // Not all streams will emit 'close' after 'aborted'. + if (!willEmitClose && typeof stream.aborted === 'boolean') { + stream.on('aborted', onclose) + } + stream.on('end', onend) + stream.on('finish', onfinish) + if (options.error !== false) { + stream.on('error', onerror) + } + stream.on('close', onclose) + if (closed) { + process.nextTick(onclose) + } else if ( + (wState !== null && wState !== undefined && wState.errorEmitted) || + (rState !== null && rState !== undefined && rState.errorEmitted) + ) { + if (!willEmitClose) { + process.nextTick(onclosed) + } + } else if ( + !readable && + (!willEmitClose || isReadable(stream)) && + (writableFinished || isWritable(stream) === false) + ) { + process.nextTick(onclosed) + } else if ( + !writable && + (!willEmitClose || isWritable(stream)) && + (readableFinished || isReadable(stream) === false) + ) { + process.nextTick(onclosed) + } else if (rState && stream.req && stream.aborted) { + process.nextTick(onclosed) + } + const cleanup = () => { + callback = nop + stream.removeListener('aborted', onclose) + stream.removeListener('complete', onfinish) + stream.removeListener('abort', onclose) + stream.removeListener('request', onrequest) + if (stream.req) stream.req.removeListener('finish', onfinish) + stream.removeListener('end', onlegacyfinish) + stream.removeListener('close', onlegacyfinish) + stream.removeListener('finish', onfinish) + stream.removeListener('end', onend) + stream.removeListener('error', onerror) + stream.removeListener('close', onclose) + } + if (options.signal && !closed) { + const abort = () => { + // Keep it because cleanup removes it. + const endCallback = callback + cleanup() + endCallback.call( + stream, + new AbortError(undefined, { + cause: options.signal.reason + }) + ) + } + if (options.signal.aborted) { + process.nextTick(abort) + } else { + addAbortListener = addAbortListener || (__nccwpck_require__(46959).addAbortListener) + const disposable = addAbortListener(options.signal, abort) + const originalCallback = callback + callback = once((...args) => { + disposable[SymbolDispose]() + originalCallback.apply(stream, args) + }) + } + } + return cleanup } - -module.exports = flatten; +function eosWeb(stream, options, callback) { + let isAborted = false + let abort = nop + if (options.signal) { + abort = () => { + isAborted = true + callback.call( + stream, + new AbortError(undefined, { + cause: options.signal.reason + }) + ) + } + if (options.signal.aborted) { + process.nextTick(abort) + } else { + addAbortListener = addAbortListener || (__nccwpck_require__(46959).addAbortListener) + const disposable = addAbortListener(options.signal, abort) + const originalCallback = callback + callback = once((...args) => { + disposable[SymbolDispose]() + originalCallback.apply(stream, args) + }) + } + } + const resolverFn = (...args) => { + if (!isAborted) { + process.nextTick(() => callback.apply(stream, args)) + } + } + PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn) + return nop +} +function finished(stream, opts) { + var _opts + let autoCleanup = false + if (opts === null) { + opts = kEmptyObject + } + if ((_opts = opts) !== null && _opts !== undefined && _opts.cleanup) { + validateBoolean(opts.cleanup, 'cleanup') + autoCleanup = opts.cleanup + } + return new Promise((resolve, reject) => { + const cleanup = eos(stream, opts, (err) => { + if (autoCleanup) { + cleanup() + } + if (err) { + reject(err) + } else { + resolve() + } + }) + }) +} +module.exports = eos +module.exports.finished = finished /***/ }), -/***/ 25723: -/***/ ((module) => { +/***/ 39082: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ +"use strict"; -/** `Object#toString` result references. */ -var objectTag = '[object Object]'; -/** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ -function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} +/* replacement start */ + +const process = __nccwpck_require__(45676) + +/* replacement end */ + +const { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = __nccwpck_require__(89629) +const { Buffer } = __nccwpck_require__(14300) +const { ERR_INVALID_ARG_TYPE, ERR_STREAM_NULL_VALUES } = (__nccwpck_require__(80529).codes) +function from(Readable, iterable, opts) { + let iterator + if (typeof iterable === 'string' || iterable instanceof Buffer) { + return new Readable({ + objectMode: true, + ...opts, + read() { + this.push(iterable) + this.push(null) + } + }) } - return result; -} + let isAsync + if (iterable && iterable[SymbolAsyncIterator]) { + isAsync = true + iterator = iterable[SymbolAsyncIterator]() + } else if (iterable && iterable[SymbolIterator]) { + isAsync = false + iterator = iterable[SymbolIterator]() + } else { + throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable) + } + const readable = new Readable({ + objectMode: true, + highWaterMark: 1, + // TODO(ronag): What options should be allowed? + ...opts + }) -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; + // Flag to protect against _read + // being called before last iteration completion. + let reading = false + readable._read = function () { + if (!reading) { + reading = true + next() + } + } + readable._destroy = function (error, cb) { + PromisePrototypeThen( + close(error), + () => process.nextTick(cb, error), + // nextTick is here in case cb throws + (e) => process.nextTick(cb, e || error) + ) + } + async function close(error) { + const hadError = error !== undefined && error !== null + const hasThrow = typeof iterator.throw === 'function' + if (hadError && hasThrow) { + const { value, done } = await iterator.throw(error) + await value + if (done) { + return + } + } + if (typeof iterator.return === 'function') { + const { value } = await iterator.return() + await value + } + } + async function next() { + for (;;) { + try { + const { value, done } = isAsync ? await iterator.next() : iterator.next() + if (done) { + readable.push(null) + } else { + const res = value && typeof value.then === 'function' ? await value : value + if (res === null) { + reading = false + throw new ERR_STREAM_NULL_VALUES() + } else if (readable.push(res)) { + continue + } else { + reading = false + } + } + } catch (err) { + readable.destroy(err) + } + break + } + } + return readable } +module.exports = from -/** Used for built-in method references. */ -var funcProto = Function.prototype, - objectProto = Object.prototype; - -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; +/***/ }), -/** Used to infer the `Object` constructor. */ -var objectCtorString = funcToString.call(Object); +/***/ 49792: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +"use strict"; -/** Built-in value references. */ -var getPrototype = overArg(Object.getPrototypeOf, Object); -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +const { ArrayIsArray, ObjectSetPrototypeOf } = __nccwpck_require__(89629) +const { EventEmitter: EE } = __nccwpck_require__(82361) +function Stream(opts) { + EE.call(this, opts) } - -/** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ -function isPlainObject(value) { - if (!isObjectLike(value) || - objectToString.call(value) != objectTag || isHostObject(value)) { - return false; +ObjectSetPrototypeOf(Stream.prototype, EE.prototype) +ObjectSetPrototypeOf(Stream, EE) +Stream.prototype.pipe = function (dest, options) { + const source = this + function ondata(chunk) { + if (dest.writable && dest.write(chunk) === false && source.pause) { + source.pause() + } } - var proto = getPrototype(value); - if (proto === null) { - return true; + source.on('data', ondata) + function ondrain() { + if (source.readable && source.resume) { + source.resume() + } } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return (typeof Ctor == 'function' && - Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); -} + dest.on('drain', ondrain) -module.exports = isPlainObject; + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend) + source.on('close', onclose) + } + let didOnEnd = false + function onend() { + if (didOnEnd) return + didOnEnd = true + dest.end() + } + function onclose() { + if (didOnEnd) return + didOnEnd = true + if (typeof dest.destroy === 'function') dest.destroy() + } + // Don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup() + if (EE.listenerCount(this, 'error') === 0) { + this.emit('error', er) + } + } + prependListener(source, 'error', onerror) + prependListener(dest, 'error', onerror) -/***/ }), + // Remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata) + dest.removeListener('drain', ondrain) + source.removeListener('end', onend) + source.removeListener('close', onclose) + source.removeListener('error', onerror) + dest.removeListener('error', onerror) + source.removeListener('end', cleanup) + source.removeListener('close', cleanup) + dest.removeListener('close', cleanup) + } + source.on('end', cleanup) + source.on('close', cleanup) + dest.on('close', cleanup) + dest.emit('pipe', source) + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest +} +function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn) -/***/ 28651: -/***/ ((module) => { - -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ - -/** Used as the size to enable large array optimizations. */ -var LARGE_ARRAY_SIZE = 200; - -/** Used to stand-in for `undefined` hash values. */ -var HASH_UNDEFINED = '__lodash_hash_undefined__'; - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991; - -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn) + else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn) + else emitter._events[event] = [fn, emitter._events[event]] +} +module.exports = { + Stream, + prependListener +} -/** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ -var reRegExpChar = /[\\^$.*+?()[\]{}|]/g; -/** Used to detect host constructors (Safari). */ -var reIsHostCtor = /^\[object .+?Constructor\]$/; +/***/ }), -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; +/***/ 63193: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; +"use strict"; -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ -function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); +const AbortController = globalThis.AbortController || (__nccwpck_require__(61659).AbortController) +const { + codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE }, + AbortError +} = __nccwpck_require__(80529) +const { validateAbortSignal, validateInteger, validateObject } = __nccwpck_require__(669) +const kWeakHandler = (__nccwpck_require__(89629).Symbol)('kWeak') +const kResistStopPropagation = (__nccwpck_require__(89629).Symbol)('kResistStopPropagation') +const { finished } = __nccwpck_require__(76080) +const staticCompose = __nccwpck_require__(63129) +const { addAbortSignalNoValidate } = __nccwpck_require__(80289) +const { isWritable, isNodeStream } = __nccwpck_require__(27981) +const { deprecate } = __nccwpck_require__(46959) +const { + ArrayPrototypePush, + Boolean, + MathFloor, + Number, + NumberIsNaN, + Promise, + PromiseReject, + PromiseResolve, + PromisePrototypeThen, + Symbol +} = __nccwpck_require__(89629) +const kEmpty = Symbol('kEmpty') +const kEof = Symbol('kEof') +function compose(stream, options) { + if (options != null) { + validateObject(options, 'options') + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal') + } + if (isNodeStream(stream) && !isWritable(stream)) { + throw new ERR_INVALID_ARG_VALUE('stream', stream, 'must be writable') + } + const composedStream = staticCompose(this, stream) + if (options !== null && options !== undefined && options.signal) { + // Not validating as we already validated before + addAbortSignalNoValidate(options.signal, composedStream) + } + return composedStream +} +function map(fn, options) { + if (typeof fn !== 'function') { + throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) } - return func.apply(thisArg, args); + if (options != null) { + validateObject(options, 'options') + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal') + } + let concurrency = 1 + if ((options === null || options === undefined ? undefined : options.concurrency) != null) { + concurrency = MathFloor(options.concurrency) + } + let highWaterMark = concurrency - 1 + if ((options === null || options === undefined ? undefined : options.highWaterMark) != null) { + highWaterMark = MathFloor(options.highWaterMark) + } + validateInteger(concurrency, 'options.concurrency', 1) + validateInteger(highWaterMark, 'options.highWaterMark', 0) + highWaterMark += concurrency + return async function* map() { + const signal = (__nccwpck_require__(46959).AbortSignalAny)( + [options === null || options === undefined ? undefined : options.signal].filter(Boolean) + ) + const stream = this + const queue = [] + const signalOpt = { + signal + } + let next + let resume + let done = false + let cnt = 0 + function onCatch() { + done = true + afterItemProcessed() + } + function afterItemProcessed() { + cnt -= 1 + maybeResume() + } + function maybeResume() { + if (resume && !done && cnt < concurrency && queue.length < highWaterMark) { + resume() + resume = null + } + } + async function pump() { + try { + for await (let val of stream) { + if (done) { + return + } + if (signal.aborted) { + throw new AbortError() + } + try { + val = fn(val, signalOpt) + if (val === kEmpty) { + continue + } + val = PromiseResolve(val) + } catch (err) { + val = PromiseReject(err) + } + cnt += 1 + PromisePrototypeThen(val, afterItemProcessed, onCatch) + queue.push(val) + if (next) { + next() + next = null + } + if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) { + await new Promise((resolve) => { + resume = resolve + }) + } + } + queue.push(kEof) + } catch (err) { + const val = PromiseReject(err) + PromisePrototypeThen(val, afterItemProcessed, onCatch) + queue.push(val) + } finally { + done = true + if (next) { + next() + next = null + } + } + } + pump() + try { + while (true) { + while (queue.length > 0) { + const val = await queue[0] + if (val === kEof) { + return + } + if (signal.aborted) { + throw new AbortError() + } + if (val !== kEmpty) { + yield val + } + queue.shift() + maybeResume() + } + await new Promise((resolve) => { + next = resolve + }) + } + } finally { + done = true + if (resume) { + resume() + resume = null + } + } + }.call(this) } - -/** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ -function arrayIncludes(array, value) { - var length = array ? array.length : 0; - return !!length && baseIndexOf(array, value, 0) > -1; +function asIndexedPairs(options = undefined) { + if (options != null) { + validateObject(options, 'options') + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal') + } + return async function* asIndexedPairs() { + let index = 0 + for await (const val of this) { + var _options$signal + if ( + options !== null && + options !== undefined && + (_options$signal = options.signal) !== null && + _options$signal !== undefined && + _options$signal.aborted + ) { + throw new AbortError({ + cause: options.signal.reason + }) + } + yield [index++, val] + } + }.call(this) } - -/** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ -function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array ? array.length : 0; - - while (++index < length) { - if (comparator(value, array[index])) { - return true; +async function some(fn, options = undefined) { + for await (const unused of filter.call(this, fn, options)) { + return true + } + return false +} +async function every(fn, options = undefined) { + if (typeof fn !== 'function') { + throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) + } + // https://en.wikipedia.org/wiki/De_Morgan%27s_laws + return !(await some.call( + this, + async (...args) => { + return !(await fn(...args)) + }, + options + )) +} +async function find(fn, options) { + for await (const result of filter.call(this, fn, options)) { + return result + } + return undefined +} +async function forEach(fn, options) { + if (typeof fn !== 'function') { + throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) + } + async function forEachFn(value, options) { + await fn(value, options) + return kEmpty + } + // eslint-disable-next-line no-unused-vars + for await (const unused of map.call(this, forEachFn, options)); +} +function filter(fn, options) { + if (typeof fn !== 'function') { + throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) + } + async function filterFn(value, options) { + if (await fn(value, options)) { + return value } + return kEmpty } - return false; + return map.call(this, filterFn, options) } -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ -function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; - - while (++index < length) { - array[offset + index] = values[index]; +// Specific to provide better error to reduce since the argument is only +// missing if the stream has no items in it - but the code is still appropriate +class ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS { + constructor() { + super('reduce') + this.message = 'Reduce of an empty stream requires an initial value' } - return array; } - -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; +async function reduce(reducer, initialValue, options) { + var _options$signal2 + if (typeof reducer !== 'function') { + throw new ERR_INVALID_ARG_TYPE('reducer', ['Function', 'AsyncFunction'], reducer) + } + if (options != null) { + validateObject(options, 'options') + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal') + } + let hasInitialValue = arguments.length > 1 + if ( + options !== null && + options !== undefined && + (_options$signal2 = options.signal) !== null && + _options$signal2 !== undefined && + _options$signal2.aborted + ) { + const err = new AbortError(undefined, { + cause: options.signal.reason + }) + this.once('error', () => {}) // The error is already propagated + await finished(this.destroy(err)) + throw err + } + const ac = new AbortController() + const signal = ac.signal + if (options !== null && options !== undefined && options.signal) { + const opts = { + once: true, + [kWeakHandler]: this, + [kResistStopPropagation]: true } + options.signal.addEventListener('abort', () => ac.abort(), opts) } - return -1; + let gotAnyItemFromStream = false + try { + for await (const value of this) { + var _options$signal3 + gotAnyItemFromStream = true + if ( + options !== null && + options !== undefined && + (_options$signal3 = options.signal) !== null && + _options$signal3 !== undefined && + _options$signal3.aborted + ) { + throw new AbortError() + } + if (!hasInitialValue) { + initialValue = value + hasInitialValue = true + } else { + initialValue = await reducer(initialValue, value, { + signal + }) + } + } + if (!gotAnyItemFromStream && !hasInitialValue) { + throw new ReduceAwareErrMissingArgs() + } + } finally { + ac.abort() + } + return initialValue } - -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - if (value !== value) { - return baseFindIndex(array, baseIsNaN, fromIndex); +async function toArray(options) { + if (options != null) { + validateObject(options, 'options') } - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal') + } + const result = [] + for await (const val of this) { + var _options$signal4 + if ( + options !== null && + options !== undefined && + (_options$signal4 = options.signal) !== null && + _options$signal4 !== undefined && + _options$signal4.aborted + ) { + throw new AbortError(undefined, { + cause: options.signal.reason + }) } + ArrayPrototypePush(result, val) } - return -1; + return result } - -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; +function flatMap(fn, options) { + const values = map.call(this, fn, options) + return async function* flatMap() { + for await (const val of values) { + yield* val + } + }.call(this) } - -/** - * Checks if a cache value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function cacheHas(cache, key) { - return cache.has(key); +function toIntegerOrInfinity(number) { + // We coerce here to align with the spec + // https://github.com/tc39/proposal-iterator-helpers/issues/169 + number = Number(number) + if (NumberIsNaN(number)) { + return 0 + } + if (number < 0) { + throw new ERR_OUT_OF_RANGE('number', '>= 0', number) + } + return number } - -/** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ -function getValue(object, key) { - return object == null ? undefined : object[key]; +function drop(number, options = undefined) { + if (options != null) { + validateObject(options, 'options') + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal') + } + number = toIntegerOrInfinity(number) + return async function* drop() { + var _options$signal5 + if ( + options !== null && + options !== undefined && + (_options$signal5 = options.signal) !== null && + _options$signal5 !== undefined && + _options$signal5.aborted + ) { + throw new AbortError() + } + for await (const val of this) { + var _options$signal6 + if ( + options !== null && + options !== undefined && + (_options$signal6 = options.signal) !== null && + _options$signal6 !== undefined && + _options$signal6.aborted + ) { + throw new AbortError() + } + if (number-- <= 0) { + yield val + } + } + }.call(this) } - -/** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ -function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} +function take(number, options = undefined) { + if (options != null) { + validateObject(options, 'options') } - return result; + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal') + } + number = toIntegerOrInfinity(number) + return async function* take() { + var _options$signal7 + if ( + options !== null && + options !== undefined && + (_options$signal7 = options.signal) !== null && + _options$signal7 !== undefined && + _options$signal7.aborted + ) { + throw new AbortError() + } + for await (const val of this) { + var _options$signal8 + if ( + options !== null && + options !== undefined && + (_options$signal8 = options.signal) !== null && + _options$signal8 !== undefined && + _options$signal8.aborted + ) { + throw new AbortError() + } + if (number-- > 0) { + yield val + } + + // Don't get another item from iterator in case we reached the end + if (number <= 0) { + return + } + } + }.call(this) +} +module.exports.streamReturningOperators = { + asIndexedPairs: deprecate(asIndexedPairs, 'readable.asIndexedPairs will be removed in a future version.'), + drop, + filter, + flatMap, + map, + take, + compose +} +module.exports.promiseReturningOperators = { + every, + forEach, + reduce, + toArray, + some, + find } -/** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ -function setToArray(set) { - var index = -1, - result = Array(set.size); - set.forEach(function(value) { - result[++index] = value; - }); - return result; -} +/***/ }), -/** Used for built-in method references. */ -var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; +/***/ 72839: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** Used to detect overreaching core-js shims. */ -var coreJsData = root['__core-js_shared__']; +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -/** Used to detect methods masquerading as native. */ -var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; -}()); +// a passthrough stream. +// basically just the most minimal sort of Transform stream. +// Every written chunk gets output as-is. -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +const { ObjectSetPrototypeOf } = __nccwpck_require__(89629) +module.exports = PassThrough +const Transform = __nccwpck_require__(86941) +ObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype) +ObjectSetPrototypeOf(PassThrough, Transform) +function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options) + Transform.call(this, options) +} +PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk) +} -/** Used to detect if a method is native. */ -var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' -); -/** Built-in value references. */ -var Symbol = root.Symbol, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; +/***/ }), -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; +/***/ 76989: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* Built-in method references that are verified to be native. */ -var Map = getNative(root, 'Map'), - Set = getNative(root, 'Set'), - nativeCreate = getNative(Object, 'create'); +/* replacement start */ -/** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function Hash(entries) { - var index = -1, - length = entries ? entries.length : 0; +const process = __nccwpck_require__(45676) - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} +/* replacement end */ +// Ported from https://github.com/mafintosh/pump with +// permission from the author, Mathias Buus (@mafintosh). -/** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ -function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; +;('use strict') +const { ArrayIsArray, Promise, SymbolAsyncIterator, SymbolDispose } = __nccwpck_require__(89629) +const eos = __nccwpck_require__(76080) +const { once } = __nccwpck_require__(46959) +const destroyImpl = __nccwpck_require__(97049) +const Duplex = __nccwpck_require__(72613) +const { + aggregateTwoErrors, + codes: { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_RETURN_VALUE, + ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED, + ERR_STREAM_PREMATURE_CLOSE + }, + AbortError +} = __nccwpck_require__(80529) +const { validateFunction, validateAbortSignal } = __nccwpck_require__(669) +const { + isIterable, + isReadable, + isReadableNodeStream, + isNodeStream, + isTransformStream, + isWebStream, + isReadableStream, + isReadableFinished +} = __nccwpck_require__(27981) +const AbortController = globalThis.AbortController || (__nccwpck_require__(61659).AbortController) +let PassThrough +let Readable +let addAbortListener +function destroyer(stream, reading, writing) { + let finished = false + stream.on('close', () => { + finished = true + }) + const cleanup = eos( + stream, + { + readable: reading, + writable: writing + }, + (err) => { + finished = !err + } + ) + return { + destroy: (err) => { + if (finished) return + finished = true + destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED('pipe')) + }, + cleanup + } } - -/** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function hashDelete(key) { - return this.has(key) && delete this.__data__[key]; +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. + validateFunction(streams[streams.length - 1], 'streams[stream.length - 1]') + return streams.pop() +} +function makeAsyncIterable(val) { + if (isIterable(val)) { + return val + } else if (isReadableNodeStream(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 = __nccwpck_require__(57920) + } + yield* Readable.prototype[SymbolAsyncIterator].call(val) +} +async function pumpToNode(iterable, writable, finish, { end }) { + let error + let onresolve = null + const resume = (err) => { + if (err) { + error = err + } + if (onresolve) { + const callback = onresolve + onresolve = null + callback() + } + } + const wait = () => + new Promise((resolve, reject) => { + if (error) { + reject(error) + } else { + onresolve = () => { + if (error) { + reject(error) + } else { + resolve() + } + } + } + }) + writable.on('drain', resume) + const cleanup = eos( + writable, + { + readable: false + }, + resume + ) + try { + if (writable.writableNeedDrain) { + await wait() + } + for await (const chunk of iterable) { + if (!writable.write(chunk)) { + await wait() + } + } + if (end) { + writable.end() + await wait() + } + finish() + } catch (err) { + finish(error !== err ? aggregateTwoErrors(error, err) : err) + } finally { + cleanup() + writable.off('drain', resume) + } } - -/** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; +async function pumpToWeb(readable, writable, finish, { end }) { + if (isTransformStream(writable)) { + writable = writable.writable + } + // https://streams.spec.whatwg.org/#example-manual-write-with-backpressure + const writer = writable.getWriter() + try { + for await (const chunk of readable) { + await writer.ready + writer.write(chunk).catch(() => {}) + } + await writer.ready + if (end) { + await writer.close() + } + finish() + } catch (err) { + try { + await writer.abort(err) + finish(err) + } catch (err) { + finish(err) + } } - return hasOwnProperty.call(data, key) ? data[key] : undefined; } - -/** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function hashHas(key) { - var data = this.__data__; - return nativeCreate ? data[key] !== undefined : hasOwnProperty.call(data, key); +function pipeline(...streams) { + return pipelineImpl(streams, once(popCallback(streams))) } +function pipelineImpl(streams, callback, opts) { + if (streams.length === 1 && ArrayIsArray(streams[0])) { + streams = streams[0] + } + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams') + } + const ac = new AbortController() + const signal = ac.signal + const outerSignal = opts === null || opts === undefined ? undefined : opts.signal + + // Need to cleanup event listeners if last stream is readable + // https://github.com/nodejs/node/issues/35452 + const lastStreamCleanup = [] + validateAbortSignal(outerSignal, 'options.signal') + function abort() { + finishImpl(new AbortError()) + } + addAbortListener = addAbortListener || (__nccwpck_require__(46959).addAbortListener) + let disposable + if (outerSignal) { + disposable = addAbortListener(outerSignal, abort) + } + let error + let value + const destroys = [] + let finishCount = 0 + function finish(err) { + finishImpl(err, --finishCount === 0) + } + function finishImpl(err, final) { + var _disposable + if (err && (!error || error.code === 'ERR_STREAM_PREMATURE_CLOSE')) { + error = err + } + if (!error && !final) { + return + } + while (destroys.length) { + destroys.shift()(error) + } + ;(_disposable = disposable) === null || _disposable === undefined ? undefined : _disposable[SymbolDispose]() + ac.abort() + if (final) { + if (!error) { + lastStreamCleanup.forEach((fn) => fn()) + } + process.nextTick(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 + const end = reading || (opts === null || opts === undefined ? undefined : opts.end) !== false + const isLastStream = i === streams.length - 1 + if (isNodeStream(stream)) { + if (end) { + const { destroy, cleanup } = destroyer(stream, reading, writing) + destroys.push(destroy) + if (isReadable(stream) && isLastStream) { + lastStreamCleanup.push(cleanup) + } + } -/** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ -function hashSet(key, value) { - var data = this.__data__; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; -} + // Catch stream errors that occur after pipe/pump has completed. + function onError(err) { + if (err && err.name !== 'AbortError' && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + finish(err) + } + } + stream.on('error', onError) + if (isReadable(stream) && isLastStream) { + lastStreamCleanup.push(() => { + stream.removeListener('error', onError) + }) + } + } + if (i === 0) { + if (typeof stream === 'function') { + ret = stream({ + signal + }) + if (!isIterable(ret)) { + throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or Stream', 'source', ret) + } + } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) { + ret = stream + } else { + ret = Duplex.from(stream) + } + } else if (typeof stream === 'function') { + if (isTransformStream(ret)) { + var _ret + ret = makeAsyncIterable((_ret = ret) === null || _ret === undefined ? undefined : _ret.readable) + } else { + ret = makeAsyncIterable(ret) + } + ret = stream(ret, { + signal + }) + if (reading) { + if (!isIterable(ret, true)) { + throw new ERR_INVALID_RETURN_VALUE('AsyncIterable', `transform[${i - 1}]`, ret) + } + } else { + var _ret2 + if (!PassThrough) { + PassThrough = __nccwpck_require__(72839) + } -// Add methods to `Hash`. -Hash.prototype.clear = hashClear; -Hash.prototype['delete'] = hashDelete; -Hash.prototype.get = hashGet; -Hash.prototype.has = hashHas; -Hash.prototype.set = hashSet; + // 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)`. -/** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function ListCache(entries) { - var index = -1, - length = entries ? entries.length : 0; + const pt = new PassThrough({ + objectMode: true + }) - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); + // Handle Promises/A+ spec, `then` could be a getter that throws on + // second use. + const then = (_ret2 = ret) === null || _ret2 === undefined ? undefined : _ret2.then + if (typeof then === 'function') { + finishCount++ + then.call( + ret, + (val) => { + value = val + if (val != null) { + pt.write(val) + } + if (end) { + pt.end() + } + process.nextTick(finish) + }, + (err) => { + pt.destroy(err) + process.nextTick(finish, err) + } + ) + } else if (isIterable(ret, true)) { + finishCount++ + pumpToNode(ret, pt, finish, { + end + }) + } else if (isReadableStream(ret) || isTransformStream(ret)) { + const toRead = ret.readable || ret + finishCount++ + pumpToNode(toRead, pt, finish, { + end + }) + } else { + throw new ERR_INVALID_RETURN_VALUE('AsyncIterable or Promise', 'destination', ret) + } + ret = pt + const { destroy, cleanup } = destroyer(ret, false, true) + destroys.push(destroy) + if (isLastStream) { + lastStreamCleanup.push(cleanup) + } + } + } else if (isNodeStream(stream)) { + if (isReadableNodeStream(ret)) { + finishCount += 2 + const cleanup = pipe(ret, stream, finish, { + end + }) + if (isReadable(stream) && isLastStream) { + lastStreamCleanup.push(cleanup) + } + } else if (isTransformStream(ret) || isReadableStream(ret)) { + const toRead = ret.readable || ret + finishCount++ + pumpToNode(toRead, stream, finish, { + end + }) + } else if (isIterable(ret)) { + finishCount++ + pumpToNode(ret, stream, finish, { + end + }) + } else { + throw new ERR_INVALID_ARG_TYPE( + 'val', + ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'], + ret + ) + } + ret = stream + } else if (isWebStream(stream)) { + if (isReadableNodeStream(ret)) { + finishCount++ + pumpToWeb(makeAsyncIterable(ret), stream, finish, { + end + }) + } else if (isReadableStream(ret) || isIterable(ret)) { + finishCount++ + pumpToWeb(ret, stream, finish, { + end + }) + } else if (isTransformStream(ret)) { + finishCount++ + pumpToWeb(ret.readable, stream, finish, { + end + }) + } else { + throw new ERR_INVALID_ARG_TYPE( + 'val', + ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'], + ret + ) + } + ret = stream + } else { + ret = Duplex.from(stream) + } } -} - -/** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ -function listCacheClear() { - this.__data__ = []; -} - -/** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - if (index < 0) { - return false; + if ( + (signal !== null && signal !== undefined && signal.aborted) || + (outerSignal !== null && outerSignal !== undefined && outerSignal.aborted) + ) { + process.nextTick(abort) } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); + return ret +} +function pipe(src, dst, finish, { end }) { + let ended = false + dst.on('close', () => { + if (!ended) { + // Finish if the destination closes before the source has completed. + finish(new ERR_STREAM_PREMATURE_CLOSE()) + } + }) + src.pipe(dst, { + end: false + }) // If end is true we already will have a listener to end dst. + + if (end) { + // 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. + + function endFn() { + ended = true + dst.end() + } + if (isReadableFinished(src)) { + // End the destination if the source has already ended. + process.nextTick(endFn) + } else { + src.once('end', endFn) + } } else { - splice.call(data, index, 1); + finish() } - return true; + eos( + src, + { + readable: true, + writable: false + }, + (err) => { + const rState = src._readableState + if ( + err && + err.code === 'ERR_STREAM_PREMATURE_CLOSE' && + 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. + src.once('end', finish).once('error', finish) + } else { + finish(err) + } + } + ) + return eos( + dst, + { + readable: false, + writable: true + }, + finish + ) } - -/** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); - - return index < 0 ? undefined : data[index][1]; +module.exports = { + pipelineImpl, + pipeline } -/** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; -} -/** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ -function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); +/***/ }), - if (index < 0) { - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; -} +/***/ 57920: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Add methods to `ListCache`. -ListCache.prototype.clear = listCacheClear; -ListCache.prototype['delete'] = listCacheDelete; -ListCache.prototype.get = listCacheGet; -ListCache.prototype.has = listCacheHas; -ListCache.prototype.set = listCacheSet; +/* replacement start */ -/** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ -function MapCache(entries) { - var index = -1, - length = entries ? entries.length : 0; +const process = __nccwpck_require__(45676) - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } -} +/* replacement end */ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -/** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ -function mapCacheClear() { - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; -} +;('use strict') +const { + ArrayPrototypeIndexOf, + NumberIsInteger, + NumberIsNaN, + NumberParseInt, + ObjectDefineProperties, + ObjectKeys, + ObjectSetPrototypeOf, + Promise, + SafeSet, + SymbolAsyncDispose, + SymbolAsyncIterator, + Symbol +} = __nccwpck_require__(89629) +module.exports = Readable +Readable.ReadableState = ReadableState +const { EventEmitter: EE } = __nccwpck_require__(82361) +const { Stream, prependListener } = __nccwpck_require__(49792) +const { Buffer } = __nccwpck_require__(14300) +const { addAbortSignal } = __nccwpck_require__(80289) +const eos = __nccwpck_require__(76080) +let debug = (__nccwpck_require__(46959).debuglog)('stream', (fn) => { + debug = fn +}) +const BufferList = __nccwpck_require__(52746) +const destroyImpl = __nccwpck_require__(97049) +const { getHighWaterMark, getDefaultHighWaterMark } = __nccwpck_require__(39948) +const { + aggregateTwoErrors, + codes: { + ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED, + ERR_OUT_OF_RANGE, + ERR_STREAM_PUSH_AFTER_EOF, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT + }, + AbortError +} = __nccwpck_require__(80529) +const { validateObject } = __nccwpck_require__(669) +const kPaused = Symbol('kPaused') +const { StringDecoder } = __nccwpck_require__(71576) +const from = __nccwpck_require__(39082) +ObjectSetPrototypeOf(Readable.prototype, Stream.prototype) +ObjectSetPrototypeOf(Readable, Stream) +const nop = () => {} +const { errorOrDestroy } = destroyImpl +const kObjectMode = 1 << 0 +const kEnded = 1 << 1 +const kEndEmitted = 1 << 2 +const kReading = 1 << 3 +const kConstructed = 1 << 4 +const kSync = 1 << 5 +const kNeedReadable = 1 << 6 +const kEmittedReadable = 1 << 7 +const kReadableListening = 1 << 8 +const kResumeScheduled = 1 << 9 +const kErrorEmitted = 1 << 10 +const kEmitClose = 1 << 11 +const kAutoDestroy = 1 << 12 +const kDestroyed = 1 << 13 +const kClosed = 1 << 14 +const kCloseEmitted = 1 << 15 +const kMultiAwaitDrain = 1 << 16 +const kReadingMore = 1 << 17 +const kDataEmitted = 1 << 18 + +// TODO(benjamingr) it is likely slower to do it this way than with free functions +function makeBitMapDescriptor(bit) { + return { + enumerable: false, + get() { + return (this.state & bit) !== 0 + }, + set(value) { + if (value) this.state |= bit + else this.state &= ~bit + } + } +} +ObjectDefineProperties(ReadableState.prototype, { + objectMode: makeBitMapDescriptor(kObjectMode), + ended: makeBitMapDescriptor(kEnded), + endEmitted: makeBitMapDescriptor(kEndEmitted), + reading: makeBitMapDescriptor(kReading), + // Stream is still being constructed and cannot be + // destroyed until construction finished or failed. + // Async construction is opt in, therefore we start as + // constructed. + constructed: makeBitMapDescriptor(kConstructed), + // A flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + sync: makeBitMapDescriptor(kSync), + // Whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + needReadable: makeBitMapDescriptor(kNeedReadable), + emittedReadable: makeBitMapDescriptor(kEmittedReadable), + readableListening: makeBitMapDescriptor(kReadableListening), + resumeScheduled: makeBitMapDescriptor(kResumeScheduled), + // True if the error was already emitted and should not be thrown again. + errorEmitted: makeBitMapDescriptor(kErrorEmitted), + emitClose: makeBitMapDescriptor(kEmitClose), + autoDestroy: makeBitMapDescriptor(kAutoDestroy), + // Has it been destroyed. + destroyed: makeBitMapDescriptor(kDestroyed), + // Indicates whether the stream has finished destroying. + closed: makeBitMapDescriptor(kClosed), + // True if close has been emitted or would have been emitted + // depending on emitClose. + closeEmitted: makeBitMapDescriptor(kCloseEmitted), + multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain), + // If true, a maybeReadMore has been scheduled. + readingMore: makeBitMapDescriptor(kReadingMore), + dataEmitted: makeBitMapDescriptor(kDataEmitted) +}) +function ReadableState(options, stream, isDuplex) { + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof __nccwpck_require__(72613) -/** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ -function mapCacheDelete(key) { - return getMapData(this, key)['delete'](key); -} + // Bit map field to store ReadableState more effciently with 1 bit per field + // instead of a V8 slot per field. + this.state = kEmitClose | kAutoDestroy | kConstructed | kSync + // Object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away. + if (options && options.objectMode) this.state |= kObjectMode + if (isDuplex && options && options.readableObjectMode) this.state |= kObjectMode -/** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ -function mapCacheGet(key) { - return getMapData(this, key).get(key); -} + // The point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = options + ? getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex) + : getDefaultHighWaterMark(false) -/** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ -function mapCacheHas(key) { - return getMapData(this, key).has(key); -} + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift(). + this.buffer = new BufferList() + this.length = 0 + this.pipes = [] + this.flowing = null + this[kPaused] = null -/** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ -function mapCacheSet(key, value) { - getMapData(this, key).set(key, value); - return this; -} + // Should close be emitted on destroy. Defaults to true. + if (options && options.emitClose === false) this.state &= ~kEmitClose -// Add methods to `MapCache`. -MapCache.prototype.clear = mapCacheClear; -MapCache.prototype['delete'] = mapCacheDelete; -MapCache.prototype.get = mapCacheGet; -MapCache.prototype.has = mapCacheHas; -MapCache.prototype.set = mapCacheSet; + // Should .destroy() be called after 'end' (and potentially 'finish'). + if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy -/** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ -function SetCache(values) { - var index = -1, - length = values ? values.length : 0; + // Indicates whether the stream has errored. When true no further + // _read calls, 'data' or 'readable' events should occur. This is needed + // since when autoDestroy is disabled we need a way to tell whether the + // stream has failed. + this.errored = null - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = (options && options.defaultEncoding) || 'utf8' + + // Ref the piped dest which we need a drain event on it + // type: null | Writable | Set. + this.awaitDrainWriters = null + this.decoder = null + this.encoding = null + if (options && options.encoding) { + this.decoder = new StringDecoder(options.encoding) + this.encoding = options.encoding } } +function Readable(options) { + if (!(this instanceof Readable)) return new Readable(options) -/** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ -function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5. + const isDuplex = this instanceof __nccwpck_require__(72613) + this._readableState = new ReadableState(options, this, isDuplex) + if (options) { + if (typeof options.read === 'function') this._read = options.read + if (typeof options.destroy === 'function') this._destroy = options.destroy + if (typeof options.construct === 'function') this._construct = options.construct + if (options.signal && !isDuplex) addAbortSignal(options.signal, this) + } + Stream.call(this, options) + destroyImpl.construct(this, () => { + if (this._readableState.needReadable) { + maybeReadMore(this, this._readableState) + } + }) } - -/** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ -function setCacheHas(value) { - return this.__data__.has(value); +Readable.prototype.destroy = destroyImpl.destroy +Readable.prototype._undestroy = destroyImpl.undestroy +Readable.prototype._destroy = function (err, cb) { + cb(err) } - -// Add methods to `SetCache`. -SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; -SetCache.prototype.has = setCacheHas; - -/** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } +Readable.prototype[EE.captureRejectionSymbol] = function (err) { + this.destroy(err) +} +Readable.prototype[SymbolAsyncDispose] = function () { + let error + if (!this.destroyed) { + error = this.readableEnded ? null : new AbortError() + this.destroy(error) } - return -1; + return new Promise((resolve, reject) => eos(this, (err) => (err && err !== error ? reject(err) : resolve(null)))) } -/** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ -function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; - - predicate || (predicate = isFlattenable); - result || (result = []); +// Manually shove something into the read() buffer. +// This returns true if the highWaterMark has not been hit yet, +// similar to how Writable.write() returns true if you should +// write() some more. +Readable.prototype.push = function (chunk, encoding) { + return readableAddChunk(this, chunk, encoding, false) +} - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); +// Unshift should *always* be something directly out of read(). +Readable.prototype.unshift = function (chunk, encoding) { + return readableAddChunk(this, chunk, encoding, true) +} +function readableAddChunk(stream, chunk, encoding, addToFront) { + debug('readableAddChunk', chunk) + const state = stream._readableState + let err + if ((state.state & kObjectMode) === 0) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding + if (state.encoding !== encoding) { + if (addToFront && state.encoding) { + // When unshifting, if state.encoding is set, we have to save + // the string in the BufferList with the state encoding. + chunk = Buffer.from(chunk, encoding).toString(state.encoding) + } else { + chunk = Buffer.from(chunk, encoding) + encoding = '' + } + } + } else if (chunk instanceof Buffer) { + encoding = '' + } else if (Stream._isUint8Array(chunk)) { + chunk = Stream._uint8ArrayToBuffer(chunk) + encoding = '' + } else if (chunk != null) { + err = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk) + } + } + if (err) { + errorOrDestroy(stream, err) + } else if (chunk === null) { + state.state &= ~kReading + onEofChunk(stream, state) + } else if ((state.state & kObjectMode) !== 0 || (chunk && chunk.length > 0)) { + if (addToFront) { + if ((state.state & kEndEmitted) !== 0) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()) + else if (state.destroyed || state.errored) return false + else addChunk(stream, state, chunk, true) + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()) + } else if (state.destroyed || state.errored) { + return false + } else { + state.state &= ~kReading + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk) + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false) + else maybeReadMore(stream, state) } else { - arrayPush(result, value); + addChunk(stream, state, chunk, false) } - } else if (!isStrict) { - result[result.length] = value; } + } else if (!addToFront) { + state.state &= ~kReading + maybeReadMore(stream, state) } - return result; + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0) +} +function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount('data') > 0) { + // Use the guard to avoid creating `Set()` repeatedly + // when we have multiple pipes. + if ((state.state & kMultiAwaitDrain) !== 0) { + state.awaitDrainWriters.clear() + } else { + state.awaitDrainWriters = null + } + state.dataEmitted = true + stream.emit('data', chunk) + } else { + // Update the buffer info. + state.length += state.objectMode ? 1 : chunk.length + if (addToFront) state.buffer.unshift(chunk) + else state.buffer.push(chunk) + if ((state.state & kNeedReadable) !== 0) emitReadable(stream) + } + maybeReadMore(stream, state) +} +Readable.prototype.isPaused = function () { + const state = this._readableState + return state[kPaused] === true || state.flowing === false } -/** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ -function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; +// Backwards compatibility. +Readable.prototype.setEncoding = function (enc) { + const decoder = new StringDecoder(enc) + this._readableState.decoder = decoder + // If setEncoding(null), decoder.encoding equals utf8. + this._readableState.encoding = this._readableState.decoder.encoding + const buffer = this._readableState.buffer + // Iterate over current buffer to convert already stored Buffers: + let content = '' + for (const data of buffer) { + content += decoder.write(data) } - var pattern = (isFunction(value) || isHostObject(value)) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); + buffer.clear() + if (content !== '') buffer.push(content) + this._readableState.length = content.length + return this } -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); +// Don't raise the hwm > 1GB. +const MAX_HWM = 0x40000000 +function computeNewHighWaterMark(n) { + if (n > MAX_HWM) { + throw new ERR_OUT_OF_RANGE('size', '<= 1GiB', n) + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts. + n-- + n |= n >>> 1 + n |= n >>> 2 + n |= n >>> 4 + n |= n >>> 8 + n |= n >>> 16 + n++ + } + return n +} - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function howMuchToRead(n, state) { + if (n <= 0 || (state.length === 0 && state.ended)) return 0 + if ((state.state & kObjectMode) !== 0) return 1 + if (NumberIsNaN(n)) { + // Only flow one buffer at a time. + if (state.flowing && state.length) return state.buffer.first().length + return state.length + } + if (n <= state.length) return n + return state.ended ? state.length : 0 } -/** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ -function baseUniq(array, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - length = array.length, - isCommon = true, - result = [], - seen = result; +// You can override either this method, or the async _read(n) below. +Readable.prototype.read = function (n) { + debug('read', n) + // Same as parseInt(undefined, 10), however V8 7.3 performance regressed + // in this scenario, so we are doing it manually. + if (n === undefined) { + n = NaN + } else if (!NumberIsInteger(n)) { + n = NumberParseInt(n, 10) + } + const state = this._readableState + const nOrig = n - if (comparator) { - isCommon = false; - includes = arrayIncludesWith; + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n) + if (n !== 0) state.state &= ~kEmittedReadable + + // If we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if ( + n === 0 && + state.needReadable && + ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended) + ) { + debug('read: emitReadable', state.length, state.ended) + if (state.length === 0 && state.ended) endReadable(this) + else emitReadable(this) + return null } - else if (length >= LARGE_ARRAY_SIZE) { - var set = iteratee ? null : createSet(array); - if (set) { - return setToArray(set); - } - isCommon = false; - includes = cacheHas; - seen = new SetCache; + n = howMuchToRead(n, state) + + // If we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this) + return null } - else { - seen = iteratee ? [] : result; + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + let doRead = (state.state & kNeedReadable) !== 0 + debug('need readable', doRead) + + // If we currently have less than the highWaterMark, then also read some. + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true + debug('length less than watermark', doRead) } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee) { - seen.push(computed); - } - result.push(value); + // However, if we've ended, then there's no point, if we're already + // reading, then it's unnecessary, if we're constructing we have to wait, + // and if we're destroyed or errored, then it's not allowed, + if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) { + doRead = false + debug('reading, ended or constructing', doRead) + } else if (doRead) { + debug('do read') + state.state |= kReading | kSync + // If the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.state |= kNeedReadable + + // Call internal read method + try { + this._read(state.highWaterMark) + } catch (err) { + errorOrDestroy(this, err) } - else if (!includes(seen, computed, comparator)) { - if (seen !== result) { - seen.push(computed); - } - result.push(value); + state.state &= ~kSync + + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state) + } + let ret + if (n > 0) ret = fromList(n, state) + else ret = null + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark + n = 0 + } else { + state.length -= n + if (state.multiAwaitDrain) { + state.awaitDrainWriters.clear() + } else { + state.awaitDrainWriters = null } } - return result; -} - -/** - * Creates a set object of `values`. - * - * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. - */ -var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { - return new Set(values); -}; + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true -/** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ -function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this) + } + if (ret !== null && !state.errorEmitted && !state.closeEmitted) { + state.dataEmitted = true + this.emit('data', ret) + } + return ret +} +function onEofChunk(stream, state) { + debug('onEofChunk') + if (state.ended) return + if (state.decoder) { + const chunk = state.decoder.end() + if (chunk && chunk.length) { + state.buffer.push(chunk) + state.length += state.objectMode ? 1 : chunk.length + } + } + state.ended = true + if (state.sync) { + // If we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call. + emitReadable(stream) + } else { + // Emit 'readable' now to make sure it gets picked up. + state.needReadable = false + state.emittedReadable = true + // We have to emit readable now that we are EOF. Modules + // in the ecosystem (e.g. dicer) rely on this event being sync. + emitReadable_(stream) + } } -/** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ -function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; +// Don't emit readable right away in sync mode, because this can trigger +// another read() call => stack overflow. This way, it might trigger +// a nextTick recursion warning, but that's not so bad. +function emitReadable(stream) { + const state = stream._readableState + debug('emitReadable', state.needReadable, state.emittedReadable) + state.needReadable = false + if (!state.emittedReadable) { + debug('emitReadable', state.flowing) + state.emittedReadable = true + process.nextTick(emitReadable_, stream) + } } +function emitReadable_(stream) { + const state = stream._readableState + debug('emitReadable_', state.destroyed, state.length, state.ended) + if (!state.destroyed && !state.errored && (state.length || state.ended)) { + stream.emit('readable') + state.emittedReadable = false + } -/** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ -function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); + // The stream needs another readable event if: + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark + flow(stream) } -/** - * Checks if `value` is suitable for use as unique object key. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. - */ -function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); +// At this point, the user has presumably seen the 'readable' event, +// and called read() to consume some data. that may have triggered +// in turn another _read(n) call, in which case reading = true if +// it's in progress. +// However, if we're not ended, or reading, and the length < hwm, +// then go ahead and try to read some more preemptively. +function maybeReadMore(stream, state) { + if (!state.readingMore && state.constructed) { + state.readingMore = true + process.nextTick(maybeReadMore_, stream, state) + } +} +function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while ( + !state.reading && + !state.ended && + (state.length < state.highWaterMark || (state.flowing && state.length === 0)) + ) { + const len = state.length + debug('maybeReadMore read 0') + stream.read(0) + if (len === state.length) + // Didn't get any data, stop spinning. + break + } + state.readingMore = false } -/** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ -function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); +// Abstract method. to be overridden in specific implementation classes. +// call cb(er, data) where data is <= n in length. +// for virtual (non-string, non-buffer) streams, "length" is somewhat +// arbitrary, and perhaps not very meaningful. +Readable.prototype._read = function (n) { + throw new ERR_METHOD_NOT_IMPLEMENTED('_read()') } +Readable.prototype.pipe = function (dest, pipeOpts) { + const src = this + const state = this._readableState + if (state.pipes.length === 1) { + if (!state.multiAwaitDrain) { + state.multiAwaitDrain = true + state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : []) + } + } + state.pipes.push(dest) + debug('pipe count=%d opts=%j', state.pipes.length, pipeOpts) + const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr + const endFn = doEnd ? onend : unpipe + if (state.endEmitted) process.nextTick(endFn) + else src.once('end', endFn) + dest.on('unpipe', onunpipe) + function onunpipe(readable, unpipeInfo) { + debug('onunpipe') + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true + cleanup() + } + } + } + function onend() { + debug('onend') + dest.end() + } + let ondrain + let cleanedUp = false + function cleanup() { + debug('cleanup') + // Cleanup event handlers once the pipe is broken. + dest.removeListener('close', onclose) + dest.removeListener('finish', onfinish) + if (ondrain) { + dest.removeListener('drain', ondrain) + } + dest.removeListener('error', onerror) + dest.removeListener('unpipe', onunpipe) + src.removeListener('end', onend) + src.removeListener('end', unpipe) + src.removeListener('data', ondata) + cleanedUp = true + + // If the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain() + } + function pause() { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if (!cleanedUp) { + if (state.pipes.length === 1 && state.pipes[0] === dest) { + debug('false write response, pause', 0) + state.awaitDrainWriters = dest + state.multiAwaitDrain = false + } else if (state.pipes.length > 1 && state.pipes.includes(dest)) { + debug('false write response, pause', state.awaitDrainWriters.size) + state.awaitDrainWriters.add(dest) + } + src.pause() + } + if (!ondrain) { + // When the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + ondrain = pipeOnDrain(src, dest) + dest.on('drain', ondrain) + } + } + src.on('data', ondata) + function ondata(chunk) { + debug('ondata') + const ret = dest.write(chunk) + debug('dest.write', ret) + if (ret === false) { + pause() + } + } -/** - * Converts `func` to its source code. - * - * @private - * @param {Function} func The function to process. - * @returns {string} Returns the source code. - */ -function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} + // If the dest has an error, then stop piping into it. + // However, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er) + unpipe() + dest.removeListener('error', onerror) + if (dest.listenerCount('error') === 0) { + const s = dest._writableState || dest._readableState + if (s && !s.errorEmitted) { + // User incorrectly emitted 'error' directly on the stream. + errorOrDestroy(dest, er) + } else { + dest.emit('error', er) + } + } } - return ''; -} -/** - * Creates an array of unique values, in order, from all given arrays using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.union([2], [1, 2]); - * // => [2, 1] - */ -var union = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); -}); + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror) -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish) + unpipe() + } + dest.once('close', onclose) + function onfinish() { + debug('onfinish') + dest.removeListener('close', onclose) + unpipe() + } + dest.once('finish', onfinish) + function unpipe() { + debug('unpipe') + src.unpipe(dest) + } + + // Tell the dest that it's being piped to. + dest.emit('pipe', src) + + // Start the flow if it hasn't been started already. + + if (dest.writableNeedDrain === true) { + pause() + } else if (!state.flowing) { + debug('pipe resume') + src.resume() + } + return dest } +function pipeOnDrain(src, dest) { + return function pipeOnDrainFunctionResult() { + const state = src._readableState -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); + // `ondrain` will call directly, + // `this` maybe not a reference to dest, + // so we use the real dest here. + if (state.awaitDrainWriters === dest) { + debug('pipeOnDrain', 1) + state.awaitDrainWriters = null + } else if (state.multiAwaitDrain) { + debug('pipeOnDrain', state.awaitDrainWriters.size) + state.awaitDrainWriters.delete(dest) + } + if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount('data')) { + src.resume() + } + } } +Readable.prototype.unpipe = function (dest) { + const state = this._readableState + const unpipeInfo = { + hasUnpiped: false + } -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; + // If we're not piping anywhere, then do nothing. + if (state.pipes.length === 0) return this + if (!dest) { + // remove all. + const dests = state.pipes + state.pipes = [] + this.pause() + for (let i = 0; i < dests.length; i++) + dests[i].emit('unpipe', this, { + hasUnpiped: false + }) + return this + } -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); + // Try to find the right one. + const index = ArrayPrototypeIndexOf(state.pipes, dest) + if (index === -1) return this + state.pipes.splice(index, 1) + if (state.pipes.length === 0) this.pause() + dest.emit('unpipe', this, unpipeInfo) + return this } -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} +// Set up data events if they are asked for +// Ensure readable listeners eventually get something. +Readable.prototype.on = function (ev, fn) { + const res = Stream.prototype.on.call(this, ev, fn) + const state = this._readableState + if (ev === 'data') { + // Update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0 -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; + // Try start flowing on next tick if stream isn't explicitly paused. + if (state.flowing !== false) this.resume() + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true + state.flowing = false + state.emittedReadable = false + debug('on readable', state.length, state.reading) + if (state.length) { + emitReadable(this) + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this) + } + } + } + return res +} +Readable.prototype.addListener = Readable.prototype.on +Readable.prototype.removeListener = function (ev, fn) { + const res = Stream.prototype.removeListener.call(this, ev, fn) + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this) + } + return res +} +Readable.prototype.off = Readable.prototype.removeListener +Readable.prototype.removeAllListeners = function (ev) { + const res = Stream.prototype.removeAllListeners.apply(this, arguments) + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this) + } + return res } +function updateReadableListening(self) { + const state = self._readableState + state.readableListening = self.listenerCount('readable') > 0 + if (state.resumeScheduled && state[kPaused] === false) { + // Flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + // Crude way to check if we should resume. + } else if (self.listenerCount('data') > 0) { + self.resume() + } else if (!state.readableListening) { + state.flowing = null + } +} +function nReadingNextTick(self) { + debug('readable nexttick read 0') + self.read(0) } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); +// pause() and resume() are remnants of the legacy readable stream API +// If the user uses them, then switch into old mode. +Readable.prototype.resume = function () { + const state = this._readableState + if (!state.flowing) { + debug('resume') + // We flow only if there is no one listening + // for readable, but we still have to call + // resume(). + state.flowing = !state.readableListening + resume(this, state) + } + state[kPaused] = false + return this } - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true + process.nextTick(resume_, stream, state) + } } - -/** - * This method returns `undefined`. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example - * - * _.times(2, _.noop); - * // => [undefined, undefined] - */ -function noop() { - // No operation performed. +function resume_(stream, state) { + debug('resume', state.reading) + if (!state.reading) { + stream.read(0) + } + state.resumeScheduled = false + stream.emit('resume') + flow(stream) + if (state.flowing && !state.reading) stream.read(0) +} +Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing) + if (this._readableState.flowing !== false) { + debug('pause') + this._readableState.flowing = false + this.emit('pause') + } + this._readableState[kPaused] = true + return this +} +function flow(stream) { + const state = stream._readableState + debug('flow', state.flowing) + while (state.flowing && stream.read() !== null); } -module.exports = union; - - -/***/ }), - -/***/ 47426: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015-2022 Douglas Christopher Wilson - * MIT Licensed - */ - -/** - * Module exports. - */ - -module.exports = __nccwpck_require__(53765) - - -/***/ }), - -/***/ 43583: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; -/*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - * @private - */ - -var db = __nccwpck_require__(47426) -var extname = (__nccwpck_require__(71017).extname) - -/** - * Module variables. - * @private - */ - -var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ -var TEXT_TYPE_REGEXP = /^text\//i - -/** - * Module exports. - * @public - */ - -exports.charset = charset -exports.charsets = { lookup: charset } -exports.contentType = contentType -exports.extension = extension -exports.extensions = Object.create(null) -exports.lookup = lookup -exports.types = Object.create(null) - -// Populate the extensions/types maps -populateMaps(exports.extensions, exports.types) +// Wrap an old-style stream as the async data source. +// This is *not* part of the readable stream interface. +// It is an ugly unfortunate mess of history. +Readable.prototype.wrap = function (stream) { + let paused = false -/** - * Get the default charset for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ + // TODO (ronag): Should this.destroy(err) emit + // 'error' on the wrapped stream? Would require + // a static factory method, e.g. Readable.wrap(stream). -function charset (type) { - if (!type || typeof type !== 'string') { - return false + stream.on('data', (chunk) => { + if (!this.push(chunk) && stream.pause) { + paused = true + stream.pause() + } + }) + stream.on('end', () => { + this.push(null) + }) + stream.on('error', (err) => { + errorOrDestroy(this, err) + }) + stream.on('close', () => { + this.destroy() + }) + stream.on('destroy', () => { + this.destroy() + }) + this._read = () => { + if (paused && stream.resume) { + paused = false + stream.resume() + } } - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - var mime = match && db[match[1].toLowerCase()] - - if (mime && mime.charset) { - return mime.charset + // Proxy all the other methods. Important when wrapping filters and duplexes. + const streamKeys = ObjectKeys(stream) + for (let j = 1; j < streamKeys.length; j++) { + const i = streamKeys[j] + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = stream[i].bind(stream) + } } - - // default text/* to utf-8 - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return 'UTF-8' + return this +} +Readable.prototype[SymbolAsyncIterator] = function () { + return streamToAsyncIterator(this) +} +Readable.prototype.iterator = function (options) { + if (options !== undefined) { + validateObject(options, 'options') + } + return streamToAsyncIterator(this, options) +} +function streamToAsyncIterator(stream, options) { + if (typeof stream.read !== 'function') { + stream = Readable.wrap(stream, { + objectMode: true + }) + } + const iter = createAsyncIterator(stream, options) + iter.stream = stream + return iter +} +async function* createAsyncIterator(stream, options) { + let callback = nop + function next(resolve) { + if (this === stream) { + callback() + callback = nop + } else { + callback = resolve + } + } + stream.on('readable', next) + let error + const cleanup = eos( + stream, + { + writable: false + }, + (err) => { + error = err ? aggregateTwoErrors(error, err) : null + callback() + callback = nop + } + ) + try { + while (true) { + const chunk = stream.destroyed ? null : stream.read() + if (chunk !== null) { + yield chunk + } else if (error) { + throw error + } else if (error === null) { + return + } else { + await new Promise(next) + } + } + } catch (err) { + error = aggregateTwoErrors(error, err) + throw error + } finally { + if ( + (error || (options === null || options === undefined ? undefined : options.destroyOnReturn) !== false) && + (error === undefined || stream._readableState.autoDestroy) + ) { + destroyImpl.destroyer(stream, null) + } else { + stream.off('readable', next) + cleanup() + } } - - return false } -/** - * Create a full Content-Type header given a MIME type or extension. - * - * @param {string} str - * @return {boolean|string} - */ +// Making it explicit these properties are not enumerable +// because otherwise some prototype manipulation in +// userland will fail. +ObjectDefineProperties(Readable.prototype, { + readable: { + __proto__: null, + get() { + const r = this._readableState + // r.readable === false means that this is part of a Duplex stream + // where the readable side was disabled upon construction. + // Compat. The user might manually disable readable side through + // deprecated setter. + return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted + }, + set(val) { + // Backwards compat. + if (this._readableState) { + this._readableState.readable = !!val + } + } + }, + readableDidRead: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState.dataEmitted + } + }, + readableAborted: { + __proto__: null, + enumerable: false, + get: function () { + return !!( + this._readableState.readable !== false && + (this._readableState.destroyed || this._readableState.errored) && + !this._readableState.endEmitted + ) + } + }, + readableHighWaterMark: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState.highWaterMark + } + }, + readableBuffer: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState && this._readableState.buffer + } + }, + readableFlowing: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState.flowing + }, + set: function (state) { + if (this._readableState) { + this._readableState.flowing = state + } + } + }, + readableLength: { + __proto__: null, + enumerable: false, + get() { + return this._readableState.length + } + }, + readableObjectMode: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.objectMode : false + } + }, + readableEncoding: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.encoding : null + } + }, + errored: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.errored : null + } + }, + closed: { + __proto__: null, + get() { + return this._readableState ? this._readableState.closed : false + } + }, + destroyed: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.destroyed : false + }, + set(value) { + // We ignore the value if the stream + // has not been initialized yet. + if (!this._readableState) { + return + } -function contentType (str) { - // TODO: should this even be in this module? - if (!str || typeof str !== 'string') { - return false + // Backward compatibility, the user is explicitly + // managing destroyed. + this._readableState.destroyed = value + } + }, + readableEnded: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.endEmitted : false + } + } +}) +ObjectDefineProperties(ReadableState.prototype, { + // Legacy getter for `pipesCount`. + pipesCount: { + __proto__: null, + get() { + return this.pipes.length + } + }, + // Legacy property for `paused`. + paused: { + __proto__: null, + get() { + return this[kPaused] !== false + }, + set(value) { + this[kPaused] = !!value + } } +}) - var mime = str.indexOf('/') === -1 - ? exports.lookup(str) - : str +// Exposed for testing purposes only. +Readable._fromList = fromList - if (!mime) { - return false +// Pluck off n bytes from an array of buffers. +// Length is the combined lengths of all the buffers in the list. +// This function is designed to be inlinable, so please take care when making +// changes to the function body. +function fromList(n, state) { + // nothing buffered. + if (state.length === 0) return null + let ret + if (state.objectMode) ret = state.buffer.shift() + else if (!n || n >= state.length) { + // Read it all, truncate the list. + if (state.decoder) ret = state.buffer.join('') + else if (state.buffer.length === 1) ret = state.buffer.first() + else ret = state.buffer.concat(state.length) + state.buffer.clear() + } else { + // read part of list. + ret = state.buffer.consume(n, state.decoder) + } + return ret +} +function endReadable(stream) { + const state = stream._readableState + debug('endReadable', state.endEmitted) + if (!state.endEmitted) { + state.ended = true + process.nextTick(endReadableNT, state, stream) } +} +function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length) - // TODO: use content-type or other module - if (mime.indexOf('charset') === -1) { - var charset = exports.charset(mime) - if (charset) mime += '; charset=' + charset.toLowerCase() + // Check that we didn't get one last unshift. + if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) { + state.endEmitted = true + stream.emit('end') + if (stream.writable && stream.allowHalfOpen === false) { + process.nextTick(endWritableNT, stream) + } else if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well. + const wState = stream._writableState + const autoDestroy = + !wState || + (wState.autoDestroy && + // We don't expect the writable to ever 'finish' + // if writable is explicitly set to false. + (wState.finished || wState.writable === false)) + if (autoDestroy) { + stream.destroy() + } + } + } +} +function endWritableNT(stream) { + const writable = stream.writable && !stream.writableEnded && !stream.destroyed + if (writable) { + stream.end() } +} +Readable.from = function (iterable, opts) { + return from(Readable, iterable, opts) +} +let webStreamsAdapters - return mime +// Lazy to avoid circular references +function lazyWebStreams() { + if (webStreamsAdapters === undefined) webStreamsAdapters = {} + return webStreamsAdapters +} +Readable.fromWeb = function (readableStream, options) { + return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options) +} +Readable.toWeb = function (streamReadable, options) { + return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options) +} +Readable.wrap = function (src, options) { + var _ref, _src$readableObjectMo + return new Readable({ + objectMode: + (_ref = + (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== undefined + ? _src$readableObjectMo + : src.objectMode) !== null && _ref !== undefined + ? _ref + : true, + ...options, + destroy(err, callback) { + destroyImpl.destroyer(src, err) + callback(err) + } + }).wrap(src) } -/** - * Get the default extension for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ -function extension (type) { - if (!type || typeof type !== 'string') { - return false - } +/***/ }), - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) +/***/ 39948: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // get extensions - var exts = match && exports.extensions[match[1].toLowerCase()] +"use strict"; - if (!exts || !exts.length) { - return false - } - return exts[0] +const { MathFloor, NumberIsInteger } = __nccwpck_require__(89629) +const { validateInteger } = __nccwpck_require__(669) +const { ERR_INVALID_ARG_VALUE } = (__nccwpck_require__(80529).codes) +let defaultHighWaterMarkBytes = 16 * 1024 +let defaultHighWaterMarkObjectMode = 16 +function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null } - -/** - * Lookup the MIME type for a file path/extension. - * - * @param {string} path - * @return {boolean|string} - */ - -function lookup (path) { - if (!path || typeof path !== 'string') { - return false +function getDefaultHighWaterMark(objectMode) { + return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes +} +function setDefaultHighWaterMark(objectMode, value) { + validateInteger(value, 'value', 0) + if (objectMode) { + defaultHighWaterMarkObjectMode = value + } else { + defaultHighWaterMarkBytes = value } - - // get the extension ("ext" or ".ext" or full path) - var extension = extname('x.' + path) - .toLowerCase() - .substr(1) - - if (!extension) { - return false +} +function getHighWaterMark(state, options, duplexKey, isDuplex) { + const hwm = highWaterMarkFrom(options, isDuplex, duplexKey) + if (hwm != null) { + if (!NumberIsInteger(hwm) || hwm < 0) { + const name = isDuplex ? `options.${duplexKey}` : 'options.highWaterMark' + throw new ERR_INVALID_ARG_VALUE(name, hwm) + } + return MathFloor(hwm) } - return exports.types[extension] || false + // Default value + return getDefaultHighWaterMark(state.objectMode) +} +module.exports = { + getHighWaterMark, + getDefaultHighWaterMark, + setDefaultHighWaterMark } -/** - * Populate the extensions and types maps. - * @private - */ -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana'] +/***/ }), - Object.keys(db).forEach(function forEachMimeType (type) { - var mime = db[type] - var exts = mime.extensions +/***/ 86941: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!exts || !exts.length) { - return - } +"use strict"; +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - // mime -> extensions - extensions[type] = exts +// a transform stream is a readable/writable stream where you do +// something with the data. Sometimes it's called a "filter", +// but that's not a great name for it, since that implies a thing where +// some bits pass through, and others are simply ignored. (That would +// be a valid example of a transform, of course.) +// +// While the output is causally related to the input, it's not a +// necessarily symmetric or synchronous transformation. For example, +// a zlib stream might take multiple plain-text writes(), and then +// emit a single compressed chunk some time in the future. +// +// Here's how this works: +// +// The Transform stream has all the aspects of the readable and writable +// stream classes. When you write(chunk), that calls _write(chunk,cb) +// internally, and returns false if there's a lot of pending writes +// buffered up. When you call read(), that calls _read(n) until +// there's enough pending readable data buffered up. +// +// In a transform stream, the written data is placed in a buffer. When +// _read(n) is called, it transforms the queued up data, calling the +// buffered _write cb's as it consumes chunks. If consuming a single +// written chunk would result in multiple output chunks, then the first +// outputted bit calls the readcb, and subsequent chunks just go into +// the read buffer, and will cause it to emit 'readable' if necessary. +// +// This way, back-pressure is actually determined by the reading side, +// since _read has to be called to start processing a new chunk. However, +// a pathological inflate type of transform can cause excessive buffering +// here. For example, imagine a stream where every byte of input is +// interpreted as an integer from 0-255, and then results in that many +// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in +// 1kb of data being output. In this case, you could write a very small +// amount of input, and end up with a very large amount of output. In +// such a pathological inflating mechanism, there'd be no way to tell +// the system to stop doing the transform. A single 4MB write could +// cause the system to run out of memory. +// +// However, even in such a pathological case, only a single written chunk +// would be consumed, and then the rest would wait (un-transformed) until +// the results of the previous transformed chunk were consumed. - // extension -> mime - for (var i = 0; i < exts.length; i++) { - var extension = exts[i] - if (types[extension]) { - var from = preference.indexOf(db[types[extension]].source) - var to = preference.indexOf(mime.source) - if (types[extension] !== 'application/octet-stream' && - (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { - // skip the remapping - continue +const { ObjectSetPrototypeOf, Symbol } = __nccwpck_require__(89629) +module.exports = Transform +const { ERR_METHOD_NOT_IMPLEMENTED } = (__nccwpck_require__(80529).codes) +const Duplex = __nccwpck_require__(72613) +const { getHighWaterMark } = __nccwpck_require__(39948) +ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype) +ObjectSetPrototypeOf(Transform, Duplex) +const kCallback = Symbol('kCallback') +function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options) + + // TODO (ronag): This should preferably always be + // applied but would be semver-major. Or even better; + // make Transform a Readable with the Writable interface. + const readableHighWaterMark = options ? getHighWaterMark(this, options, 'readableHighWaterMark', true) : null + if (readableHighWaterMark === 0) { + // A Duplex will buffer both on the writable and readable side while + // a Transform just wants to buffer hwm number of elements. To avoid + // buffering twice we disable buffering on the writable side. + options = { + ...options, + highWaterMark: null, + readableHighWaterMark, + // TODO (ronag): 0 is not optimal since we have + // a "bug" where we check needDrain before calling _write and not after. + // Refs: https://github.com/nodejs/node/pull/32887 + // Refs: https://github.com/nodejs/node/pull/35941 + writableHighWaterMark: options.writableHighWaterMark || 0 + } + } + Duplex.call(this, options) + + // We have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false + this[kCallback] = null + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform + if (typeof options.flush === 'function') this._flush = options.flush + } + + // When the writable side finishes, then flush out anything remaining. + // Backwards compat. Some Transform streams incorrectly implement _final + // instead of or in addition to _flush. By using 'prefinish' instead of + // implementing _final we continue supporting this unfortunate use case. + this.on('prefinish', prefinish) +} +function final(cb) { + if (typeof this._flush === 'function' && !this.destroyed) { + this._flush((er, data) => { + if (er) { + if (cb) { + cb(er) + } else { + this.destroy(er) } + return } - - // set the extension -> mime - types[extension] = type + if (data != null) { + this.push(data) + } + this.push(null) + if (cb) { + cb() + } + }) + } else { + this.push(null) + if (cb) { + cb() + } + } +} +function prefinish() { + if (this._final !== final) { + final.call(this) + } +} +Transform.prototype._final = final +Transform.prototype._transform = function (chunk, encoding, callback) { + throw new ERR_METHOD_NOT_IMPLEMENTED('_transform()') +} +Transform.prototype._write = function (chunk, encoding, callback) { + const rState = this._readableState + const wState = this._writableState + const length = rState.length + this._transform(chunk, encoding, (err, val) => { + if (err) { + callback(err) + return + } + if (val != null) { + this.push(val) + } + if ( + wState.ended || + // Backwards compat. + length === rState.length || + // Backwards compat. + rState.length < rState.highWaterMark + ) { + callback() + } else { + this[kCallback] = callback } }) } +Transform.prototype._read = function () { + if (this[kCallback]) { + const callback = this[kCallback] + this[kCallback] = null + callback() + } +} /***/ }), -/***/ 66186: +/***/ 27981: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var path = __nccwpck_require__(71017); -var fs = __nccwpck_require__(57147); -var _0777 = parseInt('0777', 8); +"use strict"; -module.exports = mkdirP.mkdirp = mkdirP.mkdirP = mkdirP; -function mkdirP (p, opts, f, made) { - if (typeof opts === 'function') { - f = opts; - opts = {}; - } - else if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 - } - if (!made) made = null; - - var cb = f || /* istanbul ignore next */ function () {}; - p = path.resolve(p); - - xfs.mkdir(p, mode, function (er) { - if (!er) { - made = made || p; - return cb(null, made); - } - switch (er.code) { - case 'ENOENT': - /* istanbul ignore if */ - if (path.dirname(p) === p) return cb(er); - mkdirP(path.dirname(p), opts, function (er, made) { - /* istanbul ignore if */ - if (er) cb(er, made); - else mkdirP(p, opts, cb, made); - }); - break; - - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - xfs.stat(p, function (er2, stat) { - // if the stat fails, then that's super weird. - // let the original error be the failure reason. - if (er2 || !stat.isDirectory()) cb(er, made) - else cb(null, made); - }); - break; - } - }); +const { SymbolAsyncIterator, SymbolIterator, SymbolFor } = __nccwpck_require__(89629) + +// We need to use SymbolFor to make these globally available +// for interopt with readable-stream, i.e. readable-stream +// and node core needs to be able to read/write private state +// from each other for proper interoperability. +const kIsDestroyed = SymbolFor('nodejs.stream.destroyed') +const kIsErrored = SymbolFor('nodejs.stream.errored') +const kIsReadable = SymbolFor('nodejs.stream.readable') +const kIsWritable = SymbolFor('nodejs.stream.writable') +const kIsDisturbed = SymbolFor('nodejs.stream.disturbed') +const kIsClosedPromise = SymbolFor('nodejs.webstream.isClosedPromise') +const kControllerErrorFunction = SymbolFor('nodejs.webstream.controllerErrorFunction') +function isReadableNodeStream(obj, strict = false) { + var _obj$_readableState + return !!( + ( + obj && + typeof obj.pipe === 'function' && + typeof obj.on === 'function' && + (!strict || (typeof obj.pause === 'function' && typeof obj.resume === 'function')) && + (!obj._writableState || + ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === undefined + ? undefined + : _obj$_readableState.readable) !== false) && + // Duplex + (!obj._writableState || obj._readableState) + ) // Writable has .pipe. + ) } -mkdirP.sync = function sync (p, opts, made) { - if (!opts || typeof opts !== 'object') { - opts = { mode: opts }; - } - - var mode = opts.mode; - var xfs = opts.fs || fs; - - if (mode === undefined) { - mode = _0777 - } - if (!made) made = null; +function isWritableNodeStream(obj) { + var _obj$_writableState + return !!( + ( + obj && + typeof obj.write === 'function' && + typeof obj.on === 'function' && + (!obj._readableState || + ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === undefined + ? undefined + : _obj$_writableState.writable) !== false) + ) // Duplex + ) +} - p = path.resolve(p); +function isDuplexNodeStream(obj) { + return !!( + obj && + typeof obj.pipe === 'function' && + obj._readableState && + typeof obj.on === 'function' && + typeof obj.write === 'function' + ) +} +function isNodeStream(obj) { + return ( + obj && + (obj._readableState || + obj._writableState || + (typeof obj.write === 'function' && typeof obj.on === 'function') || + (typeof obj.pipe === 'function' && typeof obj.on === 'function')) + ) +} +function isReadableStream(obj) { + return !!( + obj && + !isNodeStream(obj) && + typeof obj.pipeThrough === 'function' && + typeof obj.getReader === 'function' && + typeof obj.cancel === 'function' + ) +} +function isWritableStream(obj) { + return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === 'function' && typeof obj.abort === 'function') +} +function isTransformStream(obj) { + return !!(obj && !isNodeStream(obj) && typeof obj.readable === 'object' && typeof obj.writable === 'object') +} +function isWebStream(obj) { + return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj) +} +function isIterable(obj, isAsync) { + if (obj == null) return false + if (isAsync === true) return typeof obj[SymbolAsyncIterator] === 'function' + if (isAsync === false) return typeof obj[SymbolIterator] === 'function' + return typeof obj[SymbolAsyncIterator] === 'function' || typeof obj[SymbolIterator] === 'function' +} +function isDestroyed(stream) { + if (!isNodeStream(stream)) return null + const wState = stream._writableState + const rState = stream._readableState + const state = wState || rState + return !!(stream.destroyed || stream[kIsDestroyed] || (state !== null && state !== undefined && state.destroyed)) +} + +// Have been end():d. +function isWritableEnded(stream) { + if (!isWritableNodeStream(stream)) return null + if (stream.writableEnded === true) return true + const wState = stream._writableState + if (wState !== null && wState !== undefined && wState.errored) return false + if (typeof (wState === null || wState === undefined ? undefined : wState.ended) !== 'boolean') return null + return wState.ended +} + +// Have emitted 'finish'. +function isWritableFinished(stream, strict) { + if (!isWritableNodeStream(stream)) return null + if (stream.writableFinished === true) return true + const wState = stream._writableState + if (wState !== null && wState !== undefined && wState.errored) return false + if (typeof (wState === null || wState === undefined ? undefined : wState.finished) !== 'boolean') return null + return !!(wState.finished || (strict === false && wState.ended === true && wState.length === 0)) +} + +// Have been push(null):d. +function isReadableEnded(stream) { + if (!isReadableNodeStream(stream)) return null + if (stream.readableEnded === true) return true + const rState = stream._readableState + if (!rState || rState.errored) return false + if (typeof (rState === null || rState === undefined ? undefined : rState.ended) !== 'boolean') return null + return rState.ended +} + +// Have emitted 'end'. +function isReadableFinished(stream, strict) { + if (!isReadableNodeStream(stream)) return null + const rState = stream._readableState + if (rState !== null && rState !== undefined && rState.errored) return false + if (typeof (rState === null || rState === undefined ? undefined : rState.endEmitted) !== 'boolean') return null + return !!(rState.endEmitted || (strict === false && rState.ended === true && rState.length === 0)) +} +function isReadable(stream) { + if (stream && stream[kIsReadable] != null) return stream[kIsReadable] + if (typeof (stream === null || stream === undefined ? undefined : stream.readable) !== 'boolean') return null + if (isDestroyed(stream)) return false + return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream) +} +function isWritable(stream) { + if (stream && stream[kIsWritable] != null) return stream[kIsWritable] + if (typeof (stream === null || stream === undefined ? undefined : stream.writable) !== 'boolean') return null + if (isDestroyed(stream)) return false + return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream) +} +function isFinished(stream, opts) { + if (!isNodeStream(stream)) { + return null + } + if (isDestroyed(stream)) { + return true + } + if ((opts === null || opts === undefined ? undefined : opts.readable) !== false && isReadable(stream)) { + return false + } + if ((opts === null || opts === undefined ? undefined : opts.writable) !== false && isWritable(stream)) { + return false + } + return true +} +function isWritableErrored(stream) { + var _stream$_writableStat, _stream$_writableStat2 + if (!isNodeStream(stream)) { + return null + } + if (stream.writableErrored) { + return stream.writableErrored + } + return (_stream$_writableStat = + (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === undefined + ? undefined + : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== undefined + ? _stream$_writableStat + : null +} +function isReadableErrored(stream) { + var _stream$_readableStat, _stream$_readableStat2 + if (!isNodeStream(stream)) { + return null + } + if (stream.readableErrored) { + return stream.readableErrored + } + return (_stream$_readableStat = + (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === undefined + ? undefined + : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== undefined + ? _stream$_readableStat + : null +} +function isClosed(stream) { + if (!isNodeStream(stream)) { + return null + } + if (typeof stream.closed === 'boolean') { + return stream.closed + } + const wState = stream._writableState + const rState = stream._readableState + if ( + typeof (wState === null || wState === undefined ? undefined : wState.closed) === 'boolean' || + typeof (rState === null || rState === undefined ? undefined : rState.closed) === 'boolean' + ) { + return ( + (wState === null || wState === undefined ? undefined : wState.closed) || + (rState === null || rState === undefined ? undefined : rState.closed) + ) + } + if (typeof stream._closed === 'boolean' && isOutgoingMessage(stream)) { + return stream._closed + } + return null +} +function isOutgoingMessage(stream) { + return ( + typeof stream._closed === 'boolean' && + typeof stream._defaultKeepAlive === 'boolean' && + typeof stream._removedConnection === 'boolean' && + typeof stream._removedContLen === 'boolean' + ) +} +function isServerResponse(stream) { + return typeof stream._sent100 === 'boolean' && isOutgoingMessage(stream) +} +function isServerRequest(stream) { + var _stream$req + return ( + typeof stream._consuming === 'boolean' && + typeof stream._dumped === 'boolean' && + ((_stream$req = stream.req) === null || _stream$req === undefined ? undefined : _stream$req.upgradeOrConnect) === + undefined + ) +} +function willEmitClose(stream) { + if (!isNodeStream(stream)) return null + const wState = stream._writableState + const rState = stream._readableState + const state = wState || rState + return ( + (!state && isServerResponse(stream)) || !!(state && state.autoDestroy && state.emitClose && state.closed === false) + ) +} +function isDisturbed(stream) { + var _stream$kIsDisturbed + return !!( + stream && + ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== undefined + ? _stream$kIsDisturbed + : stream.readableDidRead || stream.readableAborted) + ) +} +function isErrored(stream) { + var _ref, + _ref2, + _ref3, + _ref4, + _ref5, + _stream$kIsErrored, + _stream$_readableStat3, + _stream$_writableStat3, + _stream$_readableStat4, + _stream$_writableStat4 + return !!( + stream && + ((_ref = + (_ref2 = + (_ref3 = + (_ref4 = + (_ref5 = + (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== undefined + ? _stream$kIsErrored + : stream.readableErrored) !== null && _ref5 !== undefined + ? _ref5 + : stream.writableErrored) !== null && _ref4 !== undefined + ? _ref4 + : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === undefined + ? undefined + : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== undefined + ? _ref3 + : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === undefined + ? undefined + : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== undefined + ? _ref2 + : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === undefined + ? undefined + : _stream$_readableStat4.errored) !== null && _ref !== undefined + ? _ref + : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === undefined + ? undefined + : _stream$_writableStat4.errored) + ) +} +module.exports = { + isDestroyed, + kIsDestroyed, + isDisturbed, + kIsDisturbed, + isErrored, + kIsErrored, + isReadable, + kIsReadable, + kIsClosedPromise, + kControllerErrorFunction, + kIsWritable, + isClosed, + isDuplexNodeStream, + isFinished, + isIterable, + isReadableNodeStream, + isReadableStream, + isReadableEnded, + isReadableFinished, + isReadableErrored, + isNodeStream, + isWebStream, + isWritable, + isWritableNodeStream, + isWritableStream, + isWritableEnded, + isWritableFinished, + isWritableErrored, + isServerRequest, + isServerResponse, + willEmitClose, + isTransformStream +} - try { - xfs.mkdirSync(p, mode); - made = made || p; - } - catch (err0) { - switch (err0.code) { - case 'ENOENT' : - made = sync(path.dirname(p), opts, made); - sync(p, opts, made); - break; - // In the case of any other error, just see if there's a dir - // there already. If so, then hooray! If not, then something - // is borked. - default: - var stat; - try { - stat = xfs.statSync(p); - } - catch (err1) /* istanbul ignore next */ { - throw err0; - } - /* istanbul ignore if */ - if (!stat.isDirectory()) throw err0; - break; - } - } +/***/ }), - return made; -}; +/***/ 48488: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/* replacement start */ -/***/ }), +const process = __nccwpck_require__(45676) -/***/ 80467: -/***/ ((module, exports, __nccwpck_require__) => { +/* replacement end */ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. -"use strict"; +// A bit simpler than readable streams. +// Implement an async ._write(chunk, encoding, cb), and it'll handle all +// the drain event emission and buffering. +;('use strict') +const { + ArrayPrototypeSlice, + Error, + FunctionPrototypeSymbolHasInstance, + ObjectDefineProperty, + ObjectDefineProperties, + ObjectSetPrototypeOf, + StringPrototypeToLowerCase, + Symbol, + SymbolHasInstance +} = __nccwpck_require__(89629) +module.exports = Writable +Writable.WritableState = WritableState +const { EventEmitter: EE } = __nccwpck_require__(82361) +const Stream = (__nccwpck_require__(49792).Stream) +const { Buffer } = __nccwpck_require__(14300) +const destroyImpl = __nccwpck_require__(97049) +const { addAbortSignal } = __nccwpck_require__(80289) +const { getHighWaterMark, getDefaultHighWaterMark } = __nccwpck_require__(39948) +const { + ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED, + ERR_STREAM_ALREADY_FINISHED, + ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING +} = (__nccwpck_require__(80529).codes) +const { errorOrDestroy } = destroyImpl +ObjectSetPrototypeOf(Writable.prototype, Stream.prototype) +ObjectSetPrototypeOf(Writable, Stream) +function nop() {} +const kOnFinished = Symbol('kOnFinished') +function WritableState(options, stream, isDuplex) { + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof __nccwpck_require__(72613) -Object.defineProperty(exports, "__esModule", ({ value: true })); + // Object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!(options && options.objectMode) + if (isDuplex) this.objectMode = this.objectMode || !!(options && options.writableObjectMode) -function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + // The point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write(). + this.highWaterMark = options + ? getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex) + : getDefaultHighWaterMark(false) -var Stream = _interopDefault(__nccwpck_require__(12781)); -var http = _interopDefault(__nccwpck_require__(13685)); -var Url = _interopDefault(__nccwpck_require__(57310)); -var whatwgUrl = _interopDefault(__nccwpck_require__(28665)); -var https = _interopDefault(__nccwpck_require__(95687)); -var zlib = _interopDefault(__nccwpck_require__(59796)); + // if _final has been called. + this.finalCalled = false -// Based on https://github.com/tmpvar/jsdom/blob/aa85b2abf07766ff7bf5c1f6daafb3726f2f2db5/lib/jsdom/living/blob.js + // drain event flag. + this.needDrain = false + // At the start of calling end() + this.ending = false + // When end() has been called, and returned. + this.ended = false + // When 'finish' is emitted. + this.finished = false -// fix for "Readable" isn't a named export issue -const Readable = Stream.Readable; + // Has it been destroyed + this.destroyed = false -const BUFFER = Symbol('buffer'); -const TYPE = Symbol('type'); + // Should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + const noDecode = !!(options && options.decodeStrings === false) + this.decodeStrings = !noDecode -class Blob { - constructor() { - this[TYPE] = ''; + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = (options && options.defaultEncoding) || 'utf8' - const blobParts = arguments[0]; - const options = arguments[1]; + // Not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0 - const buffers = []; - let size = 0; + // A flag to see when we're in the middle of a write. + this.writing = false - if (blobParts) { - const a = blobParts; - const length = Number(a.length); - for (let i = 0; i < length; i++) { - const element = a[i]; - let buffer; - if (element instanceof Buffer) { - buffer = element; - } else if (ArrayBuffer.isView(element)) { - buffer = Buffer.from(element.buffer, element.byteOffset, element.byteLength); - } else if (element instanceof ArrayBuffer) { - buffer = Buffer.from(element); - } else if (element instanceof Blob) { - buffer = element[BUFFER]; - } else { - buffer = Buffer.from(typeof element === 'string' ? element : String(element)); - } - size += buffer.length; - buffers.push(buffer); - } - } + // When true all writes will be buffered until .uncork() call. + this.corked = 0 - this[BUFFER] = Buffer.concat(buffers); + // A flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true - let type = options && options.type !== undefined && String(options.type).toLowerCase(); - if (type && !/[^\u0020-\u007E]/.test(type)) { - this[TYPE] = type; - } - } - get size() { - return this[BUFFER].length; - } - get type() { - return this[TYPE]; - } - text() { - return Promise.resolve(this[BUFFER].toString()); - } - arrayBuffer() { - const buf = this[BUFFER]; - const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - return Promise.resolve(ab); - } - stream() { - const readable = new Readable(); - readable._read = function () {}; - readable.push(this[BUFFER]); - readable.push(null); - return readable; - } - toString() { - return '[object Blob]'; - } - slice() { - const size = this.size; + // A flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false - const start = arguments[0]; - const end = arguments[1]; - let relativeStart, relativeEnd; - if (start === undefined) { - relativeStart = 0; - } else if (start < 0) { - relativeStart = Math.max(size + start, 0); - } else { - relativeStart = Math.min(start, size); - } - if (end === undefined) { - relativeEnd = size; - } else if (end < 0) { - relativeEnd = Math.max(size + end, 0); - } else { - relativeEnd = Math.min(end, size); - } - const span = Math.max(relativeEnd - relativeStart, 0); + // The callback that's passed to _write(chunk, cb). + this.onwrite = onwrite.bind(undefined, stream) - const buffer = this[BUFFER]; - const slicedBuffer = buffer.slice(relativeStart, relativeStart + span); - const blob = new Blob([], { type: arguments[2] }); - blob[BUFFER] = slicedBuffer; - return blob; - } -} + // The callback that the user supplies to write(chunk, encoding, cb). + this.writecb = null -Object.defineProperties(Blob.prototype, { - size: { enumerable: true }, - type: { enumerable: true }, - slice: { enumerable: true } -}); + // The amount that is being written when _write is called. + this.writelen = 0 -Object.defineProperty(Blob.prototype, Symbol.toStringTag, { - value: 'Blob', - writable: false, - enumerable: false, - configurable: true -}); + // Storage for data passed to the afterWrite() callback in case of + // synchronous _write() completion. + this.afterWriteTickInfo = null + resetBuffer(this) -/** - * fetch-error.js - * - * FetchError interface for operational errors - */ + // Number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted. + this.pendingcb = 0 -/** - * Create FetchError instance - * - * @param String message Error message for human - * @param String type Error type for machine - * @param String systemError For Node.js system error - * @return FetchError - */ -function FetchError(message, type, systemError) { - Error.call(this, message); + // Stream is still being constructed and cannot be + // destroyed until construction finished or failed. + // Async construction is opt in, therefore we start as + // constructed. + this.constructed = true - this.message = message; - this.type = type; + // Emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams. + this.prefinished = false - // when err.type is `system`, err.code contains system error code - if (systemError) { - this.code = this.errno = systemError.code; - } + // True if the error was already emitted and should not be thrown again. + this.errorEmitted = false - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); -} + // Should close be emitted on destroy. Defaults to true. + this.emitClose = !options || options.emitClose !== false -FetchError.prototype = Object.create(Error.prototype); -FetchError.prototype.constructor = FetchError; -FetchError.prototype.name = 'FetchError'; + // Should .destroy() be called after 'finish' (and potentially 'end'). + this.autoDestroy = !options || options.autoDestroy !== false -let convert; -try { - convert = (__nccwpck_require__(22877).convert); -} catch (e) {} + // Indicates whether the stream has errored. When true all write() calls + // should return false. This is needed since when autoDestroy + // is disabled we need a way to tell whether the stream has failed. + this.errored = null -const INTERNALS = Symbol('Body internals'); + // Indicates whether the stream has finished destroying. + this.closed = false -// fix an issue where "PassThrough" isn't a named export for node <10 -const PassThrough = Stream.PassThrough; + // True if close has been emitted or would have been emitted + // depending on emitClose. + this.closeEmitted = false + this[kOnFinished] = [] +} +function resetBuffer(state) { + state.buffered = [] + state.bufferedIndex = 0 + state.allBuffers = true + state.allNoop = true +} +WritableState.prototype.getBuffer = function getBuffer() { + return ArrayPrototypeSlice(this.buffered, this.bufferedIndex) +} +ObjectDefineProperty(WritableState.prototype, 'bufferedRequestCount', { + __proto__: null, + get() { + return this.buffered.length - this.bufferedIndex + } +}) +function Writable(options) { + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. -/** - * Body mixin - * - * Ref: https://fetch.spec.whatwg.org/#body - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -function Body(body) { - var _this = this; + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. - var _ref = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}, - _ref$size = _ref.size; + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5. + const isDuplex = this instanceof __nccwpck_require__(72613) + if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) return new Writable(options) + this._writableState = new WritableState(options, this, isDuplex) + if (options) { + if (typeof options.write === 'function') this._write = options.write + if (typeof options.writev === 'function') this._writev = options.writev + if (typeof options.destroy === 'function') this._destroy = options.destroy + if (typeof options.final === 'function') this._final = options.final + if (typeof options.construct === 'function') this._construct = options.construct + if (options.signal) addAbortSignal(options.signal, this) + } + Stream.call(this, options) + destroyImpl.construct(this, () => { + const state = this._writableState + if (!state.writing) { + clearBuffer(this, state) + } + finishMaybe(this, state) + }) +} +ObjectDefineProperty(Writable, SymbolHasInstance, { + __proto__: null, + value: function (object) { + if (FunctionPrototypeSymbolHasInstance(this, object)) return true + if (this !== Writable) return false + return object && object._writableState instanceof WritableState + } +}) - let size = _ref$size === undefined ? 0 : _ref$size; - var _ref$timeout = _ref.timeout; - let timeout = _ref$timeout === undefined ? 0 : _ref$timeout; +// Otherwise people can pipe Writable streams, which is just wrong. +Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()) +} +function _write(stream, chunk, encoding, cb) { + const state = stream._writableState + if (typeof encoding === 'function') { + cb = encoding + encoding = state.defaultEncoding + } else { + if (!encoding) encoding = state.defaultEncoding + else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding) + if (typeof cb !== 'function') cb = nop + } + if (chunk === null) { + throw new ERR_STREAM_NULL_VALUES() + } else if (!state.objectMode) { + if (typeof chunk === 'string') { + if (state.decodeStrings !== false) { + chunk = Buffer.from(chunk, encoding) + encoding = 'buffer' + } + } else if (chunk instanceof Buffer) { + encoding = 'buffer' + } else if (Stream._isUint8Array(chunk)) { + chunk = Stream._uint8ArrayToBuffer(chunk) + encoding = 'buffer' + } else { + throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk) + } + } + let err + if (state.ending) { + err = new ERR_STREAM_WRITE_AFTER_END() + } else if (state.destroyed) { + err = new ERR_STREAM_DESTROYED('write') + } + if (err) { + process.nextTick(cb, err) + errorOrDestroy(stream, err, true) + return err + } + state.pendingcb++ + return writeOrBuffer(stream, state, chunk, encoding, cb) +} +Writable.prototype.write = function (chunk, encoding, cb) { + return _write(this, chunk, encoding, cb) === true +} +Writable.prototype.cork = function () { + this._writableState.corked++ +} +Writable.prototype.uncork = function () { + const state = this._writableState + if (state.corked) { + state.corked-- + if (!state.writing) clearBuffer(this, state) + } +} +Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = StringPrototypeToLowerCase(encoding) + if (!Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding) + this._writableState.defaultEncoding = encoding + return this +} - if (body == null) { - // body is undefined or null - body = null; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - body = Buffer.from(body.toString()); - } else if (isBlob(body)) ; else if (Buffer.isBuffer(body)) ; else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - body = Buffer.from(body); - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - body = Buffer.from(body.buffer, body.byteOffset, body.byteLength); - } else if (body instanceof Stream) ; else { - // none of the above - // coerce to string then buffer - body = Buffer.from(String(body)); - } - this[INTERNALS] = { - body, - disturbed: false, - error: null - }; - this.size = size; - this.timeout = timeout; +// If we're already writing something, then just put this +// in the queue, and wait our turn. Otherwise, call _write +// If we return false, then we need a drain event, so set that flag. +function writeOrBuffer(stream, state, chunk, encoding, callback) { + const len = state.objectMode ? 1 : chunk.length + state.length += len + + // stream._write resets state.length + const ret = state.length < state.highWaterMark + // We must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true + if (state.writing || state.corked || state.errored || !state.constructed) { + state.buffered.push({ + chunk, + encoding, + callback + }) + if (state.allBuffers && encoding !== 'buffer') { + state.allBuffers = false + } + if (state.allNoop && callback !== nop) { + state.allNoop = false + } + } else { + state.writelen = len + state.writecb = callback + state.writing = true + state.sync = true + stream._write(chunk, encoding, state.onwrite) + state.sync = false + } - if (body instanceof Stream) { - body.on('error', function (err) { - const error = err.name === 'AbortError' ? err : new FetchError(`Invalid response body while trying to fetch ${_this.url}: ${err.message}`, 'system', err); - _this[INTERNALS].error = error; - }); - } + // Return false if errored or destroyed in order to break + // any synchronous while(stream.write(data)) loops. + return ret && !state.errored && !state.destroyed +} +function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len + state.writecb = cb + state.writing = true + state.sync = true + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write')) + else if (writev) stream._writev(chunk, state.onwrite) + else stream._write(chunk, encoding, state.onwrite) + state.sync = false +} +function onwriteError(stream, state, er, cb) { + --state.pendingcb + cb(er) + // Ensure callbacks are invoked even when autoDestroy is + // not enabled. Passing `er` here doesn't make sense since + // it's related to one specific write, not to the buffered + // writes. + errorBuffer(state) + // This can emit error, but error must always follow cb. + errorOrDestroy(stream, er) } +function onwrite(stream, er) { + const state = stream._writableState + const sync = state.sync + const cb = state.writecb + if (typeof cb !== 'function') { + errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK()) + return + } + state.writing = false + state.writecb = null + state.length -= state.writelen + state.writelen = 0 + if (er) { + // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 + er.stack // eslint-disable-line no-unused-expressions -Body.prototype = { - get body() { - return this[INTERNALS].body; - }, + if (!state.errored) { + state.errored = er + } - get bodyUsed() { - return this[INTERNALS].disturbed; - }, + // In case of duplex streams we need to notify the readable side of the + // error. + if (stream._readableState && !stream._readableState.errored) { + stream._readableState.errored = er + } + if (sync) { + process.nextTick(onwriteError, stream, state, er, cb) + } else { + onwriteError(stream, state, er, cb) + } + } else { + if (state.buffered.length > state.bufferedIndex) { + clearBuffer(stream, state) + } + if (sync) { + // It is a common case that the callback passed to .write() is always + // the same. In that case, we do not schedule a new nextTick(), but + // rather just increase a counter, to improve performance and avoid + // memory allocations. + if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) { + state.afterWriteTickInfo.count++ + } else { + state.afterWriteTickInfo = { + count: 1, + cb, + stream, + state + } + process.nextTick(afterWriteTick, state.afterWriteTickInfo) + } + } else { + afterWrite(stream, state, 1, cb) + } + } +} +function afterWriteTick({ stream, state, count, cb }) { + state.afterWriteTickInfo = null + return afterWrite(stream, state, count, cb) +} +function afterWrite(stream, state, count, cb) { + const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain + if (needDrain) { + state.needDrain = false + stream.emit('drain') + } + while (count-- > 0) { + state.pendingcb-- + cb() + } + if (state.destroyed) { + errorBuffer(state) + } + finishMaybe(stream, state) +} - /** - * Decode response as ArrayBuffer - * - * @return Promise - */ - arrayBuffer() { - return consumeBody.call(this).then(function (buf) { - return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength); - }); - }, +// If there's something in the buffer waiting, then invoke callbacks. +function errorBuffer(state) { + if (state.writing) { + return + } + for (let n = state.bufferedIndex; n < state.buffered.length; ++n) { + var _state$errored + const { chunk, callback } = state.buffered[n] + const len = state.objectMode ? 1 : chunk.length + state.length -= len + callback( + (_state$errored = state.errored) !== null && _state$errored !== undefined + ? _state$errored + : new ERR_STREAM_DESTROYED('write') + ) + } + const onfinishCallbacks = state[kOnFinished].splice(0) + for (let i = 0; i < onfinishCallbacks.length; i++) { + var _state$errored2 + onfinishCallbacks[i]( + (_state$errored2 = state.errored) !== null && _state$errored2 !== undefined + ? _state$errored2 + : new ERR_STREAM_DESTROYED('end') + ) + } + resetBuffer(state) +} - /** - * Return raw response as Blob - * - * @return Promise - */ - blob() { - let ct = this.headers && this.headers.get('content-type') || ''; - return consumeBody.call(this).then(function (buf) { - return Object.assign( - // Prevent copying - new Blob([], { - type: ct.toLowerCase() - }), { - [BUFFER]: buf - }); - }); - }, +// If there's something in the buffer waiting, then process it. +function clearBuffer(stream, state) { + if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) { + return + } + const { buffered, bufferedIndex, objectMode } = state + const bufferedLength = buffered.length - bufferedIndex + if (!bufferedLength) { + return + } + let i = bufferedIndex + state.bufferProcessing = true + if (bufferedLength > 1 && stream._writev) { + state.pendingcb -= bufferedLength - 1 + const callback = state.allNoop + ? nop + : (err) => { + for (let n = i; n < buffered.length; ++n) { + buffered[n].callback(err) + } + } + // Make a copy of `buffered` if it's going to be used by `callback` above, + // since `doWrite` will mutate the array. + const chunks = state.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i) + chunks.allBuffers = state.allBuffers + doWrite(stream, state, true, state.length, chunks, '', callback) + resetBuffer(state) + } else { + do { + const { chunk, encoding, callback } = buffered[i] + buffered[i++] = null + const len = objectMode ? 1 : chunk.length + doWrite(stream, state, false, len, chunk, encoding, callback) + } while (i < buffered.length && !state.writing) + if (i === buffered.length) { + resetBuffer(state) + } else if (i > 256) { + buffered.splice(0, i) + state.bufferedIndex = 0 + } else { + state.bufferedIndex = i + } + } + state.bufferProcessing = false +} +Writable.prototype._write = function (chunk, encoding, cb) { + if (this._writev) { + this._writev( + [ + { + chunk, + encoding + } + ], + cb + ) + } else { + throw new ERR_METHOD_NOT_IMPLEMENTED('_write()') + } +} +Writable.prototype._writev = null +Writable.prototype.end = function (chunk, encoding, cb) { + const state = this._writableState + if (typeof chunk === 'function') { + cb = chunk + chunk = null + encoding = null + } else if (typeof encoding === 'function') { + cb = encoding + encoding = null + } + let err + if (chunk !== null && chunk !== undefined) { + const ret = _write(this, chunk, encoding) + if (ret instanceof Error) { + err = ret + } + } - /** - * Decode response as json - * - * @return Promise - */ - json() { - var _this2 = this; + // .end() fully uncorks. + if (state.corked) { + state.corked = 1 + this.uncork() + } + if (err) { + // Do nothing... + } else if (!state.errored && !state.ending) { + // This is forgiving in terms of unnecessary calls to end() and can hide + // logic errors. However, usually such errors are harmless and causing a + // hard error can be disproportionately destructive. It is not always + // trivial for the user to determine whether end() needs to be called + // or not. + + state.ending = true + finishMaybe(this, state, true) + state.ended = true + } else if (state.finished) { + err = new ERR_STREAM_ALREADY_FINISHED('end') + } else if (state.destroyed) { + err = new ERR_STREAM_DESTROYED('end') + } + if (typeof cb === 'function') { + if (err || state.finished) { + process.nextTick(cb, err) + } else { + state[kOnFinished].push(cb) + } + } + return this +} +function needFinish(state) { + return ( + state.ending && + !state.destroyed && + state.constructed && + state.length === 0 && + !state.errored && + state.buffered.length === 0 && + !state.finished && + !state.writing && + !state.errorEmitted && + !state.closeEmitted + ) +} +function callFinal(stream, state) { + let called = false + function onFinish(err) { + if (called) { + errorOrDestroy(stream, err !== null && err !== undefined ? err : ERR_MULTIPLE_CALLBACK()) + return + } + called = true + state.pendingcb-- + if (err) { + const onfinishCallbacks = state[kOnFinished].splice(0) + for (let i = 0; i < onfinishCallbacks.length; i++) { + onfinishCallbacks[i](err) + } + errorOrDestroy(stream, err, state.sync) + } else if (needFinish(state)) { + state.prefinished = true + stream.emit('prefinish') + // Backwards compat. Don't check state.sync here. + // Some streams assume 'finish' will be emitted + // asynchronously relative to _final callback. + state.pendingcb++ + process.nextTick(finish, stream, state) + } + } + state.sync = true + state.pendingcb++ + try { + stream._final(onFinish) + } catch (err) { + onFinish(err) + } + state.sync = false +} +function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.finalCalled = true + callFinal(stream, state) + } else { + state.prefinished = true + stream.emit('prefinish') + } + } +} +function finishMaybe(stream, state, sync) { + if (needFinish(state)) { + prefinish(stream, state) + if (state.pendingcb === 0) { + if (sync) { + state.pendingcb++ + process.nextTick( + (stream, state) => { + if (needFinish(state)) { + finish(stream, state) + } else { + state.pendingcb-- + } + }, + stream, + state + ) + } else if (needFinish(state)) { + state.pendingcb++ + finish(stream, state) + } + } + } +} +function finish(stream, state) { + state.pendingcb-- + state.finished = true + const onfinishCallbacks = state[kOnFinished].splice(0) + for (let i = 0; i < onfinishCallbacks.length; i++) { + onfinishCallbacks[i]() + } + stream.emit('finish') + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well. + const rState = stream._readableState + const autoDestroy = + !rState || + (rState.autoDestroy && + // We don't expect the readable to ever 'end' + // if readable is explicitly set to false. + (rState.endEmitted || rState.readable === false)) + if (autoDestroy) { + stream.destroy() + } + } +} +ObjectDefineProperties(Writable.prototype, { + closed: { + __proto__: null, + get() { + return this._writableState ? this._writableState.closed : false + } + }, + destroyed: { + __proto__: null, + get() { + return this._writableState ? this._writableState.destroyed : false + }, + set(value) { + // Backward compatibility, the user is explicitly managing destroyed. + if (this._writableState) { + this._writableState.destroyed = value + } + } + }, + writable: { + __proto__: null, + get() { + const w = this._writableState + // w.writable === false means that this is part of a Duplex stream + // where the writable side was disabled upon construction. + // Compat. The user might manually disable writable side through + // deprecated setter. + return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended + }, + set(val) { + // Backwards compatible. + if (this._writableState) { + this._writableState.writable = !!val + } + } + }, + writableFinished: { + __proto__: null, + get() { + return this._writableState ? this._writableState.finished : false + } + }, + writableObjectMode: { + __proto__: null, + get() { + return this._writableState ? this._writableState.objectMode : false + } + }, + writableBuffer: { + __proto__: null, + get() { + return this._writableState && this._writableState.getBuffer() + } + }, + writableEnded: { + __proto__: null, + get() { + return this._writableState ? this._writableState.ending : false + } + }, + writableNeedDrain: { + __proto__: null, + get() { + const wState = this._writableState + if (!wState) return false + return !wState.destroyed && !wState.ending && wState.needDrain + } + }, + writableHighWaterMark: { + __proto__: null, + get() { + return this._writableState && this._writableState.highWaterMark + } + }, + writableCorked: { + __proto__: null, + get() { + return this._writableState ? this._writableState.corked : 0 + } + }, + writableLength: { + __proto__: null, + get() { + return this._writableState && this._writableState.length + } + }, + errored: { + __proto__: null, + enumerable: false, + get() { + return this._writableState ? this._writableState.errored : null + } + }, + writableAborted: { + __proto__: null, + enumerable: false, + get: function () { + return !!( + this._writableState.writable !== false && + (this._writableState.destroyed || this._writableState.errored) && + !this._writableState.finished + ) + } + } +}) +const destroy = destroyImpl.destroy +Writable.prototype.destroy = function (err, cb) { + const state = this._writableState - return consumeBody.call(this).then(function (buffer) { - try { - return JSON.parse(buffer.toString()); - } catch (err) { - return Body.Promise.reject(new FetchError(`invalid json response body at ${_this2.url} reason: ${err.message}`, 'invalid-json')); - } - }); - }, + // Invoke pending callbacks. + if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) { + process.nextTick(errorBuffer, state) + } + destroy.call(this, err, cb) + return this +} +Writable.prototype._undestroy = destroyImpl.undestroy +Writable.prototype._destroy = function (err, cb) { + cb(err) +} +Writable.prototype[EE.captureRejectionSymbol] = function (err) { + this.destroy(err) +} +let webStreamsAdapters - /** - * Decode response as text - * - * @return Promise - */ - text() { - return consumeBody.call(this).then(function (buffer) { - return buffer.toString(); - }); - }, +// Lazy to avoid circular references +function lazyWebStreams() { + if (webStreamsAdapters === undefined) webStreamsAdapters = {} + return webStreamsAdapters +} +Writable.fromWeb = function (writableStream, options) { + return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options) +} +Writable.toWeb = function (streamWritable) { + return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable) +} - /** - * Decode response as buffer (non-spec api) - * - * @return Promise - */ - buffer() { - return consumeBody.call(this); - }, - /** - * Decode response as text, while automatically detecting the encoding and - * trying to decode to UTF-8 (non-spec api) - * - * @return Promise - */ - textConverted() { - var _this3 = this; +/***/ }), - return consumeBody.call(this).then(function (buffer) { - return convertBody(buffer, _this3.headers); - }); - } -}; +/***/ 669: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// In browsers, all properties are enumerable. -Object.defineProperties(Body.prototype, { - body: { enumerable: true }, - bodyUsed: { enumerable: true }, - arrayBuffer: { enumerable: true }, - blob: { enumerable: true }, - json: { enumerable: true }, - text: { enumerable: true } -}); +"use strict"; +/* eslint jsdoc/require-jsdoc: "error" */ -Body.mixIn = function (proto) { - for (const name of Object.getOwnPropertyNames(Body.prototype)) { - // istanbul ignore else: future proof - if (!(name in proto)) { - const desc = Object.getOwnPropertyDescriptor(Body.prototype, name); - Object.defineProperty(proto, name, desc); - } - } -}; + + +const { + ArrayIsArray, + ArrayPrototypeIncludes, + ArrayPrototypeJoin, + ArrayPrototypeMap, + NumberIsInteger, + NumberIsNaN, + NumberMAX_SAFE_INTEGER, + NumberMIN_SAFE_INTEGER, + NumberParseInt, + ObjectPrototypeHasOwnProperty, + RegExpPrototypeExec, + String, + StringPrototypeToUpperCase, + StringPrototypeTrim +} = __nccwpck_require__(89629) +const { + hideStackFrames, + codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL } +} = __nccwpck_require__(80529) +const { normalizeEncoding } = __nccwpck_require__(46959) +const { isAsyncFunction, isArrayBufferView } = (__nccwpck_require__(46959).types) +const signals = {} /** - * Consume and convert an entire Body to a Buffer. - * - * Ref: https://fetch.spec.whatwg.org/#concept-body-consume-body - * - * @return Promise + * @param {*} value + * @returns {boolean} */ -function consumeBody() { - var _this4 = this; - - if (this[INTERNALS].disturbed) { - return Body.Promise.reject(new TypeError(`body used already for: ${this.url}`)); - } +function isInt32(value) { + return value === (value | 0) +} - this[INTERNALS].disturbed = true; +/** + * @param {*} value + * @returns {boolean} + */ +function isUint32(value) { + return value === value >>> 0 +} +const octalReg = /^[0-7]+$/ +const modeDesc = 'must be a 32-bit unsigned integer or an octal string' - if (this[INTERNALS].error) { - return Body.Promise.reject(this[INTERNALS].error); - } +/** + * Parse and validate values that will be converted into mode_t (the S_* + * constants). Only valid numbers and octal strings are allowed. They could be + * converted to 32-bit unsigned integers or non-negative signed integers in the + * C++ land, but any value higher than 0o777 will result in platform-specific + * behaviors. + * @param {*} value Values to be validated + * @param {string} name Name of the argument + * @param {number} [def] If specified, will be returned for invalid values + * @returns {number} + */ +function parseFileMode(value, name, def) { + if (typeof value === 'undefined') { + value = def + } + if (typeof value === 'string') { + if (RegExpPrototypeExec(octalReg, value) === null) { + throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc) + } + value = NumberParseInt(value, 8) + } + validateUint32(value, name) + return value +} - let body = this.body; +/** + * @callback validateInteger + * @param {*} value + * @param {string} name + * @param {number} [min] + * @param {number} [max] + * @returns {asserts value is number} + */ - // body is null - if (body === null) { - return Body.Promise.resolve(Buffer.alloc(0)); - } +/** @type {validateInteger} */ +const validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => { + if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value) + if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, 'an integer', value) + if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) +}) - // body is blob - if (isBlob(body)) { - body = body.stream(); - } +/** + * @callback validateInt32 + * @param {*} value + * @param {string} name + * @param {number} [min] + * @param {number} [max] + * @returns {asserts value is number} + */ - // body is buffer - if (Buffer.isBuffer(body)) { - return Body.Promise.resolve(body); - } +/** @type {validateInt32} */ +const validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => { + // The defaults for min and max correspond to the limits of 32-bit integers. + if (typeof value !== 'number') { + throw new ERR_INVALID_ARG_TYPE(name, 'number', value) + } + if (!NumberIsInteger(value)) { + throw new ERR_OUT_OF_RANGE(name, 'an integer', value) + } + if (value < min || value > max) { + throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) + } +}) - // istanbul ignore if: should never happen - if (!(body instanceof Stream)) { - return Body.Promise.resolve(Buffer.alloc(0)); - } +/** + * @callback validateUint32 + * @param {*} value + * @param {string} name + * @param {number|boolean} [positive=false] + * @returns {asserts value is number} + */ - // body is stream - // get ready to actually consume the body - let accum = []; - let accumBytes = 0; - let abort = false; +/** @type {validateUint32} */ +const validateUint32 = hideStackFrames((value, name, positive = false) => { + if (typeof value !== 'number') { + throw new ERR_INVALID_ARG_TYPE(name, 'number', value) + } + if (!NumberIsInteger(value)) { + throw new ERR_OUT_OF_RANGE(name, 'an integer', value) + } + const min = positive ? 1 : 0 + // 2 ** 32 === 4294967296 + const max = 4294967295 + if (value < min || value > max) { + throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) + } +}) - return new Body.Promise(function (resolve, reject) { - let resTimeout; +/** + * @callback validateString + * @param {*} value + * @param {string} name + * @returns {asserts value is string} + */ - // allow timeout on slow response body - if (_this4.timeout) { - resTimeout = setTimeout(function () { - abort = true; - reject(new FetchError(`Response timeout while trying to fetch ${_this4.url} (over ${_this4.timeout}ms)`, 'body-timeout')); - }, _this4.timeout); - } +/** @type {validateString} */ +function validateString(value, name) { + if (typeof value !== 'string') throw new ERR_INVALID_ARG_TYPE(name, 'string', value) +} - // handle stream errors - body.on('error', function (err) { - if (err.name === 'AbortError') { - // if the request was aborted, reject with this Error - abort = true; - reject(err); - } else { - // other errors, such as incorrect content-encoding - reject(new FetchError(`Invalid response body while trying to fetch ${_this4.url}: ${err.message}`, 'system', err)); - } - }); +/** + * @callback validateNumber + * @param {*} value + * @param {string} name + * @param {number} [min] + * @param {number} [max] + * @returns {asserts value is number} + */ - body.on('data', function (chunk) { - if (abort || chunk === null) { - return; - } +/** @type {validateNumber} */ +function validateNumber(value, name, min = undefined, max) { + if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value) + if ( + (min != null && value < min) || + (max != null && value > max) || + ((min != null || max != null) && NumberIsNaN(value)) + ) { + throw new ERR_OUT_OF_RANGE( + name, + `${min != null ? `>= ${min}` : ''}${min != null && max != null ? ' && ' : ''}${max != null ? `<= ${max}` : ''}`, + value + ) + } +} - if (_this4.size && accumBytes + chunk.length > _this4.size) { - abort = true; - reject(new FetchError(`content size at ${_this4.url} over limit: ${_this4.size}`, 'max-size')); - return; - } +/** + * @callback validateOneOf + * @template T + * @param {T} value + * @param {string} name + * @param {T[]} oneOf + */ - accumBytes += chunk.length; - accum.push(chunk); - }); +/** @type {validateOneOf} */ +const validateOneOf = hideStackFrames((value, name, oneOf) => { + if (!ArrayPrototypeIncludes(oneOf, value)) { + const allowed = ArrayPrototypeJoin( + ArrayPrototypeMap(oneOf, (v) => (typeof v === 'string' ? `'${v}'` : String(v))), + ', ' + ) + const reason = 'must be one of: ' + allowed + throw new ERR_INVALID_ARG_VALUE(name, value, reason) + } +}) - body.on('end', function () { - if (abort) { - return; - } +/** + * @callback validateBoolean + * @param {*} value + * @param {string} name + * @returns {asserts value is boolean} + */ - clearTimeout(resTimeout); +/** @type {validateBoolean} */ +function validateBoolean(value, name) { + if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value) +} - try { - resolve(Buffer.concat(accum, accumBytes)); - } catch (err) { - // handle streams that have accumulated too much data (issue #414) - reject(new FetchError(`Could not create Buffer from response body for ${_this4.url}: ${err.message}`, 'system', err)); - } - }); - }); +/** + * @param {any} options + * @param {string} key + * @param {boolean} defaultValue + * @returns {boolean} + */ +function getOwnPropertyValueOrDefault(options, key, defaultValue) { + return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key] } /** - * Detect buffer encoding and convert to target encoding - * ref: http://www.w3.org/TR/2011/WD-html5-20110113/parsing.html#determining-the-character-encoding - * - * @param Buffer buffer Incoming buffer - * @param String encoding Target encoding - * @return String + * @callback validateObject + * @param {*} value + * @param {string} name + * @param {{ + * allowArray?: boolean, + * allowFunction?: boolean, + * nullable?: boolean + * }} [options] + */ + +/** @type {validateObject} */ +const validateObject = hideStackFrames((value, name, options = null) => { + const allowArray = getOwnPropertyValueOrDefault(options, 'allowArray', false) + const allowFunction = getOwnPropertyValueOrDefault(options, 'allowFunction', false) + const nullable = getOwnPropertyValueOrDefault(options, 'nullable', false) + if ( + (!nullable && value === null) || + (!allowArray && ArrayIsArray(value)) || + (typeof value !== 'object' && (!allowFunction || typeof value !== 'function')) + ) { + throw new ERR_INVALID_ARG_TYPE(name, 'Object', value) + } +}) + +/** + * @callback validateDictionary - We are using the Web IDL Standard definition + * of "dictionary" here, which means any value + * whose Type is either Undefined, Null, or + * Object (which includes functions). + * @param {*} value + * @param {string} name + * @see https://webidl.spec.whatwg.org/#es-dictionary + * @see https://tc39.es/ecma262/#table-typeof-operator-results */ -function convertBody(buffer, headers) { - if (typeof convert !== 'function') { - throw new Error('The package `encoding` must be installed to use the textConverted() function'); - } - const ct = headers.get('content-type'); - let charset = 'utf-8'; - let res, str; +/** @type {validateDictionary} */ +const validateDictionary = hideStackFrames((value, name) => { + if (value != null && typeof value !== 'object' && typeof value !== 'function') { + throw new ERR_INVALID_ARG_TYPE(name, 'a dictionary', value) + } +}) - // header - if (ct) { - res = /charset=([^;]*)/i.exec(ct); - } +/** + * @callback validateArray + * @param {*} value + * @param {string} name + * @param {number} [minLength] + * @returns {asserts value is any[]} + */ - // no charset in content type, peek at response body for at most 1024 bytes - str = buffer.slice(0, 1024).toString(); +/** @type {validateArray} */ +const validateArray = hideStackFrames((value, name, minLength = 0) => { + if (!ArrayIsArray(value)) { + throw new ERR_INVALID_ARG_TYPE(name, 'Array', value) + } + if (value.length < minLength) { + const reason = `must be longer than ${minLength}` + throw new ERR_INVALID_ARG_VALUE(name, value, reason) + } +}) - // html5 - if (!res && str) { - res = / { + if (!isArrayBufferView(buffer)) { + throw new ERR_INVALID_ARG_TYPE(name, ['Buffer', 'TypedArray', 'DataView'], buffer) + } +}) + +/** + * @param {string} data + * @param {string} encoding + */ +function validateEncoding(data, encoding) { + const normalizedEncoding = normalizeEncoding(encoding) + const length = data.length + if (normalizedEncoding === 'hex' && length % 2 !== 0) { + throw new ERR_INVALID_ARG_VALUE('encoding', encoding, `is invalid for data of length ${length}`) + } } /** - * Check if `obj` is a W3C `Blob` object (which `File` inherits from) - * @param {*} obj - * @return {boolean} + * Check that the port number is not NaN when coerced to a number, + * is an integer and that it falls within the legal range of port numbers. + * @param {*} port + * @param {string} [name='Port'] + * @param {boolean} [allowZero=true] + * @returns {number} */ -function isBlob(obj) { - return typeof obj === 'object' && typeof obj.arrayBuffer === 'function' && typeof obj.type === 'string' && typeof obj.stream === 'function' && typeof obj.constructor === 'function' && typeof obj.constructor.name === 'string' && /^(Blob|File)$/.test(obj.constructor.name) && /^(Blob|File)$/.test(obj[Symbol.toStringTag]); +function validatePort(port, name = 'Port', allowZero = true) { + if ( + (typeof port !== 'number' && typeof port !== 'string') || + (typeof port === 'string' && StringPrototypeTrim(port).length === 0) || + +port !== +port >>> 0 || + port > 0xffff || + (port === 0 && !allowZero) + ) { + throw new ERR_SOCKET_BAD_PORT(name, port, allowZero) + } + return port | 0 } /** - * Clone body given Res/Req instance - * - * @param Mixed instance Response or Request instance - * @return Mixed + * @callback validateAbortSignal + * @param {*} signal + * @param {string} name */ -function clone(instance) { - let p1, p2; - let body = instance.body; - // don't allow cloning a used body - if (instance.bodyUsed) { - throw new Error('cannot clone body after it is used'); - } +/** @type {validateAbortSignal} */ +const validateAbortSignal = hideStackFrames((signal, name) => { + if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) { + throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) + } +}) - // check that body is a stream and not form-data object - // note: we can't clone the form-data object without having it as a dependency - if (body instanceof Stream && typeof body.getBoundary !== 'function') { - // tee instance body - p1 = new PassThrough(); - p2 = new PassThrough(); - body.pipe(p1); - body.pipe(p2); - // set instance body to teed body and return the other teed body - instance[INTERNALS].body = p1; - body = p2; - } +/** + * @callback validateFunction + * @param {*} value + * @param {string} name + * @returns {asserts value is Function} + */ - return body; -} +/** @type {validateFunction} */ +const validateFunction = hideStackFrames((value, name) => { + if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) +}) /** - * Performs the operation "extract a `Content-Type` value from |object|" as - * specified in the specification: - * https://fetch.spec.whatwg.org/#concept-bodyinit-extract - * - * This function assumes that instance.body is present. - * - * @param Mixed instance Any options.body input + * @callback validatePlainFunction + * @param {*} value + * @param {string} name + * @returns {asserts value is Function} */ -function extractContentType(body) { - if (body === null) { - // body is null - return null; - } else if (typeof body === 'string') { - // body is string - return 'text/plain;charset=UTF-8'; - } else if (isURLSearchParams(body)) { - // body is a URLSearchParams - return 'application/x-www-form-urlencoded;charset=UTF-8'; - } else if (isBlob(body)) { - // body is blob - return body.type || null; - } else if (Buffer.isBuffer(body)) { - // body is buffer - return null; - } else if (Object.prototype.toString.call(body) === '[object ArrayBuffer]') { - // body is ArrayBuffer - return null; - } else if (ArrayBuffer.isView(body)) { - // body is ArrayBufferView - return null; - } else if (typeof body.getBoundary === 'function') { - // detect form data input from form-data module - return `multipart/form-data;boundary=${body.getBoundary()}`; - } else if (body instanceof Stream) { - // body is stream - // can't really do much about this - return null; - } else { - // Body constructor defaults other things to string - return 'text/plain;charset=UTF-8'; - } -} + +/** @type {validatePlainFunction} */ +const validatePlainFunction = hideStackFrames((value, name) => { + if (typeof value !== 'function' || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) +}) /** - * The Fetch Standard treats this as if "total bytes" is a property on the body. - * For us, we have to explicitly get it with a function. - * - * ref: https://fetch.spec.whatwg.org/#concept-body-total-bytes - * - * @param Body instance Instance of Body - * @return Number? Number of bytes, or null if not possible + * @callback validateUndefined + * @param {*} value + * @param {string} name + * @returns {asserts value is undefined} */ -function getTotalBytes(instance) { - const body = instance.body; - - if (body === null) { - // body is null - return 0; - } else if (isBlob(body)) { - return body.size; - } else if (Buffer.isBuffer(body)) { - // body is buffer - return body.length; - } else if (body && typeof body.getLengthSync === 'function') { - // detect form data input from form-data module - if (body._lengthRetrievers && body._lengthRetrievers.length == 0 || // 1.x - body.hasKnownLength && body.hasKnownLength()) { - // 2.x - return body.getLengthSync(); - } - return null; - } else { - // body is stream - return null; - } -} +/** @type {validateUndefined} */ +const validateUndefined = hideStackFrames((value, name) => { + if (value !== undefined) throw new ERR_INVALID_ARG_TYPE(name, 'undefined', value) +}) /** - * Write a Body to a Node.js WritableStream (e.g. http.Request) object. - * - * @param Body instance Instance of Body - * @return Void + * @template T + * @param {T} value + * @param {string} name + * @param {T[]} union */ -function writeToStream(dest, instance) { - const body = instance.body; - - - if (body === null) { - // body is null - dest.end(); - } else if (isBlob(body)) { - body.stream().pipe(dest); - } else if (Buffer.isBuffer(body)) { - // body is buffer - dest.write(body); - dest.end(); - } else { - // body is stream - body.pipe(dest); - } +function validateUnion(value, name, union) { + if (!ArrayPrototypeIncludes(union, value)) { + throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value) + } } -// expose Promise -Body.Promise = global.Promise; +/* + The rules for the Link header field are described here: + https://www.rfc-editor.org/rfc/rfc8288.html#section-3 + + This regex validates any string surrounded by angle brackets + (not necessarily a valid URI reference) followed by zero or more + link-params separated by semicolons. +*/ +const linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/ /** - * headers.js - * - * Headers class offers convenient helpers + * @param {any} value + * @param {string} name */ - -const invalidTokenRegex = /[^\^_`a-zA-Z\-0-9!#$%&'*+.|~]/; -const invalidHeaderCharRegex = /[^\t\x20-\x7e\x80-\xff]/; - -function validateName(name) { - name = `${name}`; - if (invalidTokenRegex.test(name) || name === '') { - throw new TypeError(`${name} is not a legal HTTP header name`); - } -} - -function validateValue(value) { - value = `${value}`; - if (invalidHeaderCharRegex.test(value)) { - throw new TypeError(`${value} is not a legal HTTP header value`); - } +function validateLinkHeaderFormat(value, name) { + if (typeof value === 'undefined' || !RegExpPrototypeExec(linkValueRegExp, value)) { + throw new ERR_INVALID_ARG_VALUE( + name, + value, + 'must be an array or string of format "; rel=preload; as=style"' + ) + } } /** - * Find the key in the map object given a header name. - * - * Returns undefined if not found. - * - * @param String name Header name - * @return String|Undefined + * @param {any} hints + * @return {string} */ -function find(map, name) { - name = name.toLowerCase(); - for (const key in map) { - if (key.toLowerCase() === name) { - return key; - } - } - return undefined; +function validateLinkHeaderValue(hints) { + if (typeof hints === 'string') { + validateLinkHeaderFormat(hints, 'hints') + return hints + } else if (ArrayIsArray(hints)) { + const hintsLength = hints.length + let result = '' + if (hintsLength === 0) { + return result + } + for (let i = 0; i < hintsLength; i++) { + const link = hints[i] + validateLinkHeaderFormat(link, 'hints') + result += link + if (i !== hintsLength - 1) { + result += ', ' + } + } + return result + } + throw new ERR_INVALID_ARG_VALUE( + 'hints', + hints, + 'must be an array or string of format "; rel=preload; as=style"' + ) } +module.exports = { + isInt32, + isUint32, + parseFileMode, + validateArray, + validateStringArray, + validateBooleanArray, + validateAbortSignalArray, + validateBoolean, + validateBuffer, + validateDictionary, + validateEncoding, + validateFunction, + validateInt32, + validateInteger, + validateNumber, + validateObject, + validateOneOf, + validatePlainFunction, + validatePort, + validateSignalName, + validateString, + validateUint32, + validateUndefined, + validateUnion, + validateAbortSignal, + validateLinkHeaderValue +} + + +/***/ }), + +/***/ 80529: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const MAP = Symbol('map'); -class Headers { - /** - * Headers class - * - * @param Object headers Response headers - * @return Void - */ - constructor() { - let init = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : undefined; +"use strict"; - this[MAP] = Object.create(null); - if (init instanceof Headers) { - const rawHeaders = init.raw(); - const headerNames = Object.keys(rawHeaders); +const { format, inspect, AggregateError: CustomAggregateError } = __nccwpck_require__(46959) - for (const headerName of headerNames) { - for (const value of rawHeaders[headerName]) { - this.append(headerName, value); - } - } +/* + This file is a reduced and adapted version of the main lib/internal/errors.js file defined at + + https://github.com/nodejs/node/blob/master/lib/internal/errors.js + + Don't try to replace with the original file and keep it up to date (starting from E(...) definitions) + with the upstream file. +*/ + +const AggregateError = globalThis.AggregateError || CustomAggregateError +const kIsNodeError = Symbol('kIsNodeError') +const kTypes = [ + 'string', + 'function', + 'number', + 'object', + // Accept 'Function' and 'Object' as alternative to the lower cased version. + 'Function', + 'Object', + 'boolean', + 'bigint', + 'symbol' +] +const classRegExp = /^([A-Z][a-z0-9]*)+$/ +const nodeInternalPrefix = '__node_internal_' +const codes = {} +function assert(value, message) { + if (!value) { + throw new codes.ERR_INTERNAL_ASSERTION(message) + } +} - return; - } +// Only use this for integers! Decimal numbers do not work with this function. +function addNumericalSeparator(val) { + let res = '' + let i = val.length + const start = val[0] === '-' ? 1 : 0 + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}` + } + return `${val.slice(0, i)}${res}` +} +function getMessage(key, msg, args) { + if (typeof msg === 'function') { + assert( + msg.length <= args.length, + // Default options do not count. + `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).` + ) + return msg(...args) + } + const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length + assert( + expectedLength === args.length, + `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).` + ) + if (args.length === 0) { + return msg + } + return format(msg, ...args) +} +function E(code, message, Base) { + if (!Base) { + Base = Error + } + class NodeError extends Base { + constructor(...args) { + super(getMessage(code, message, args)) + } + toString() { + return `${this.name} [${code}]: ${this.message}` + } + } + Object.defineProperties(NodeError.prototype, { + name: { + value: Base.name, + writable: true, + enumerable: false, + configurable: true + }, + toString: { + value() { + return `${this.name} [${code}]: ${this.message}` + }, + writable: true, + enumerable: false, + configurable: true + } + }) + NodeError.prototype.code = code + NodeError.prototype[kIsNodeError] = true + codes[code] = NodeError +} +function hideStackFrames(fn) { + // We rename the functions that will be hidden to cut off the stacktrace + // at the outermost one + const hidden = nodeInternalPrefix + fn.name + Object.defineProperty(fn, 'name', { + value: hidden + }) + return fn +} +function aggregateTwoErrors(innerError, outerError) { + if (innerError && outerError && innerError !== outerError) { + if (Array.isArray(outerError.errors)) { + // If `outerError` is already an `AggregateError`. + outerError.errors.push(innerError) + return outerError + } + const err = new AggregateError([outerError, innerError], outerError.message) + err.code = outerError.code + return err + } + return innerError || outerError +} +class AbortError extends Error { + constructor(message = 'The operation was aborted', options = undefined) { + if (options !== undefined && typeof options !== 'object') { + throw new codes.ERR_INVALID_ARG_TYPE('options', 'Object', options) + } + super(message, options) + this.code = 'ABORT_ERR' + this.name = 'AbortError' + } +} +E('ERR_ASSERTION', '%s', Error) +E( + 'ERR_INVALID_ARG_TYPE', + (name, expected, actual) => { + assert(typeof name === 'string', "'name' must be a string") + if (!Array.isArray(expected)) { + expected = [expected] + } + let msg = 'The ' + if (name.endsWith(' argument')) { + // For cases like 'first argument' + msg += `${name} ` + } else { + msg += `"${name}" ${name.includes('.') ? 'property' : 'argument'} ` + } + msg += 'must be ' + const types = [] + const instances = [] + const other = [] + for (const value of expected) { + assert(typeof value === 'string', 'All expected entries have to be of type string') + if (kTypes.includes(value)) { + types.push(value.toLowerCase()) + } else if (classRegExp.test(value)) { + instances.push(value) + } else { + assert(value !== 'object', 'The value "object" should be written as "Object"') + other.push(value) + } + } - // We don't worry about converting prop to ByteString here as append() - // will handle it. - if (init == null) ; else if (typeof init === 'object') { - const method = init[Symbol.iterator]; - if (method != null) { - if (typeof method !== 'function') { - throw new TypeError('Header pairs must be iterable'); - } + // Special handle `object` in case other instances are allowed to outline + // the differences between each other. + if (instances.length > 0) { + const pos = types.indexOf('object') + if (pos !== -1) { + types.splice(types, pos, 1) + instances.push('Object') + } + } + if (types.length > 0) { + switch (types.length) { + case 1: + msg += `of type ${types[0]}` + break + case 2: + msg += `one of type ${types[0]} or ${types[1]}` + break + default: { + const last = types.pop() + msg += `one of type ${types.join(', ')}, or ${last}` + } + } + if (instances.length > 0 || other.length > 0) { + msg += ' or ' + } + } + if (instances.length > 0) { + switch (instances.length) { + case 1: + msg += `an instance of ${instances[0]}` + break + case 2: + msg += `an instance of ${instances[0]} or ${instances[1]}` + break + default: { + const last = instances.pop() + msg += `an instance of ${instances.join(', ')}, or ${last}` + } + } + if (other.length > 0) { + msg += ' or ' + } + } + switch (other.length) { + case 0: + break + case 1: + if (other[0].toLowerCase() !== other[0]) { + msg += 'an ' + } + msg += `${other[0]}` + break + case 2: + msg += `one of ${other[0]} or ${other[1]}` + break + default: { + const last = other.pop() + msg += `one of ${other.join(', ')}, or ${last}` + } + } + if (actual == null) { + msg += `. Received ${actual}` + } else if (typeof actual === 'function' && actual.name) { + msg += `. Received function ${actual.name}` + } else if (typeof actual === 'object') { + var _actual$constructor + if ( + (_actual$constructor = actual.constructor) !== null && + _actual$constructor !== undefined && + _actual$constructor.name + ) { + msg += `. Received an instance of ${actual.constructor.name}` + } else { + const inspected = inspect(actual, { + depth: -1 + }) + msg += `. Received ${inspected}` + } + } else { + let inspected = inspect(actual, { + colors: false + }) + if (inspected.length > 25) { + inspected = `${inspected.slice(0, 25)}...` + } + msg += `. Received type ${typeof actual} (${inspected})` + } + return msg + }, + TypeError +) +E( + 'ERR_INVALID_ARG_VALUE', + (name, value, reason = 'is invalid') => { + let inspected = inspect(value) + if (inspected.length > 128) { + inspected = inspected.slice(0, 128) + '...' + } + const type = name.includes('.') ? 'property' : 'argument' + return `The ${type} '${name}' ${reason}. Received ${inspected}` + }, + TypeError +) +E( + 'ERR_INVALID_RETURN_VALUE', + (input, name, value) => { + var _value$constructor + const type = + value !== null && + value !== undefined && + (_value$constructor = value.constructor) !== null && + _value$constructor !== undefined && + _value$constructor.name + ? `instance of ${value.constructor.name}` + : `type ${typeof value}` + return `Expected ${input} to be returned from the "${name}"` + ` function but got ${type}.` + }, + TypeError +) +E( + 'ERR_MISSING_ARGS', + (...args) => { + assert(args.length > 0, 'At least one arg needs to be specified') + let msg + const len = args.length + args = (Array.isArray(args) ? args : [args]).map((a) => `"${a}"`).join(' or ') + switch (len) { + case 1: + msg += `The ${args[0]} argument` + break + case 2: + msg += `The ${args[0]} and ${args[1]} arguments` + break + default: + { + const last = args.pop() + msg += `The ${args.join(', ')}, and ${last} arguments` + } + break + } + return `${msg} must be specified` + }, + TypeError +) +E( + 'ERR_OUT_OF_RANGE', + (str, range, input) => { + assert(range, 'Missing "range" argument') + let received + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)) + } else if (typeof input === 'bigint') { + received = String(input) + if (input > 2n ** 32n || input < -(2n ** 32n)) { + received = addNumericalSeparator(received) + } + received += 'n' + } else { + received = inspect(input) + } + return `The value of "${str}" is out of range. It must be ${range}. Received ${received}` + }, + RangeError +) +E('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error) +E('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error) +E('ERR_STREAM_ALREADY_FINISHED', 'Cannot call %s after a stream was finished', Error) +E('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error) +E('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error) +E('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError) +E('ERR_STREAM_PREMATURE_CLOSE', 'Premature close', Error) +E('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error) +E('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event', Error) +E('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error) +E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError) +module.exports = { + AbortError, + aggregateTwoErrors: hideStackFrames(aggregateTwoErrors), + hideStackFrames, + codes +} - // sequence> - // Note: per spec we have to first exhaust the lists then process them - const pairs = []; - for (const pair of init) { - if (typeof pair !== 'object' || typeof pair[Symbol.iterator] !== 'function') { - throw new TypeError('Each header pair must be iterable'); - } - pairs.push(Array.from(pair)); - } - for (const pair of pairs) { - if (pair.length !== 2) { - throw new TypeError('Each header pair must be a name/value tuple'); - } - this.append(pair[0], pair[1]); - } - } else { - // record - for (const key of Object.keys(init)) { - const value = init[key]; - this.append(key, value); - } - } - } else { - throw new TypeError('Provided initializer must be an object'); - } - } +/***/ }), - /** - * Return combined header value given name - * - * @param String name Header name - * @return Mixed - */ - get(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key === undefined) { - return null; - } +/***/ 45193: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return this[MAP][key].join(', '); - } +"use strict"; - /** - * Iterate over all headers - * - * @param Function callback Executed for each item with parameters (value, name, thisArg) - * @param Boolean thisArg `this` context for callback function - * @return Void - */ - forEach(callback) { - let thisArg = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : undefined; - let pairs = getHeaders(this); - let i = 0; - while (i < pairs.length) { - var _pairs$i = pairs[i]; - const name = _pairs$i[0], - value = _pairs$i[1]; +const Stream = __nccwpck_require__(12781) +if (Stream && process.env.READABLE_STREAM === 'disable') { + const promises = Stream.promises + + // Explicit export naming is needed for ESM + module.exports._uint8ArrayToBuffer = Stream._uint8ArrayToBuffer + module.exports._isUint8Array = Stream._isUint8Array + module.exports.isDisturbed = Stream.isDisturbed + module.exports.isErrored = Stream.isErrored + module.exports.isReadable = Stream.isReadable + module.exports.Readable = Stream.Readable + module.exports.Writable = Stream.Writable + module.exports.Duplex = Stream.Duplex + module.exports.Transform = Stream.Transform + module.exports.PassThrough = Stream.PassThrough + module.exports.addAbortSignal = Stream.addAbortSignal + module.exports.finished = Stream.finished + module.exports.destroy = Stream.destroy + module.exports.pipeline = Stream.pipeline + module.exports.compose = Stream.compose + Object.defineProperty(Stream, 'promises', { + configurable: true, + enumerable: true, + get() { + return promises + } + }) + module.exports.Stream = Stream.Stream +} else { + const CustomStream = __nccwpck_require__(75102) + const promises = __nccwpck_require__(348) + const originalDestroy = CustomStream.Readable.destroy + module.exports = CustomStream.Readable + + // Explicit export naming is needed for ESM + module.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer + module.exports._isUint8Array = CustomStream._isUint8Array + module.exports.isDisturbed = CustomStream.isDisturbed + module.exports.isErrored = CustomStream.isErrored + module.exports.isReadable = CustomStream.isReadable + module.exports.Readable = CustomStream.Readable + module.exports.Writable = CustomStream.Writable + module.exports.Duplex = CustomStream.Duplex + module.exports.Transform = CustomStream.Transform + module.exports.PassThrough = CustomStream.PassThrough + module.exports.addAbortSignal = CustomStream.addAbortSignal + module.exports.finished = CustomStream.finished + module.exports.destroy = CustomStream.destroy + module.exports.destroy = originalDestroy + module.exports.pipeline = CustomStream.pipeline + module.exports.compose = CustomStream.compose + Object.defineProperty(CustomStream, 'promises', { + configurable: true, + enumerable: true, + get() { + return promises + } + }) + module.exports.Stream = CustomStream.Stream +} - callback.call(thisArg, value, name, this); - pairs = getHeaders(this); - i++; - } - } +// Allow default importing +module.exports["default"] = module.exports - /** - * Overwrite header values given name - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - set(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - this[MAP][key !== undefined ? key : name] = [value]; - } - /** - * Append a value onto existing header - * - * @param String name Header name - * @param String value Header value - * @return Void - */ - append(name, value) { - name = `${name}`; - value = `${value}`; - validateName(name); - validateValue(value); - const key = find(this[MAP], name); - if (key !== undefined) { - this[MAP][key].push(value); - } else { - this[MAP][name] = [value]; - } - } +/***/ }), - /** - * Check for header name existence - * - * @param String name Header name - * @return Boolean - */ - has(name) { - name = `${name}`; - validateName(name); - return find(this[MAP], name) !== undefined; - } +/***/ 89629: +/***/ ((module) => { - /** - * Delete all header values given name - * - * @param String name Header name - * @return Void - */ - delete(name) { - name = `${name}`; - validateName(name); - const key = find(this[MAP], name); - if (key !== undefined) { - delete this[MAP][key]; - } - } +"use strict"; - /** - * Return raw headers (non-spec api) - * - * @return Object - */ - raw() { - return this[MAP]; - } - /** - * Get an iterator on keys. - * - * @return Iterator - */ - keys() { - return createHeadersIterator(this, 'key'); - } +/* + This file is a reduced and adapted version of the main lib/internal/per_context/primordials.js file defined at - /** - * Get an iterator on values. - * - * @return Iterator - */ - values() { - return createHeadersIterator(this, 'value'); - } + https://github.com/nodejs/node/blob/master/lib/internal/per_context/primordials.js - /** - * Get an iterator on entries. - * - * This is the default iterator of the Headers object. - * - * @return Iterator - */ - [Symbol.iterator]() { - return createHeadersIterator(this, 'key+value'); - } + Don't try to replace with the original file and keep it up to date with the upstream file. +*/ +module.exports = { + ArrayIsArray(self) { + return Array.isArray(self) + }, + ArrayPrototypeIncludes(self, el) { + return self.includes(el) + }, + ArrayPrototypeIndexOf(self, el) { + return self.indexOf(el) + }, + ArrayPrototypeJoin(self, sep) { + return self.join(sep) + }, + ArrayPrototypeMap(self, fn) { + return self.map(fn) + }, + ArrayPrototypePop(self, el) { + return self.pop(el) + }, + ArrayPrototypePush(self, el) { + return self.push(el) + }, + ArrayPrototypeSlice(self, start, end) { + return self.slice(start, end) + }, + Error, + FunctionPrototypeCall(fn, thisArgs, ...args) { + return fn.call(thisArgs, ...args) + }, + FunctionPrototypeSymbolHasInstance(self, instance) { + return Function.prototype[Symbol.hasInstance].call(self, instance) + }, + MathFloor: Math.floor, + Number, + NumberIsInteger: Number.isInteger, + NumberIsNaN: Number.isNaN, + NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, + NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, + NumberParseInt: Number.parseInt, + ObjectDefineProperties(self, props) { + return Object.defineProperties(self, props) + }, + ObjectDefineProperty(self, name, prop) { + return Object.defineProperty(self, name, prop) + }, + ObjectGetOwnPropertyDescriptor(self, name) { + return Object.getOwnPropertyDescriptor(self, name) + }, + ObjectKeys(obj) { + return Object.keys(obj) + }, + ObjectSetPrototypeOf(target, proto) { + return Object.setPrototypeOf(target, proto) + }, + Promise, + PromisePrototypeCatch(self, fn) { + return self.catch(fn) + }, + PromisePrototypeThen(self, thenFn, catchFn) { + return self.then(thenFn, catchFn) + }, + PromiseReject(err) { + return Promise.reject(err) + }, + PromiseResolve(val) { + return Promise.resolve(val) + }, + ReflectApply: Reflect.apply, + RegExpPrototypeTest(self, value) { + return self.test(value) + }, + SafeSet: Set, + String, + StringPrototypeSlice(self, start, end) { + return self.slice(start, end) + }, + StringPrototypeToLowerCase(self) { + return self.toLowerCase() + }, + StringPrototypeToUpperCase(self) { + return self.toUpperCase() + }, + StringPrototypeTrim(self) { + return self.trim() + }, + Symbol, + SymbolFor: Symbol.for, + SymbolAsyncIterator: Symbol.asyncIterator, + SymbolHasInstance: Symbol.hasInstance, + SymbolIterator: Symbol.iterator, + SymbolDispose: Symbol.dispose || Symbol('Symbol.dispose'), + SymbolAsyncDispose: Symbol.asyncDispose || Symbol('Symbol.asyncDispose'), + TypedArrayPrototypeSet(self, buf, len) { + return self.set(buf, len) + }, + Boolean: Boolean, + Uint8Array } -Headers.prototype.entries = Headers.prototype[Symbol.iterator]; - -Object.defineProperty(Headers.prototype, Symbol.toStringTag, { - value: 'Headers', - writable: false, - enumerable: false, - configurable: true -}); -Object.defineProperties(Headers.prototype, { - get: { enumerable: true }, - forEach: { enumerable: true }, - set: { enumerable: true }, - append: { enumerable: true }, - has: { enumerable: true }, - delete: { enumerable: true }, - keys: { enumerable: true }, - values: { enumerable: true }, - entries: { enumerable: true } -}); -function getHeaders(headers) { - let kind = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'key+value'; +/***/ }), - const keys = Object.keys(headers[MAP]).sort(); - return keys.map(kind === 'key' ? function (k) { - return k.toLowerCase(); - } : kind === 'value' ? function (k) { - return headers[MAP][k].join(', '); - } : function (k) { - return [k.toLowerCase(), headers[MAP][k].join(', ')]; - }); -} +/***/ 46959: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const INTERNAL = Symbol('internal'); +"use strict"; -function createHeadersIterator(target, kind) { - const iterator = Object.create(HeadersIteratorPrototype); - iterator[INTERNAL] = { - target, - kind, - index: 0 - }; - return iterator; -} -const HeadersIteratorPrototype = Object.setPrototypeOf({ - next() { - // istanbul ignore if - if (!this || Object.getPrototypeOf(this) !== HeadersIteratorPrototype) { - throw new TypeError('Value of `this` is not a HeadersIterator'); - } +const bufferModule = __nccwpck_require__(14300) +const { kResistStopPropagation, SymbolDispose } = __nccwpck_require__(89629) +const AbortSignal = globalThis.AbortSignal || (__nccwpck_require__(61659).AbortSignal) +const AbortController = globalThis.AbortController || (__nccwpck_require__(61659).AbortController) +const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor +const Blob = globalThis.Blob || bufferModule.Blob +/* eslint-disable indent */ +const isBlob = + typeof Blob !== 'undefined' + ? function isBlob(b) { + // eslint-disable-next-line indent + return b instanceof Blob + } + : function isBlob(b) { + return false + } +/* eslint-enable indent */ - var _INTERNAL = this[INTERNAL]; - const target = _INTERNAL.target, - kind = _INTERNAL.kind, - index = _INTERNAL.index; +const validateAbortSignal = (signal, name) => { + if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) { + throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) + } +} +const validateFunction = (value, name) => { + if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) +} - const values = getHeaders(target, kind); - const len = values.length; - if (index >= len) { - return { - value: undefined, - done: true - }; - } - - this[INTERNAL].index = index + 1; - - return { - value: values[index], - done: false - }; - } -}, Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]()))); - -Object.defineProperty(HeadersIteratorPrototype, Symbol.toStringTag, { - value: 'HeadersIterator', - writable: false, - enumerable: false, - configurable: true -}); - -/** - * Export the Headers object in a form that Node.js can consume. - * - * @param Headers headers - * @return Object - */ -function exportNodeCompatibleHeaders(headers) { - const obj = Object.assign({ __proto__: null }, headers[MAP]); - - // http.request() only supports string as Host header. This hack makes - // specifying custom Host header possible. - const hostHeaderKey = find(headers[MAP], 'Host'); - if (hostHeaderKey !== undefined) { - obj[hostHeaderKey] = obj[hostHeaderKey][0]; - } - - return obj; +// This is a simplified version of AggregateError +class AggregateError extends Error { + constructor(errors) { + if (!Array.isArray(errors)) { + throw new TypeError(`Expected input to be an Array, got ${typeof errors}`) + } + let message = '' + for (let i = 0; i < errors.length; i++) { + message += ` ${errors[i].stack}\n` + } + super(message) + this.name = 'AggregateError' + this.errors = errors + } } - -/** - * Create a Headers object from an object of headers, ignoring those that do - * not conform to HTTP grammar productions. - * - * @param Object obj Object of headers - * @return Headers - */ -function createHeadersLenient(obj) { - const headers = new Headers(); - for (const name of Object.keys(obj)) { - if (invalidTokenRegex.test(name)) { - continue; - } - if (Array.isArray(obj[name])) { - for (const val of obj[name]) { - if (invalidHeaderCharRegex.test(val)) { - continue; - } - if (headers[MAP][name] === undefined) { - headers[MAP][name] = [val]; - } else { - headers[MAP][name].push(val); - } - } - } else if (!invalidHeaderCharRegex.test(obj[name])) { - headers[MAP][name] = [obj[name]]; - } - } - return headers; +module.exports = { + AggregateError, + kEmptyObject: Object.freeze({}), + once(callback) { + let called = false + return function (...args) { + if (called) { + return + } + called = true + callback.apply(this, args) + } + }, + createDeferredPromise: function () { + let resolve + let reject + + // eslint-disable-next-line promise/param-names + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return { + promise, + resolve, + reject + } + }, + promisify(fn) { + return new Promise((resolve, reject) => { + fn((err, ...args) => { + if (err) { + return reject(err) + } + return resolve(...args) + }) + }) + }, + debuglog() { + return function () {} + }, + format(format, ...args) { + // Simplified version of https://nodejs.org/api/util.html#utilformatformat-args + return format.replace(/%([sdifj])/g, function (...[_unused, type]) { + const replacement = args.shift() + if (type === 'f') { + return replacement.toFixed(6) + } else if (type === 'j') { + return JSON.stringify(replacement) + } else if (type === 's' && typeof replacement === 'object') { + const ctor = replacement.constructor !== Object ? replacement.constructor.name : '' + return `${ctor} {}`.trim() + } else { + return replacement.toString() + } + }) + }, + inspect(value) { + // Vastly simplified version of https://nodejs.org/api/util.html#utilinspectobject-options + switch (typeof value) { + case 'string': + if (value.includes("'")) { + if (!value.includes('"')) { + return `"${value}"` + } else if (!value.includes('`') && !value.includes('${')) { + return `\`${value}\`` + } + } + return `'${value}'` + case 'number': + if (isNaN(value)) { + return 'NaN' + } else if (Object.is(value, -0)) { + return String(value) + } + return value + case 'bigint': + return `${String(value)}n` + case 'boolean': + case 'undefined': + return String(value) + case 'object': + return '{}' + } + }, + types: { + isAsyncFunction(fn) { + return fn instanceof AsyncFunction + }, + isArrayBufferView(arr) { + return ArrayBuffer.isView(arr) + } + }, + isBlob, + deprecate(fn, message) { + return fn + }, + addAbortListener: + (__nccwpck_require__(82361).addAbortListener) || + function addAbortListener(signal, listener) { + if (signal === undefined) { + throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal) + } + validateAbortSignal(signal, 'signal') + validateFunction(listener, 'listener') + let removeEventListener + if (signal.aborted) { + queueMicrotask(() => listener()) + } else { + signal.addEventListener('abort', listener, { + __proto__: null, + once: true, + [kResistStopPropagation]: true + }) + removeEventListener = () => { + signal.removeEventListener('abort', listener) + } + } + return { + __proto__: null, + [SymbolDispose]() { + var _removeEventListener + ;(_removeEventListener = removeEventListener) === null || _removeEventListener === undefined + ? undefined + : _removeEventListener() + } + } + }, + AbortSignalAny: + AbortSignal.any || + function AbortSignalAny(signals) { + // Fast path if there is only one signal. + if (signals.length === 1) { + return signals[0] + } + const ac = new AbortController() + const abort = () => ac.abort() + signals.forEach((signal) => { + validateAbortSignal(signal, 'signals') + signal.addEventListener('abort', abort, { + once: true + }) + }) + ac.signal.addEventListener( + 'abort', + () => { + signals.forEach((signal) => signal.removeEventListener('abort', abort)) + }, + { + once: true + } + ) + return ac.signal + } } +module.exports.promisify.custom = Symbol.for('nodejs.util.promisify.custom') -const INTERNALS$1 = Symbol('Response internals'); -// fix an issue where "STATUS_CODES" aren't a named export for node <10 -const STATUS_CODES = http.STATUS_CODES; +/***/ }), -/** - * Response class - * - * @param Stream body Readable stream - * @param Object opts Response options - * @return Void - */ -class Response { - constructor() { - let body = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; - let opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; +/***/ 75102: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - Body.call(this, body, opts); +/* replacement start */ - const status = opts.status || 200; - const headers = new Headers(opts.headers); +const { Buffer } = __nccwpck_require__(14300) - if (body != null && !headers.has('Content-Type')) { - const contentType = extractContentType(body); - if (contentType) { - headers.append('Content-Type', contentType); - } - } +/* replacement end */ +// Copyright Joyent, Inc. and other Node contributors. +// +// Permission is hereby granted, free of charge, to any person obtaining a +// copy of this software and associated documentation files (the +// "Software"), to deal in the Software without restriction, including +// without limitation the rights to use, copy, modify, merge, publish, +// distribute, sublicense, and/or sell copies of the Software, and to permit +// persons to whom the Software is furnished to do so, subject to the +// following conditions: +// +// The above copyright notice and this permission notice shall be included +// in all copies or substantial portions of the Software. +// +// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN +// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, +// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR +// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE +// USE OR OTHER DEALINGS IN THE SOFTWARE. - this[INTERNALS$1] = { - url: opts.url, - status, - statusText: opts.statusText || STATUS_CODES[status], - headers, - counter: opts.counter - }; - } +;('use strict') +const { ObjectDefineProperty, ObjectKeys, ReflectApply } = __nccwpck_require__(89629) +const { + promisify: { custom: customPromisify } +} = __nccwpck_require__(46959) +const { streamReturningOperators, promiseReturningOperators } = __nccwpck_require__(63193) +const { + codes: { ERR_ILLEGAL_CONSTRUCTOR } +} = __nccwpck_require__(80529) +const compose = __nccwpck_require__(63129) +const { setDefaultHighWaterMark, getDefaultHighWaterMark } = __nccwpck_require__(39948) +const { pipeline } = __nccwpck_require__(76989) +const { destroyer } = __nccwpck_require__(97049) +const eos = __nccwpck_require__(76080) +const internalBuffer = {} +const promises = __nccwpck_require__(348) +const utils = __nccwpck_require__(27981) +const Stream = (module.exports = __nccwpck_require__(49792).Stream) +Stream.isDestroyed = utils.isDestroyed +Stream.isDisturbed = utils.isDisturbed +Stream.isErrored = utils.isErrored +Stream.isReadable = utils.isReadable +Stream.isWritable = utils.isWritable +Stream.Readable = __nccwpck_require__(57920) +for (const key of ObjectKeys(streamReturningOperators)) { + const op = streamReturningOperators[key] + function fn(...args) { + if (new.target) { + throw ERR_ILLEGAL_CONSTRUCTOR() + } + return Stream.Readable.from(ReflectApply(op, this, args)) + } + ObjectDefineProperty(fn, 'name', { + __proto__: null, + value: op.name + }) + ObjectDefineProperty(fn, 'length', { + __proto__: null, + value: op.length + }) + ObjectDefineProperty(Stream.Readable.prototype, key, { + __proto__: null, + value: fn, + enumerable: false, + configurable: true, + writable: true + }) +} +for (const key of ObjectKeys(promiseReturningOperators)) { + const op = promiseReturningOperators[key] + function fn(...args) { + if (new.target) { + throw ERR_ILLEGAL_CONSTRUCTOR() + } + return ReflectApply(op, this, args) + } + ObjectDefineProperty(fn, 'name', { + __proto__: null, + value: op.name + }) + ObjectDefineProperty(fn, 'length', { + __proto__: null, + value: op.length + }) + ObjectDefineProperty(Stream.Readable.prototype, key, { + __proto__: null, + value: fn, + enumerable: false, + configurable: true, + writable: true + }) +} +Stream.Writable = __nccwpck_require__(48488) +Stream.Duplex = __nccwpck_require__(72613) +Stream.Transform = __nccwpck_require__(86941) +Stream.PassThrough = __nccwpck_require__(72839) +Stream.pipeline = pipeline +const { addAbortSignal } = __nccwpck_require__(80289) +Stream.addAbortSignal = addAbortSignal +Stream.finished = eos +Stream.destroy = destroyer +Stream.compose = compose +Stream.setDefaultHighWaterMark = setDefaultHighWaterMark +Stream.getDefaultHighWaterMark = getDefaultHighWaterMark +ObjectDefineProperty(Stream, 'promises', { + __proto__: null, + configurable: true, + enumerable: true, + get() { + return promises + } +}) +ObjectDefineProperty(pipeline, customPromisify, { + __proto__: null, + enumerable: true, + get() { + return promises.pipeline + } +}) +ObjectDefineProperty(eos, customPromisify, { + __proto__: null, + enumerable: true, + get() { + return promises.finished + } +}) - get url() { - return this[INTERNALS$1].url || ''; - } +// Backwards-compat with node 0.4.x +Stream.Stream = Stream +Stream._isUint8Array = function isUint8Array(value) { + return value instanceof Uint8Array +} +Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) +} - get status() { - return this[INTERNALS$1].status; - } - /** - * Convenience property representing if the request ended normally - */ - get ok() { - return this[INTERNALS$1].status >= 200 && this[INTERNALS$1].status < 300; - } +/***/ }), - get redirected() { - return this[INTERNALS$1].counter > 0; - } +/***/ 348: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - get statusText() { - return this[INTERNALS$1].statusText; - } +"use strict"; - get headers() { - return this[INTERNALS$1].headers; - } - /** - * Clone this response - * - * @return Response - */ - clone() { - return new Response(clone(this), { - url: this.url, - status: this.status, - statusText: this.statusText, - headers: this.headers, - ok: this.ok, - redirected: this.redirected - }); - } +const { ArrayPrototypePop, Promise } = __nccwpck_require__(89629) +const { isIterable, isNodeStream, isWebStream } = __nccwpck_require__(27981) +const { pipelineImpl: pl } = __nccwpck_require__(76989) +const { finished } = __nccwpck_require__(76080) +__nccwpck_require__(75102) +function pipeline(...streams) { + return new Promise((resolve, reject) => { + let signal + let end + const lastArg = streams[streams.length - 1] + if ( + lastArg && + typeof lastArg === 'object' && + !isNodeStream(lastArg) && + !isIterable(lastArg) && + !isWebStream(lastArg) + ) { + const options = ArrayPrototypePop(streams) + signal = options.signal + end = options.end + } + pl( + streams, + (err, value) => { + if (err) { + reject(err) + } else { + resolve(value) + } + }, + { + signal, + end + } + ) + }) +} +module.exports = { + finished, + pipeline } -Body.mixIn(Response.prototype); - -Object.defineProperties(Response.prototype, { - url: { enumerable: true }, - status: { enumerable: true }, - ok: { enumerable: true }, - redirected: { enumerable: true }, - statusText: { enumerable: true }, - headers: { enumerable: true }, - clone: { enumerable: true } -}); -Object.defineProperty(Response.prototype, Symbol.toStringTag, { - value: 'Response', - writable: false, - enumerable: false, - configurable: true -}); +/***/ }), -const INTERNALS$2 = Symbol('Request internals'); -const URL = Url.URL || whatwgUrl.URL; +/***/ 44967: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// fix an issue where "format", "parse" aren't a named export for node <10 -const parse_url = Url.parse; -const format_url = Url.format; +module.exports = readdirGlob; -/** - * Wrapper around `new URL` to handle arbitrary URLs - * - * @param {string} urlStr - * @return {void} - */ -function parseURL(urlStr) { - /* - Check whether the URL is absolute or not - Scheme: https://tools.ietf.org/html/rfc3986#section-3.1 - Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3 - */ - if (/^[a-zA-Z][a-zA-Z\d+\-.]*:/.exec(urlStr)) { - urlStr = new URL(urlStr).toString(); - } +const fs = __nccwpck_require__(57147); +const { EventEmitter } = __nccwpck_require__(82361); +const { Minimatch } = __nccwpck_require__(27771); +const { resolve } = __nccwpck_require__(71017); - // Fallback to old implementation for arbitrary URLs - return parse_url(urlStr); +function readdir(dir, strict) { + return new Promise((resolve, reject) => { + fs.readdir(dir, {withFileTypes: true} ,(err, files) => { + if(err) { + switch (err.code) { + case 'ENOTDIR': // Not a directory + if(strict) { + reject(err); + } else { + resolve([]); + } + break; + case 'ENOTSUP': // Operation not supported + case 'ENOENT': // No such file or directory + case 'ENAMETOOLONG': // Filename too long + case 'UNKNOWN': + resolve([]); + break; + case 'ELOOP': // Too many levels of symbolic links + default: + reject(err); + break; + } + } else { + resolve(files); + } + }); + }); +} +function stat(file, followSymlinks) { + return new Promise((resolve, reject) => { + const statFunc = followSymlinks ? fs.stat : fs.lstat; + statFunc(file, (err, stats) => { + if(err) { + switch (err.code) { + case 'ENOENT': + if(followSymlinks) { + // Fallback to lstat to handle broken links as files + resolve(stat(file, false)); + } else { + resolve(null); + } + break; + default: + resolve(null); + break; + } + } else { + resolve(stats); + } + }); + }); } -const streamDestructionSupported = 'destroy' in Stream.Readable.prototype; +async function* exploreWalkAsync(dir, path, followSymlinks, useStat, shouldSkip, strict) { + let files = await readdir(path + dir, strict); + for(const file of files) { + let name = file.name; + if(name === undefined) { + // undefined file.name means the `withFileTypes` options is not supported by node + // we have to call the stat function to know if file is directory or not. + name = file; + useStat = true; + } + const filename = dir + '/' + name; + const relative = filename.slice(1); // Remove the leading / + const absolute = path + '/' + relative; + let stats = null; + if(useStat || followSymlinks) { + stats = await stat(absolute, followSymlinks); + } + if(!stats && file.name !== undefined) { + stats = file; + } + if(stats === null) { + stats = { isDirectory: () => false }; + } -/** - * Check if a value is an instance of Request. - * - * @param Mixed input - * @return Boolean - */ -function isRequest(input) { - return typeof input === 'object' && typeof input[INTERNALS$2] === 'object'; + if(stats.isDirectory()) { + if(!shouldSkip(relative)) { + yield {relative, absolute, stats}; + yield* exploreWalkAsync(filename, path, followSymlinks, useStat, shouldSkip, false); + } + } else { + yield {relative, absolute, stats}; + } + } } - -function isAbortSignal(signal) { - const proto = signal && typeof signal === 'object' && Object.getPrototypeOf(signal); - return !!(proto && proto.constructor.name === 'AbortSignal'); +async function* explore(path, followSymlinks, useStat, shouldSkip) { + yield* exploreWalkAsync('', path, followSymlinks, useStat, shouldSkip, true); } -/** - * Request class - * - * @param Mixed input Url or Request instance - * @param Object init Custom options - * @return Void - */ -class Request { - constructor(input) { - let init = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; - let parsedURL; +function readOptions(options) { + return { + pattern: options.pattern, + dot: !!options.dot, + noglobstar: !!options.noglobstar, + matchBase: !!options.matchBase, + nocase: !!options.nocase, + ignore: options.ignore, + skip: options.skip, - // normalize input - if (!isRequest(input)) { - if (input && input.href) { - // in order to support Node.js' Url objects; though WHATWG's URL objects - // will fall into this branch also (since their `toString()` will return - // `href` property anyway) - parsedURL = parseURL(input.href); - } else { - // coerce input to a string before attempting to parse - parsedURL = parseURL(`${input}`); - } - input = {}; - } else { - parsedURL = parseURL(input.url); - } + follow: !!options.follow, + stat: !!options.stat, + nodir: !!options.nodir, + mark: !!options.mark, + silent: !!options.silent, + absolute: !!options.absolute + }; +} - let method = init.method || input.method || 'GET'; - method = method.toUpperCase(); +class ReaddirGlob extends EventEmitter { + constructor(cwd, options, cb) { + super(); + if(typeof options === 'function') { + cb = options; + options = null; + } - if ((init.body != null || isRequest(input) && input.body !== null) && (method === 'GET' || method === 'HEAD')) { - throw new TypeError('Request with GET/HEAD method cannot have body'); - } + this.options = readOptions(options || {}); + + this.matchers = []; + if(this.options.pattern) { + const matchers = Array.isArray(this.options.pattern) ? this.options.pattern : [this.options.pattern]; + this.matchers = matchers.map( m => + new Minimatch(m, { + dot: this.options.dot, + noglobstar:this.options.noglobstar, + matchBase:this.options.matchBase, + nocase:this.options.nocase + }) + ); + } + + this.ignoreMatchers = []; + if(this.options.ignore) { + const ignorePatterns = Array.isArray(this.options.ignore) ? this.options.ignore : [this.options.ignore]; + this.ignoreMatchers = ignorePatterns.map( ignore => + new Minimatch(ignore, {dot: true}) + ); + } + + this.skipMatchers = []; + if(this.options.skip) { + const skipPatterns = Array.isArray(this.options.skip) ? this.options.skip : [this.options.skip]; + this.skipMatchers = skipPatterns.map( skip => + new Minimatch(skip, {dot: true}) + ); + } - let inputBody = init.body != null ? init.body : isRequest(input) && input.body !== null ? clone(input) : null; + this.iterator = explore(resolve(cwd || '.'), this.options.follow, this.options.stat, this._shouldSkipDirectory.bind(this)); + this.paused = false; + this.inactive = false; + this.aborted = false; + + if(cb) { + this._matches = []; + this.on('match', match => this._matches.push(this.options.absolute ? match.absolute : match.relative)); + this.on('error', err => cb(err)); + this.on('end', () => cb(null, this._matches)); + } - Body.call(this, inputBody, { - timeout: init.timeout || input.timeout || 0, - size: init.size || input.size || 0 - }); + setTimeout( () => this._next(), 0); + } - const headers = new Headers(init.headers || input.headers || {}); + _shouldSkipDirectory(relative) { + //console.log(relative, this.skipMatchers.some(m => m.match(relative))); + return this.skipMatchers.some(m => m.match(relative)); + } - if (inputBody != null && !headers.has('Content-Type')) { - const contentType = extractContentType(inputBody); - if (contentType) { - headers.append('Content-Type', contentType); - } - } + _fileMatches(relative, isDirectory) { + const file = relative + (isDirectory ? '/' : ''); + return (this.matchers.length === 0 || this.matchers.some(m => m.match(file))) + && !this.ignoreMatchers.some(m => m.match(file)) + && (!this.options.nodir || !isDirectory); + } - let signal = isRequest(input) ? input.signal : null; - if ('signal' in init) signal = init.signal; + _next() { + if(!this.paused && !this.aborted) { + this.iterator.next() + .then((obj)=> { + if(!obj.done) { + const isDirectory = obj.value.stats.isDirectory(); + if(this._fileMatches(obj.value.relative, isDirectory )) { + let relative = obj.value.relative; + let absolute = obj.value.absolute; + if(this.options.mark && isDirectory) { + relative += '/'; + absolute += '/'; + } + if(this.options.stat) { + this.emit('match', {relative, absolute, stat:obj.value.stats}); + } else { + this.emit('match', {relative, absolute}); + } + } + this._next(this.iterator); + } else { + this.emit('end'); + } + }) + .catch((err) => { + this.abort(); + this.emit('error', err); + if(!err.code && !this.options.silent) { + console.error(err); + } + }); + } else { + this.inactive = true; + } + } - if (signal != null && !isAbortSignal(signal)) { - throw new TypeError('Expected signal to be an instanceof AbortSignal'); - } + abort() { + this.aborted = true; + } - this[INTERNALS$2] = { - method, - redirect: init.redirect || input.redirect || 'follow', - headers, - parsedURL, - signal - }; + pause() { + this.paused = true; + } - // node-fetch-only options - this.follow = init.follow !== undefined ? init.follow : input.follow !== undefined ? input.follow : 20; - this.compress = init.compress !== undefined ? init.compress : input.compress !== undefined ? input.compress : true; - this.counter = init.counter || input.counter || 0; - this.agent = init.agent || input.agent; - } + resume() { + this.paused = false; + if(this.inactive) { + this.inactive = false; + this._next(); + } + } +} - get method() { - return this[INTERNALS$2].method; - } - get url() { - return format_url(this[INTERNALS$2].parsedURL); - } +function readdirGlob(pattern, options, cb) { + return new ReaddirGlob(pattern, options, cb); +} +readdirGlob.ReaddirGlob = ReaddirGlob; - get headers() { - return this[INTERNALS$2].headers; - } +/***/ }), - get redirect() { - return this[INTERNALS$2].redirect; - } +/***/ 79482: +/***/ ((module) => { - get signal() { - return this[INTERNALS$2].signal; - } +const isWindows = typeof process === 'object' && + process && + process.platform === 'win32' +module.exports = isWindows ? { sep: '\\' } : { sep: '/' } - /** - * Clone this request - * - * @return Request - */ - clone() { - return new Request(this); - } + +/***/ }), + +/***/ 27771: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const minimatch = module.exports = (p, pattern, options = {}) => { + assertValidPattern(pattern) + + // shortcut: comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + return false + } + + return new Minimatch(pattern, options).match(p) } -Body.mixIn(Request.prototype); +module.exports = minimatch -Object.defineProperty(Request.prototype, Symbol.toStringTag, { - value: 'Request', - writable: false, - enumerable: false, - configurable: true -}); +const path = __nccwpck_require__(79482) +minimatch.sep = path.sep -Object.defineProperties(Request.prototype, { - method: { enumerable: true }, - url: { enumerable: true }, - headers: { enumerable: true }, - redirect: { enumerable: true }, - clone: { enumerable: true }, - signal: { enumerable: true } -}); +const GLOBSTAR = Symbol('globstar **') +minimatch.GLOBSTAR = GLOBSTAR +const expand = __nccwpck_require__(33717) -/** - * Convert a Request to Node.js http request options. - * - * @param Request A Request instance - * @return Object The options object to be passed to http.request - */ -function getNodeRequestOptions(request) { - const parsedURL = request[INTERNALS$2].parsedURL; - const headers = new Headers(request[INTERNALS$2].headers); +const plTypes = { + '!': { open: '(?:(?!(?:', close: '))[^/]*?)'}, + '?': { open: '(?:', close: ')?' }, + '+': { open: '(?:', close: ')+' }, + '*': { open: '(?:', close: ')*' }, + '@': { open: '(?:', close: ')' } +} - // fetch step 1.3 - if (!headers.has('Accept')) { - headers.set('Accept', '*/*'); - } +// any single thing other than / +// don't need to escape / when using new RegExp() +const qmark = '[^/]' - // Basic fetch - if (!parsedURL.protocol || !parsedURL.hostname) { - throw new TypeError('Only absolute URLs are supported'); - } +// * => any number of characters +const star = qmark + '*?' - if (!/^https?:$/.test(parsedURL.protocol)) { - throw new TypeError('Only HTTP(S) protocols are supported'); - } +// ** when dots are allowed. Anything goes, except .. and . +// not (^ or / followed by one or two dots followed by $ or /), +// followed by anything, any number of times. +const twoStarDot = '(?:(?!(?:\\\/|^)(?:\\.{1,2})($|\\\/)).)*?' - if (request.signal && request.body instanceof Stream.Readable && !streamDestructionSupported) { - throw new Error('Cancellation of streamed requests with AbortSignal is not supported in node < 8'); - } +// not a ^ or / followed by a dot, +// followed by anything, any number of times. +const twoStarNoDot = '(?:(?!(?:\\\/|^)\\.).)*?' - // HTTP-network-or-cache fetch steps 2.4-2.7 - let contentLengthValue = null; - if (request.body == null && /^(POST|PUT)$/i.test(request.method)) { - contentLengthValue = '0'; - } - if (request.body != null) { - const totalBytes = getTotalBytes(request); - if (typeof totalBytes === 'number') { - contentLengthValue = String(totalBytes); - } - } - if (contentLengthValue) { - headers.set('Content-Length', contentLengthValue); - } +// "abc" -> { a:true, b:true, c:true } +const charSet = s => s.split('').reduce((set, c) => { + set[c] = true + return set +}, {}) - // HTTP-network-or-cache fetch step 2.11 - if (!headers.has('User-Agent')) { - headers.set('User-Agent', 'node-fetch/1.0 (+https://github.com/bitinn/node-fetch)'); - } +// characters that need to be escaped in RegExp. +const reSpecials = charSet('().*{}+?[]^$\\!') - // HTTP-network-or-cache fetch step 2.15 - if (request.compress && !headers.has('Accept-Encoding')) { - headers.set('Accept-Encoding', 'gzip,deflate'); - } +// characters that indicate we have to add the pattern start +const addPatternStartSet = charSet('[.(') - let agent = request.agent; - if (typeof agent === 'function') { - agent = agent(parsedURL); - } +// normalizes slashes. +const slashSplit = /\/+/ - // HTTP-network fetch step 4.2 - // chunked encoding is handled by Node.js +minimatch.filter = (pattern, options = {}) => + (p, i, list) => minimatch(p, pattern, options) - return Object.assign({}, parsedURL, { - method: request.method, - headers: exportNodeCompatibleHeaders(headers), - agent - }); +const ext = (a, b = {}) => { + const t = {} + Object.keys(a).forEach(k => t[k] = a[k]) + Object.keys(b).forEach(k => t[k] = b[k]) + return t } -/** - * abort-error.js - * - * AbortError interface for cancelled requests - */ +minimatch.defaults = def => { + if (!def || typeof def !== 'object' || !Object.keys(def).length) { + return minimatch + } -/** - * Create AbortError instance - * - * @param String message Error message for human - * @return AbortError - */ -function AbortError(message) { - Error.call(this, message); + const orig = minimatch - this.type = 'aborted'; - this.message = message; + const m = (p, pattern, options) => orig(p, pattern, ext(def, options)) + m.Minimatch = class Minimatch extends orig.Minimatch { + constructor (pattern, options) { + super(pattern, ext(def, options)) + } + } + m.Minimatch.defaults = options => orig.defaults(ext(def, options)).Minimatch + m.filter = (pattern, options) => orig.filter(pattern, ext(def, options)) + m.defaults = options => orig.defaults(ext(def, options)) + m.makeRe = (pattern, options) => orig.makeRe(pattern, ext(def, options)) + m.braceExpand = (pattern, options) => orig.braceExpand(pattern, ext(def, options)) + m.match = (list, pattern, options) => orig.match(list, pattern, ext(def, options)) - // hide custom error implementation details from end-users - Error.captureStackTrace(this, this.constructor); + return m } -AbortError.prototype = Object.create(Error.prototype); -AbortError.prototype.constructor = AbortError; -AbortError.prototype.name = 'AbortError'; -const URL$1 = Url.URL || whatwgUrl.URL; -// fix an issue where "PassThrough", "resolve" aren't a named export for node <10 -const PassThrough$1 = Stream.PassThrough; -const isDomainOrSubdomain = function isDomainOrSubdomain(destination, original) { - const orig = new URL$1(original).hostname; - const dest = new URL$1(destination).hostname; - return orig === dest || orig[orig.length - dest.length - 1] === '.' && orig.endsWith(dest); -}; +// Brace expansion: +// a{b,c}d -> abd acd +// a{b,}c -> abc ac +// a{0..3}d -> a0d a1d a2d a3d +// a{b,c{d,e}f}g -> abg acdfg acefg +// a{b,c}d{e,f}g -> abdeg acdeg abdeg abdfg +// +// Invalid sets are not expanded. +// a{2..}b -> a{2..}b +// a{b}c -> a{b}c +minimatch.braceExpand = (pattern, options) => braceExpand(pattern, options) -/** - * isSameProtocol reports whether the two provided URLs use the same protocol. - * - * Both domains must already be in canonical form. - * @param {string|URL} original - * @param {string|URL} destination - */ -const isSameProtocol = function isSameProtocol(destination, original) { - const orig = new URL$1(original).protocol; - const dest = new URL$1(destination).protocol; +const braceExpand = (pattern, options = {}) => { + assertValidPattern(pattern) - return orig === dest; -}; + // Thanks to Yeting Li for + // improving this regexp to avoid a ReDOS vulnerability. + if (options.nobrace || !/\{(?:(?!\{).)*\}/.test(pattern)) { + // shortcut. no need to expand. + return [pattern] + } -/** - * Fetch function - * - * @param Mixed url Absolute url or Request instance - * @param Object opts Fetch options - * @return Promise - */ -function fetch(url, opts) { + return expand(pattern) +} - // allow custom promise - if (!fetch.Promise) { - throw new Error('native promise missing, set fetch.Promise to your favorite alternative'); - } +const MAX_PATTERN_LENGTH = 1024 * 64 +const assertValidPattern = pattern => { + if (typeof pattern !== 'string') { + throw new TypeError('invalid pattern') + } - Body.Promise = fetch.Promise; + if (pattern.length > MAX_PATTERN_LENGTH) { + throw new TypeError('pattern is too long') + } +} - // wrap http.request into fetch - return new fetch.Promise(function (resolve, reject) { - // build request object - const request = new Request(url, opts); - const options = getNodeRequestOptions(request); +// parse a component of the expanded set. +// At this point, no pattern may contain "/" in it +// so we're going to return a 2d array, where each entry is the full +// pattern, split on '/', and then turned into a regular expression. +// A regexp is made at the end which joins each array with an +// escaped /, and another full one which joins each regexp with |. +// +// Following the lead of Bash 4.1, note that "**" only has special meaning +// when it is the *only* thing in a path portion. Otherwise, any series +// of * is equivalent to a single *. Globstar behavior is enabled by +// default, and can be disabled by setting options.noglobstar. +const SUBPARSE = Symbol('subparse') - const send = (options.protocol === 'https:' ? https : http).request; - const signal = request.signal; +minimatch.makeRe = (pattern, options) => + new Minimatch(pattern, options || {}).makeRe() - let response = null; +minimatch.match = (list, pattern, options = {}) => { + const mm = new Minimatch(pattern, options) + list = list.filter(f => mm.match(f)) + if (mm.options.nonull && !list.length) { + list.push(pattern) + } + return list +} - const abort = function abort() { - let error = new AbortError('The user aborted a request.'); - reject(error); - if (request.body && request.body instanceof Stream.Readable) { - destroyStream(request.body, error); - } - if (!response || !response.body) return; - response.body.emit('error', error); - }; +// replace stuff like \* with * +const globUnescape = s => s.replace(/\\(.)/g, '$1') +const charUnescape = s => s.replace(/\\([^-\]])/g, '$1') +const regExpEscape = s => s.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, '\\$&') +const braExpEscape = s => s.replace(/[[\]\\]/g, '\\$&') - if (signal && signal.aborted) { - abort(); - return; - } +class Minimatch { + constructor (pattern, options) { + assertValidPattern(pattern) - const abortAndFinalize = function abortAndFinalize() { - abort(); - finalize(); - }; + if (!options) options = {} - // send request - const req = send(options); - let reqTimeout; + this.options = options + this.set = [] + this.pattern = pattern + this.windowsPathsNoEscape = !!options.windowsPathsNoEscape || + options.allowWindowsEscape === false + if (this.windowsPathsNoEscape) { + this.pattern = this.pattern.replace(/\\/g, '/') + } + this.regexp = null + this.negate = false + this.comment = false + this.empty = false + this.partial = !!options.partial - if (signal) { - signal.addEventListener('abort', abortAndFinalize); - } + // make the set of regexps etc. + this.make() + } - function finalize() { - req.abort(); - if (signal) signal.removeEventListener('abort', abortAndFinalize); - clearTimeout(reqTimeout); - } + debug () {} - if (request.timeout) { - req.once('socket', function (socket) { - reqTimeout = setTimeout(function () { - reject(new FetchError(`network timeout at: ${request.url}`, 'request-timeout')); - finalize(); - }, request.timeout); - }); - } + make () { + const pattern = this.pattern + const options = this.options - req.on('error', function (err) { - reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err)); + // empty patterns and comments match nothing. + if (!options.nocomment && pattern.charAt(0) === '#') { + this.comment = true + return + } + if (!pattern) { + this.empty = true + return + } - if (response && response.body) { - destroyStream(response.body, err); - } + // step 1: figure out negation, etc. + this.parseNegate() - finalize(); - }); + // step 2: expand braces + let set = this.globSet = this.braceExpand() - fixResponseChunkedTransferBadEnding(req, function (err) { - if (signal && signal.aborted) { - return; - } + if (options.debug) this.debug = (...args) => console.error(...args) - if (response && response.body) { - destroyStream(response.body, err); - } - }); + this.debug(this.pattern, set) - /* c8 ignore next 18 */ - if (parseInt(process.version.substring(1)) < 14) { - // Before Node.js 14, pipeline() does not fully support async iterators and does not always - // properly handle when the socket close/end events are out of order. - req.on('socket', function (s) { - s.addListener('close', function (hadError) { - // if a data listener is still present we didn't end cleanly - const hasDataListener = s.listenerCount('data') > 0; + // step 3: now we have a set, so turn each one into a series of path-portion + // matching patterns. + // These will be regexps, except in the case of "**", which is + // set to the GLOBSTAR object for globstar behavior, + // and will not contain any / characters + set = this.globParts = set.map(s => s.split(slashSplit)) - // if end happened before close but the socket didn't emit an error, do it now - if (response && hasDataListener && !hadError && !(signal && signal.aborted)) { - const err = new Error('Premature close'); - err.code = 'ERR_STREAM_PREMATURE_CLOSE'; - response.body.emit('error', err); - } - }); - }); - } + this.debug(this.pattern, set) - req.on('response', function (res) { - clearTimeout(reqTimeout); + // glob --> regexps + set = set.map((s, si, set) => s.map(this.parse, this)) - const headers = createHeadersLenient(res.headers); + this.debug(this.pattern, set) - // HTTP fetch step 5 - if (fetch.isRedirect(res.statusCode)) { - // HTTP fetch step 5.2 - const location = headers.get('Location'); + // filter out everything that didn't compile properly. + set = set.filter(s => s.indexOf(false) === -1) - // HTTP fetch step 5.3 - let locationURL = null; - try { - locationURL = location === null ? null : new URL$1(location, request.url).toString(); - } catch (err) { - // error here can only be invalid URL in Location: header - // do not throw when options.redirect == manual - // let the user extract the errorneous redirect URL - if (request.redirect !== 'manual') { - reject(new FetchError(`uri requested responds with an invalid redirect URL: ${location}`, 'invalid-redirect')); - finalize(); - return; - } - } - - // HTTP fetch step 5.5 - switch (request.redirect) { - case 'error': - reject(new FetchError(`uri requested responds with a redirect, redirect mode is set to error: ${request.url}`, 'no-redirect')); - finalize(); - return; - case 'manual': - // node-fetch-specific step: make manual redirect a bit easier to use by setting the Location header value to the resolved URL. - if (locationURL !== null) { - // handle corrupted header - try { - headers.set('Location', locationURL); - } catch (err) { - // istanbul ignore next: nodejs server prevent invalid response headers, we can't test this through normal request - reject(err); - } - } - break; - case 'follow': - // HTTP-redirect fetch step 2 - if (locationURL === null) { - break; - } - - // HTTP-redirect fetch step 5 - if (request.counter >= request.follow) { - reject(new FetchError(`maximum redirect reached at: ${request.url}`, 'max-redirect')); - finalize(); - return; - } - - // HTTP-redirect fetch step 6 (counter increment) - // Create a new Request object. - const requestOpts = { - headers: new Headers(request.headers), - follow: request.follow, - counter: request.counter + 1, - agent: request.agent, - compress: request.compress, - method: request.method, - body: request.body, - signal: request.signal, - timeout: request.timeout, - size: request.size - }; - - if (!isDomainOrSubdomain(request.url, locationURL) || !isSameProtocol(request.url, locationURL)) { - for (const name of ['authorization', 'www-authenticate', 'cookie', 'cookie2']) { - requestOpts.headers.delete(name); - } - } + this.debug(this.pattern, set) - // HTTP-redirect fetch step 9 - if (res.statusCode !== 303 && request.body && getTotalBytes(request) === null) { - reject(new FetchError('Cannot follow redirect with body being a readable stream', 'unsupported-redirect')); - finalize(); - return; - } + this.set = set + } - // HTTP-redirect fetch step 11 - if (res.statusCode === 303 || (res.statusCode === 301 || res.statusCode === 302) && request.method === 'POST') { - requestOpts.method = 'GET'; - requestOpts.body = undefined; - requestOpts.headers.delete('content-length'); - } + parseNegate () { + if (this.options.nonegate) return - // HTTP-redirect fetch step 15 - resolve(fetch(new Request(locationURL, requestOpts))); - finalize(); - return; - } - } + const pattern = this.pattern + let negate = false + let negateOffset = 0 - // prepare response - res.once('end', function () { - if (signal) signal.removeEventListener('abort', abortAndFinalize); - }); - let body = res.pipe(new PassThrough$1()); + for (let i = 0; i < pattern.length && pattern.charAt(i) === '!'; i++) { + negate = !negate + negateOffset++ + } - const response_options = { - url: request.url, - status: res.statusCode, - statusText: res.statusMessage, - headers: headers, - size: request.size, - timeout: request.timeout, - counter: request.counter - }; + if (negateOffset) this.pattern = pattern.slice(negateOffset) + this.negate = negate + } - // HTTP-network fetch step 12.1.1.3 - const codings = headers.get('Content-Encoding'); + // set partial to true to test if, for example, + // "/a/b" matches the start of "/*/b/*/d" + // Partial means, if you run out of file before you run + // out of pattern, then that's fine, as long as all + // the parts match. + matchOne (file, pattern, partial) { + var options = this.options - // HTTP-network fetch step 12.1.1.4: handle content codings + this.debug('matchOne', + { 'this': this, file: file, pattern: pattern }) - // in following scenarios we ignore compression support - // 1. compression support is disabled - // 2. HEAD request - // 3. no Content-Encoding header - // 4. no content response (204) - // 5. content not modified response (304) - if (!request.compress || request.method === 'HEAD' || codings === null || res.statusCode === 204 || res.statusCode === 304) { - response = new Response(body, response_options); - resolve(response); - return; - } + this.debug('matchOne', file.length, pattern.length) - // For Node v6+ - // Be less strict when decoding compressed responses, since sometimes - // servers send slightly invalid responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - const zlibOptions = { - flush: zlib.Z_SYNC_FLUSH, - finishFlush: zlib.Z_SYNC_FLUSH - }; + for (var fi = 0, + pi = 0, + fl = file.length, + pl = pattern.length + ; (fi < fl) && (pi < pl) + ; fi++, pi++) { + this.debug('matchOne loop') + var p = pattern[pi] + var f = file[fi] - // for gzip - if (codings == 'gzip' || codings == 'x-gzip') { - body = body.pipe(zlib.createGunzip(zlibOptions)); - response = new Response(body, response_options); - resolve(response); - return; - } + this.debug(pattern, p, f) - // for deflate - if (codings == 'deflate' || codings == 'x-deflate') { - // handle the infamous raw deflate response from old servers - // a hack for old IIS and Apache servers - const raw = res.pipe(new PassThrough$1()); - raw.once('data', function (chunk) { - // see http://stackoverflow.com/questions/37519828 - if ((chunk[0] & 0x0F) === 0x08) { - body = body.pipe(zlib.createInflate()); - } else { - body = body.pipe(zlib.createInflateRaw()); - } - response = new Response(body, response_options); - resolve(response); - }); - raw.on('end', function () { - // some old IIS servers return zero-length OK deflate responses, so 'data' is never emitted. - if (!response) { - response = new Response(body, response_options); - resolve(response); - } - }); - return; - } + // should be impossible. + // some invalid regexp stuff in the set. + /* istanbul ignore if */ + if (p === false) return false - // for br - if (codings == 'br' && typeof zlib.createBrotliDecompress === 'function') { - body = body.pipe(zlib.createBrotliDecompress()); - response = new Response(body, response_options); - resolve(response); - return; - } + if (p === GLOBSTAR) { + this.debug('GLOBSTAR', [pattern, p, f]) - // otherwise, use response as-is - response = new Response(body, response_options); - resolve(response); - }); + // "**" + // a/**/b/**/c would match the following: + // a/b/x/y/z/c + // a/x/y/z/b/c + // a/b/x/b/x/c + // a/b/c + // To do this, take the rest of the pattern after + // the **, and see if it would match the file remainder. + // If so, return success. + // If not, the ** "swallows" a segment, and try again. + // This is recursively awful. + // + // a/**/b/**/c matching a/b/x/y/z/c + // - a matches a + // - doublestar + // - matchOne(b/x/y/z/c, b/**/c) + // - b matches b + // - doublestar + // - matchOne(x/y/z/c, c) -> no + // - matchOne(y/z/c, c) -> no + // - matchOne(z/c, c) -> no + // - matchOne(c, c) yes, hit + var fr = fi + var pr = pi + 1 + if (pr === pl) { + this.debug('** at the end') + // a ** at the end will just swallow the rest. + // We have found a match. + // however, it will not swallow /.x, unless + // options.dot is set. + // . and .. are *never* matched by **, for explosively + // exponential reasons. + for (; fi < fl; fi++) { + if (file[fi] === '.' || file[fi] === '..' || + (!options.dot && file[fi].charAt(0) === '.')) return false + } + return true + } - writeToStream(req, request); - }); -} -function fixResponseChunkedTransferBadEnding(request, errorCallback) { - let socket; + // ok, let's see if we can swallow whatever we can. + while (fr < fl) { + var swallowee = file[fr] - request.on('socket', function (s) { - socket = s; - }); + this.debug('\nglobstar while', file, fr, pattern, pr, swallowee) - request.on('response', function (response) { - const headers = response.headers; + // XXX remove this slice. Just pass the start index. + if (this.matchOne(file.slice(fr), pattern.slice(pr), partial)) { + this.debug('globstar found match!', fr, fl, swallowee) + // found a match. + return true + } else { + // can't swallow "." or ".." ever. + // can only swallow ".foo" when explicitly asked. + if (swallowee === '.' || swallowee === '..' || + (!options.dot && swallowee.charAt(0) === '.')) { + this.debug('dot detected!', file, fr, pattern, pr) + break + } - if (headers['transfer-encoding'] === 'chunked' && !headers['content-length']) { - response.once('close', function (hadError) { - // tests for socket presence, as in some situations the - // the 'socket' event is not triggered for the request - // (happens in deno), avoids `TypeError` - // if a data listener is still present we didn't end cleanly - const hasDataListener = socket && socket.listenerCount('data') > 0; + // ** swallows a segment, and continue. + this.debug('globstar swallow a segment, and continue') + fr++ + } + } - if (hasDataListener && !hadError) { - const err = new Error('Premature close'); - err.code = 'ERR_STREAM_PREMATURE_CLOSE'; - errorCallback(err); - } - }); - } - }); -} + // no match was found. + // However, in partial mode, we can't say this is necessarily over. + // If there's more *pattern* left, then + /* istanbul ignore if */ + if (partial) { + // ran out of file + this.debug('\n>>> no match, partial?', file, fr, pattern, pr) + if (fr === fl) return true + } + return false + } -function destroyStream(stream, err) { - if (stream.destroy) { - stream.destroy(err); - } else { - // node < 8 - stream.emit('error', err); - stream.end(); - } -} + // something other than ** + // non-magic patterns just have to match exactly + // patterns with magic have been turned into regexps. + var hit + if (typeof p === 'string') { + hit = f === p + this.debug('string match', p, f, hit) + } else { + hit = f.match(p) + this.debug('pattern match', p, f, hit) + } -/** - * Redirect code matching - * - * @param Number code Status code - * @return Boolean - */ -fetch.isRedirect = function (code) { - return code === 301 || code === 302 || code === 303 || code === 307 || code === 308; -}; + if (!hit) return false + } -// expose Promise -fetch.Promise = global.Promise; + // Note: ending in / means that we'll get a final "" + // at the end of the pattern. This can only match a + // corresponding "" at the end of the file. + // If the file ends in /, then it can only match a + // a pattern that ends in /, unless the pattern just + // doesn't have any more for it. But, a/b/ should *not* + // match "a/b/*", even though "" matches against the + // [^/]*? pattern, except in partial mode, where it might + // simply not be reached yet. + // However, a/b/ should still satisfy a/* -module.exports = exports = fetch; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports["default"] = exports; -exports.Headers = Headers; -exports.Request = Request; -exports.Response = Response; -exports.FetchError = FetchError; -exports.AbortError = AbortError; + // now either we fell off the end of the pattern, or we're done. + if (fi === fl && pi === pl) { + // ran out of pattern and filename at the same time. + // an exact hit! + return true + } else if (fi === fl) { + // ran out of file, but still had pattern left. + // this is ok if we're doing the match as part of + // a glob fs traversal. + return partial + } else /* istanbul ignore else */ if (pi === pl) { + // ran out of pattern, still have file left. + // this is only acceptable if we're on the very last + // empty segment of a file with a trailing slash. + // a/* should match a/b/ + return (fi === fl - 1) && (file[fi] === '') + } + // should be unreachable. + /* istanbul ignore next */ + throw new Error('wtf?') + } -/***/ }), + braceExpand () { + return braceExpand(this.pattern, this.options) + } -/***/ 55388: -/***/ ((module) => { + parse (pattern, isSub) { + assertValidPattern(pattern) -/*! - * normalize-path - * - * Copyright (c) 2014-2018, Jon Schlinkert. - * Released under the MIT License. - */ + const options = this.options -module.exports = function(path, stripTrailing) { - if (typeof path !== 'string') { - throw new TypeError('expected path to be a string'); - } + // shortcuts + if (pattern === '**') { + if (!options.noglobstar) + return GLOBSTAR + else + pattern = '*' + } + if (pattern === '') return '' - if (path === '\\' || path === '/') return '/'; + let re = '' + let hasMagic = false + let escaping = false + // ? => one single character + const patternListStack = [] + const negativeLists = [] + let stateChar + let inClass = false + let reClassStart = -1 + let classStart = -1 + let cs + let pl + let sp + // . and .. never match anything that doesn't start with ., + // even when options.dot is set. However, if the pattern + // starts with ., then traversal patterns can match. + let dotTravAllowed = pattern.charAt(0) === '.' + let dotFileAllowed = options.dot || dotTravAllowed + const patternStart = () => + dotTravAllowed + ? '' + : dotFileAllowed + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)' + const subPatternStart = (p) => + p.charAt(0) === '.' + ? '' + : options.dot + ? '(?!(?:^|\\/)\\.{1,2}(?:$|\\/))' + : '(?!\\.)' - var len = path.length; - if (len <= 1) return path; - // ensure that win32 namespaces has two leading slashes, so that the path is - // handled properly by the win32 version of path.parse() after being normalized - // https://msdn.microsoft.com/library/windows/desktop/aa365247(v=vs.85).aspx#namespaces - var prefix = ''; - if (len > 4 && path[3] === '\\') { - var ch = path[2]; - if ((ch === '?' || ch === '.') && path.slice(0, 2) === '\\\\') { - path = path.slice(2); - prefix = '//'; + const clearStateChar = () => { + if (stateChar) { + // we had some state-tracking character + // that wasn't consumed by this pass. + switch (stateChar) { + case '*': + re += star + hasMagic = true + break + case '?': + re += qmark + hasMagic = true + break + default: + re += '\\' + stateChar + break + } + this.debug('clearStateChar %j %j', stateChar, re) + stateChar = false + } } - } - var segs = path.split(/[/\\]+/); - if (stripTrailing !== false && segs[segs.length - 1] === '') { - segs.pop(); - } - return prefix + segs.join('/'); -}; + for (let i = 0, c; (i < pattern.length) && (c = pattern.charAt(i)); i++) { + this.debug('%s\t%s %s %j', pattern, i, re, c) + // skip over any that are escaped. + if (escaping) { + /* istanbul ignore next - completely not allowed, even escaped. */ + if (c === '/') { + return false + } -/***/ }), + if (reSpecials[c]) { + re += '\\' + } + re += c + escaping = false + continue + } -/***/ 1223: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + switch (c) { + /* istanbul ignore next */ + case '/': { + // Should already be path-split by now. + return false + } -var wrappy = __nccwpck_require__(62940) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) + case '\\': + if (inClass && pattern.charAt(i + 1) === '-') { + re += c + continue + } -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) + clearStateChar() + escaping = true + continue - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) + // the various stateChar values + // for the "extglob" stuff. + case '?': + case '*': + case '+': + case '@': + case '!': + this.debug('%s\t%s %s %j <-- stateChar', pattern, i, re, c) -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) - } - f.called = false - return f -} + // all of those are literals inside a class, except that + // the glob [!a] means [^a] in regexp + if (inClass) { + this.debug(' in class') + if (c === '!' && i === classStart + 1) c = '^' + re += c + continue + } -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) - } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f -} + // if we already have a stateChar, then it means + // that there was something like ** or +? in there. + // Handle the stateChar, then proceed with this one. + this.debug('call clearStateChar %j', stateChar) + clearStateChar() + stateChar = c + // if extglob is disabled, then +(asdf|foo) isn't a thing. + // just clear the statechar *now*, rather than even diving into + // the patternList stuff. + if (options.noext) clearStateChar() + continue + case '(': { + if (inClass) { + re += '(' + continue + } -/***/ }), + if (!stateChar) { + re += '\\(' + continue + } -/***/ 38714: -/***/ ((module) => { + const plEntry = { + type: stateChar, + start: i - 1, + reStart: re.length, + open: plTypes[stateChar].open, + close: plTypes[stateChar].close, + } + this.debug(this.pattern, '\t', plEntry) + patternListStack.push(plEntry) + // negation is (?:(?!(?:js)(?:))[^/]*) + re += plEntry.open + // next entry starts with a dot maybe? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true + re += subPatternStart(pattern.slice(i + 1)) + } + this.debug('plType %j %j', stateChar, re) + stateChar = false + continue + } -"use strict"; + case ')': { + const plEntry = patternListStack[patternListStack.length - 1] + if (inClass || !plEntry) { + re += '\\)' + continue + } + patternListStack.pop() + + // closing an extglob + clearStateChar() + hasMagic = true + pl = plEntry + // negation is (?:(?!js)[^/]*) + // The others are (?:) + re += pl.close + if (pl.type === '!') { + negativeLists.push(Object.assign(pl, { reEnd: re.length })) + } + continue + } + case '|': { + const plEntry = patternListStack[patternListStack.length - 1] + if (inClass || !plEntry) { + re += '\\|' + continue + } -function posix(path) { - return path.charAt(0) === '/'; -} + clearStateChar() + re += '|' + // next subpattern can start with a dot? + if (plEntry.start === 0 && plEntry.type !== '!') { + dotTravAllowed = true + re += subPatternStart(pattern.slice(i + 1)) + } + continue + } -function win32(path) { - // https://github.com/nodejs/node/blob/b3fcc245fb25539909ef1d5eaa01dbf92e168633/lib/path.js#L56 - var splitDeviceRe = /^([a-zA-Z]:|[\\\/]{2}[^\\\/]+[\\\/]+[^\\\/]+)?([\\\/])?([\s\S]*?)$/; - var result = splitDeviceRe.exec(path); - var device = result[1] || ''; - var isUnc = Boolean(device && device.charAt(1) !== ':'); + // these are mostly the same in regexp and glob + case '[': + // swallow any state-tracking char before the [ + clearStateChar() - // UNC paths are always absolute - return Boolean(result[2] || isUnc); -} + if (inClass) { + re += '\\' + c + continue + } -module.exports = process.platform === 'win32' ? win32 : posix; -module.exports.posix = posix; -module.exports.win32 = win32; + inClass = true + classStart = i + reClassStart = re.length + re += c + continue + case ']': + // a right bracket shall lose its special + // meaning and represent itself in + // a bracket expression if it occurs + // first in the list. -- POSIX.2 2.8.3.2 + if (i === classStart + 1 || !inClass) { + re += '\\' + c + continue + } -/***/ }), + // split where the last [ was, make sure we don't have + // an invalid re. if so, re-walk the contents of the + // would-be class to re-translate any characters that + // were passed through as-is + // TODO: It would probably be faster to determine this + // without a try/catch and a new RegExp, but it's tricky + // to do safely. For now, this is safe and works. + cs = pattern.substring(classStart + 1, i) + try { + RegExp('[' + braExpEscape(charUnescape(cs)) + ']') + // looks good, finish up the class. + re += c + } catch (er) { + // out of order ranges in JS are errors, but in glob syntax, + // they're just a range that matches nothing. + re = re.substring(0, reClassStart) + '(?:$.)' // match nothing ever + } + hasMagic = true + inClass = false + continue -/***/ 47810: -/***/ ((module) => { + default: + // swallow any state char that wasn't consumed + clearStateChar() -"use strict"; + if (reSpecials[c] && !(c === '^' && inClass)) { + re += '\\' + } + re += c + break -if (typeof process === 'undefined' || - !process.version || - process.version.indexOf('v0.') === 0 || - process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { - module.exports = { nextTick: nextTick }; -} else { - module.exports = process -} + } // switch + } // for -function nextTick(fn, arg1, arg2, arg3) { - if (typeof fn !== 'function') { - throw new TypeError('"callback" argument must be a function'); - } - var len = arguments.length; - var args, i; - switch (len) { - case 0: - case 1: - return process.nextTick(fn); - case 2: - return process.nextTick(function afterTickOne() { - fn.call(null, arg1); - }); - case 3: - return process.nextTick(function afterTickTwo() { - fn.call(null, arg1, arg2); - }); - case 4: - return process.nextTick(function afterTickThree() { - fn.call(null, arg1, arg2, arg3); - }); - default: - args = new Array(len - 1); - i = 0; - while (i < args.length) { - args[i++] = arguments[i]; + // handle the case where we left a class open. + // "[abc" is valid, equivalent to "\[abc" + if (inClass) { + // split where the last [ was, and escape it + // this is a huge pita. We now have to re-walk + // the contents of the would-be class to re-translate + // any characters that were passed through as-is + cs = pattern.slice(classStart + 1) + sp = this.parse(cs, SUBPARSE) + re = re.substring(0, reClassStart) + '\\[' + sp[0] + hasMagic = hasMagic || sp[1] } - return process.nextTick(function afterTick() { - fn.apply(null, args); - }); - } -} + // handle the case where we had a +( thing at the *end* + // of the pattern. + // each pattern list stack adds 3 chars, and we need to go through + // and escape any | chars that were passed through as-is for the regexp. + // Go through and escape them, taking care not to double-escape any + // | chars that were already escaped. + for (pl = patternListStack.pop(); pl; pl = patternListStack.pop()) { + let tail + tail = re.slice(pl.reStart + pl.open.length) + this.debug('setting tail', re, pl) + // maybe some even number of \, then maybe 1 \, followed by a | + tail = tail.replace(/((?:\\{2}){0,64})(\\?)\|/g, (_, $1, $2) => { + /* istanbul ignore else - should already be done */ + if (!$2) { + // the | isn't already escaped, so escape it. + $2 = '\\' + } + // need to escape all those slashes *again*, without escaping the + // one that we need for escaping the | character. As it works out, + // escaping an even number of slashes can be done by simply repeating + // it exactly after itself. That's why this trick works. + // + // I am sorry that you have to see this. + return $1 + $1 + $2 + '|' + }) -/***/ }), + this.debug('tail=%j\n %s', tail, tail, pl, re) + const t = pl.type === '*' ? star + : pl.type === '?' ? qmark + : '\\' + pl.type -/***/ 67214: -/***/ ((module) => { + hasMagic = true + re = re.slice(0, pl.reStart) + t + '\\(' + tail + } -"use strict"; + // handle trailing things that only matter at the very end. + clearStateChar() + if (escaping) { + // trailing \\ + re += '\\\\' + } + // only need to apply the nodot start if the re starts with + // something that could conceivably capture a dot + const addPatternStart = addPatternStartSet[re.charAt(0)] -const codes = {}; + // Hack to work around lack of negative lookbehind in JS + // A pattern like: *.!(x).!(y|z) needs to ensure that a name + // like 'a.xyz.yz' doesn't match. So, the first negative + // lookahead, has to look ALL the way ahead, to the end of + // the pattern. + for (let n = negativeLists.length - 1; n > -1; n--) { + const nl = negativeLists[n] -function createErrorType(code, message, Base) { - if (!Base) { - Base = Error - } + const nlBefore = re.slice(0, nl.reStart) + const nlFirst = re.slice(nl.reStart, nl.reEnd - 8) + let nlAfter = re.slice(nl.reEnd) + const nlLast = re.slice(nl.reEnd - 8, nl.reEnd) + nlAfter - function getMessage (arg1, arg2, arg3) { - if (typeof message === 'string') { - return message - } else { - return message(arg1, arg2, arg3) + // Handle nested stuff like *(*.js|!(*.json)), where open parens + // mean that we should *not* include the ) in the bit that is considered + // "after" the negated section. + const closeParensBefore = nlBefore.split(')').length + const openParensBefore = nlBefore.split('(').length - closeParensBefore + let cleanAfter = nlAfter + for (let i = 0; i < openParensBefore; i++) { + cleanAfter = cleanAfter.replace(/\)[+*?]?/, '') + } + nlAfter = cleanAfter + + const dollar = nlAfter === '' && isSub !== SUBPARSE ? '(?:$|\\/)' : '' + + re = nlBefore + nlFirst + nlAfter + dollar + nlLast } - } - class NodeError extends Base { - constructor (arg1, arg2, arg3) { - super(getMessage(arg1, arg2, arg3)); + // if the re is not "" at this point, then we need to make sure + // it doesn't match against an empty path part. + // Otherwise a/* will match a/, which it should not. + if (re !== '' && hasMagic) { + re = '(?=.)' + re } - } - NodeError.prototype.name = Base.name; - NodeError.prototype.code = code; + if (addPatternStart) { + re = patternStart() + re + } - codes[code] = NodeError; -} + // parsing just a piece of a larger pattern. + if (isSub === SUBPARSE) { + return [re, hasMagic] + } -// https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js -function oneOf(expected, thing) { - if (Array.isArray(expected)) { - const len = expected.length; - expected = expected.map((i) => String(i)); - if (len > 2) { - return `one of ${thing} ${expected.slice(0, len - 1).join(', ')}, or ` + - expected[len - 1]; - } else if (len === 2) { - return `one of ${thing} ${expected[0]} or ${expected[1]}`; - } else { - return `of ${thing} ${expected[0]}`; + // if it's nocase, and the lcase/uppercase don't match, it's magic + if (options.nocase && !hasMagic) { + hasMagic = pattern.toUpperCase() !== pattern.toLowerCase() + } + + // skip the regexp for non-magical patterns + // unescape anything in it, though, so that it'll be + // an exact match against a file etc. + if (!hasMagic) { + return globUnescape(pattern) + } + + const flags = options.nocase ? 'i' : '' + try { + return Object.assign(new RegExp('^' + re + '$', flags), { + _glob: pattern, + _src: re, + }) + } catch (er) /* istanbul ignore next - should be impossible */ { + // If it was an invalid regular expression, then it can't match + // anything. This trick looks for a character after the end of + // the string, which is of course impossible, except in multi-line + // mode, but it's not a /m regex. + return new RegExp('$.') } - } else { - return `of ${thing} ${String(expected)}`; } -} -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith -function startsWith(str, search, pos) { - return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search; -} + makeRe () { + if (this.regexp || this.regexp === false) return this.regexp -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith -function endsWith(str, search, this_len) { - if (this_len === undefined || this_len > str.length) { - this_len = str.length; - } - return str.substring(this_len - search.length, this_len) === search; -} + // at this point, this.set is a 2d array of partial + // pattern strings, or "**". + // + // It's better to use .match(). This function shouldn't + // be used, really, but it's pretty convenient sometimes, + // when you just want to work with a regex. + const set = this.set -// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes -function includes(str, search, start) { - if (typeof start !== 'number') { - start = 0; - } + if (!set.length) { + this.regexp = false + return this.regexp + } + const options = this.options - if (start + search.length > str.length) { - return false; - } else { - return str.indexOf(search, start) !== -1; - } -} + const twoStar = options.noglobstar ? star + : options.dot ? twoStarDot + : twoStarNoDot + const flags = options.nocase ? 'i' : '' -createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) { - return 'The value "' + value + '" is invalid for option "' + name + '"' -}, TypeError); -createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) { - // determiner: 'must be' or 'must not be' - let determiner; - if (typeof expected === 'string' && startsWith(expected, 'not ')) { - determiner = 'must not be'; - expected = expected.replace(/^not /, ''); - } else { - determiner = 'must be'; - } + // coalesce globstars and regexpify non-globstar patterns + // if it's the only item, then we just do one twoStar + // if it's the first, and there are more, prepend (\/|twoStar\/)? to next + // if it's the last, append (\/twoStar|) to previous + // if it's in the middle, append (\/|\/twoStar\/) to previous + // then filter out GLOBSTAR symbols + let re = set.map(pattern => { + pattern = pattern.map(p => + typeof p === 'string' ? regExpEscape(p) + : p === GLOBSTAR ? GLOBSTAR + : p._src + ).reduce((set, p) => { + if (!(set[set.length - 1] === GLOBSTAR && p === GLOBSTAR)) { + set.push(p) + } + return set + }, []) + pattern.forEach((p, i) => { + if (p !== GLOBSTAR || pattern[i-1] === GLOBSTAR) { + return + } + if (i === 0) { + if (pattern.length > 1) { + pattern[i+1] = '(?:\\\/|' + twoStar + '\\\/)?' + pattern[i+1] + } else { + pattern[i] = twoStar + } + } else if (i === pattern.length - 1) { + pattern[i-1] += '(?:\\\/|' + twoStar + ')?' + } else { + pattern[i-1] += '(?:\\\/|\\\/' + twoStar + '\\\/)' + pattern[i+1] + pattern[i+1] = GLOBSTAR + } + }) + return pattern.filter(p => p !== GLOBSTAR).join('/') + }).join('|') - let msg; - if (endsWith(name, ' argument')) { - // For cases like 'first argument' - msg = `The ${name} ${determiner} ${oneOf(expected, 'type')}`; - } else { - const type = includes(name, '.') ? 'property' : 'argument'; - msg = `The "${name}" ${type} ${determiner} ${oneOf(expected, 'type')}`; + // must match entire pattern + // ending in a * or ** will make it less strict. + re = '^(?:' + re + ')$' + + // can match anything, as long as it's not this. + if (this.negate) re = '^(?!' + re + ').*$' + + try { + this.regexp = new RegExp(re, flags) + } catch (ex) /* istanbul ignore next - should be impossible */ { + this.regexp = false + } + return this.regexp } - msg += `. Received type ${typeof actual}`; - return msg; -}, TypeError); -createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF'); -createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) { - return 'The ' + name + ' method is not implemented' -}); -createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close'); -createErrorType('ERR_STREAM_DESTROYED', function (name) { - return 'Cannot call ' + name + ' after a stream was destroyed'; -}); -createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times'); -createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable'); -createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end'); -createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); -createErrorType('ERR_UNKNOWN_ENCODING', function (arg) { - return 'Unknown encoding: ' + arg -}, TypeError); -createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event'); + match (f, partial = this.partial) { + this.debug('match', f, this.pattern) + // short-circuit in the case of busted things. + // comments, etc. + if (this.comment) return false + if (this.empty) return f === '' -module.exports.q = codes; + if (f === '/' && partial) return true + const options = this.options -/***/ }), + // windows: need to use /, not \ + if (path.sep !== '/') { + f = f.split(path.sep).join('/') + } -/***/ 41359: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // treat the test path as a set of pathparts. + f = f.split(slashSplit) + this.debug(this.pattern, 'split', f) -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + // just ONE of the pattern sets in this.set needs to match + // in order for it to be valid. If negating, then just one + // match means that we have failed. + // Either way, return on the first hit. -// a duplex stream is just a stream that is both readable and writable. -// Since JS doesn't have multiple prototypal inheritance, this class -// prototypally inherits from Readable, and then parasitically from -// Writable. + const set = this.set + this.debug(this.pattern, 'set', set) + // Find the basename of the path by looking for the last non-empty segment + let filename + for (let i = f.length - 1; i >= 0; i--) { + filename = f[i] + if (filename) break + } + for (let i = 0; i < set.length; i++) { + const pattern = set[i] + let file = f + if (options.matchBase && pattern.length === 1) { + file = [filename] + } + const hit = this.matchOne(file, pattern, partial) + if (hit) { + if (options.flipNegate) return true + return !this.negate + } + } -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) keys.push(key); - return keys; -}; -/**/ + // didn't get any hits. this is success if it's a negative + // pattern, failure otherwise. + if (options.flipNegate) return false + return this.negate + } -module.exports = Duplex; -var Readable = __nccwpck_require__(51433); -var Writable = __nccwpck_require__(26993); -__nccwpck_require__(44124)(Duplex, Readable); -{ - // Allow the keys array to be GC'ed. - var keys = objectKeys(Writable.prototype); - for (var v = 0; v < keys.length; v++) { - var method = keys[v]; - if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + static defaults (def) { + return minimatch.defaults(def).Minimatch } } -function Duplex(options) { - if (!(this instanceof Duplex)) return new Duplex(options); - Readable.call(this, options); - Writable.call(this, options); - this.allowHalfOpen = true; - if (options) { - if (options.readable === false) this.readable = false; - if (options.writable === false) this.writable = false; - if (options.allowHalfOpen === false) { - this.allowHalfOpen = false; - this.once('end', onend); - } - } -} -Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.highWaterMark; - } -}); -Object.defineProperty(Duplex.prototype, 'writableBuffer', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState && this._writableState.getBuffer(); - } -}); -Object.defineProperty(Duplex.prototype, 'writableLength', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - return this._writableState.length; - } -}); -// the no-half-open enforcer -function onend() { - // If the writable side ended, then we're ok. - if (this._writableState.ended) return; +minimatch.Minimatch = Minimatch - // no more data can be written. - // But allow more writes to happen in this tick. - process.nextTick(onEndNT, this); -} -function onEndNT(self) { - self.end(); -} -Object.defineProperty(Duplex.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined || this._writableState === undefined) { - return false; + +/***/ }), + +/***/ 72043: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +;(function (sax) { // wrapper for non-node envs + sax.parser = function (strict, opt) { return new SAXParser(strict, opt) } + sax.SAXParser = SAXParser + sax.SAXStream = SAXStream + sax.createStream = createStream + + // When we pass the MAX_BUFFER_LENGTH position, start checking for buffer overruns. + // When we check, schedule the next check for MAX_BUFFER_LENGTH - (max(buffer lengths)), + // since that's the earliest that a buffer overrun could occur. This way, checks are + // as rare as required, but as often as necessary to ensure never crossing this bound. + // Furthermore, buffers are only tested at most once per write(), so passing a very + // large string into write() might have undesirable effects, but this is manageable by + // the caller, so it is assumed to be safe. Thus, a call to write() may, in the extreme + // edge case, result in creating at most one complete copy of the string passed in. + // Set to Infinity to have unlimited buffers. + sax.MAX_BUFFER_LENGTH = 64 * 1024 + + var buffers = [ + 'comment', 'sgmlDecl', 'textNode', 'tagName', 'doctype', + 'procInstName', 'procInstBody', 'entity', 'attribName', + 'attribValue', 'cdata', 'script' + ] + + sax.EVENTS = [ + 'text', + 'processinginstruction', + 'sgmldeclaration', + 'doctype', + 'comment', + 'opentagstart', + 'attribute', + 'opentag', + 'closetag', + 'opencdata', + 'cdata', + 'closecdata', + 'error', + 'end', + 'ready', + 'script', + 'opennamespace', + 'closenamespace' + ] + + function SAXParser (strict, opt) { + if (!(this instanceof SAXParser)) { + return new SAXParser(strict, opt) } - return this._readableState.destroyed && this._writableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (this._readableState === undefined || this._writableState === undefined) { - return; + + var parser = this + clearBuffers(parser) + parser.q = parser.c = '' + parser.bufferCheckPosition = sax.MAX_BUFFER_LENGTH + parser.opt = opt || {} + parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags + parser.looseCase = parser.opt.lowercase ? 'toLowerCase' : 'toUpperCase' + parser.tags = [] + parser.closed = parser.closedRoot = parser.sawRoot = false + parser.tag = parser.error = null + parser.strict = !!strict + parser.noscript = !!(strict || parser.opt.noscript) + parser.state = S.BEGIN + parser.strictEntities = parser.opt.strictEntities + parser.ENTITIES = parser.strictEntities ? Object.create(sax.XML_ENTITIES) : Object.create(sax.ENTITIES) + parser.attribList = [] + + // namespaces form a prototype chain. + // it always points at the current tag, + // which protos to its parent tag. + if (parser.opt.xmlns) { + parser.ns = Object.create(rootNS) } - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; - this._writableState.destroyed = value; + // mostly just for error reporting + parser.trackPosition = parser.opt.position !== false + if (parser.trackPosition) { + parser.position = parser.line = parser.column = 0 + } + emit(parser, 'onready') } -}); -/***/ }), + if (!Object.create) { + Object.create = function (o) { + function F () {} + F.prototype = o + var newf = new F() + return newf + } + } -/***/ 81542: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!Object.keys) { + Object.keys = function (o) { + var a = [] + for (var i in o) if (o.hasOwnProperty(i)) a.push(i) + return a + } + } -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + function checkBufferLength (parser) { + var maxAllowed = Math.max(sax.MAX_BUFFER_LENGTH, 10) + var maxActual = 0 + for (var i = 0, l = buffers.length; i < l; i++) { + var len = parser[buffers[i]].length + if (len > maxAllowed) { + // Text/cdata nodes can get big, and since they're buffered, + // we can get here under normal conditions. + // Avoid issues by emitting the text node now, + // so at least it won't get any bigger. + switch (buffers[i]) { + case 'textNode': + closeText(parser) + break -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. + case 'cdata': + emitNode(parser, 'oncdata', parser.cdata) + parser.cdata = '' + break + case 'script': + emitNode(parser, 'onscript', parser.script) + parser.script = '' + break + default: + error(parser, 'Max buffer length exceeded: ' + buffers[i]) + } + } + maxActual = Math.max(maxActual, len) + } + // schedule the next check for the earliest possible buffer overrun. + var m = sax.MAX_BUFFER_LENGTH - maxActual + parser.bufferCheckPosition = m + parser.position + } -module.exports = PassThrough; -var Transform = __nccwpck_require__(34415); -__nccwpck_require__(44124)(PassThrough, Transform); -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - Transform.call(this, options); -} -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; + function clearBuffers (parser) { + for (var i = 0, l = buffers.length; i < l; i++) { + parser[buffers[i]] = '' + } + } -/***/ }), + function flushBuffers (parser) { + closeText(parser) + if (parser.cdata !== '') { + emitNode(parser, 'oncdata', parser.cdata) + parser.cdata = '' + } + if (parser.script !== '') { + emitNode(parser, 'onscript', parser.script) + parser.script = '' + } + } -/***/ 51433: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + SAXParser.prototype = { + end: function () { end(this) }, + write: write, + resume: function () { this.error = null; return this }, + close: function () { return this.write(null) }, + flush: function () { flushBuffers(this) } + } -"use strict"; -// Copyright Joyent, Inc. and other Node contributors. -// -// Permission is hereby granted, free of charge, to any person obtaining a -// copy of this software and associated documentation files (the -// "Software"), to deal in the Software without restriction, including -// without limitation the rights to use, copy, modify, merge, publish, -// distribute, sublicense, and/or sell copies of the Software, and to permit -// persons to whom the Software is furnished to do so, subject to the -// following conditions: -// -// The above copyright notice and this permission notice shall be included -// in all copies or substantial portions of the Software. -// -// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS -// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF -// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN -// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR -// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE -// USE OR OTHER DEALINGS IN THE SOFTWARE. + var Stream + try { + Stream = (__nccwpck_require__(12781).Stream) + } catch (ex) { + Stream = function () {} + } + if (!Stream) Stream = function () {} + var streamWraps = sax.EVENTS.filter(function (ev) { + return ev !== 'error' && ev !== 'end' + }) + function createStream (strict, opt) { + return new SAXStream(strict, opt) + } -module.exports = Readable; + function SAXStream (strict, opt) { + if (!(this instanceof SAXStream)) { + return new SAXStream(strict, opt) + } -/**/ -var Duplex; -/**/ + Stream.apply(this) -Readable.ReadableState = ReadableState; + this._parser = new SAXParser(strict, opt) + this.writable = true + this.readable = true -/**/ -var EE = (__nccwpck_require__(82361).EventEmitter); -var EElistenerCount = function EElistenerCount(emitter, type) { - return emitter.listeners(type).length; -}; -/**/ + var me = this -/**/ -var Stream = __nccwpck_require__(62387); -/**/ + this._parser.onend = function () { + me.emit('end') + } -var Buffer = (__nccwpck_require__(14300).Buffer); -var OurUint8Array = (typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : typeof self !== 'undefined' ? self : {}).Uint8Array || function () {}; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; -} + this._parser.onerror = function (er) { + me.emit('error', er) -/**/ -var debugUtil = __nccwpck_require__(73837); -var debug; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function debug() {}; -} -/**/ + // if didn't throw, then means error was handled. + // go ahead and clear error, so we can write again. + me._parser.error = null + } -var BufferList = __nccwpck_require__(52746); -var destroyImpl = __nccwpck_require__(97049); -var _require = __nccwpck_require__(39948), - getHighWaterMark = _require.getHighWaterMark; -var _require$codes = (__nccwpck_require__(67214)/* .codes */ .q), - ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE, - ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF, - ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED, - ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; - -// Lazy loaded to improve the startup performance. -var StringDecoder; -var createReadableStreamAsyncIterator; -var from; -__nccwpck_require__(44124)(Readable, Stream); -var errorOrDestroy = destroyImpl.errorOrDestroy; -var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; -function prependListener(emitter, event, fn) { - // Sadly this is not cacheable as some libraries bundle their own - // event emitter implementation with them. - if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); + this._decoder = null - // This is a hack to make sure that our error handler is attached before any - // userland ones. NEVER DO THIS. This is here only because this code needs - // to continue to work with older versions of Node.js that do not include - // the prependListener() method. The goal is to eventually remove this hack. - if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; -} -function ReadableState(options, stream, isDuplex) { - Duplex = Duplex || __nccwpck_require__(41359); - options = options || {}; + streamWraps.forEach(function (ev) { + Object.defineProperty(me, 'on' + ev, { + get: function () { + return me._parser['on' + ev] + }, + set: function (h) { + if (!h) { + me.removeAllListeners(ev) + me._parser['on' + ev] = h + return h + } + me.on(ev, h) + }, + enumerable: true, + configurable: false + }) + }) + } - // Duplex streams are both readable and writable, but share - // the same options object. - // However, some cases require setting options to different - // values for the readable and the writable sides of the duplex stream. - // These options can be provided separately as readableXXX and writableXXX. - if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; + SAXStream.prototype = Object.create(Stream.prototype, { + constructor: { + value: SAXStream + } + }) - // object stream flag. Used to make read(n) ignore n and to - // make all the buffer merging and length checks go away - this.objectMode = !!options.objectMode; - if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; + SAXStream.prototype.write = function (data) { + if (typeof Buffer === 'function' && + typeof Buffer.isBuffer === 'function' && + Buffer.isBuffer(data)) { + if (!this._decoder) { + var SD = (__nccwpck_require__(71576).StringDecoder) + this._decoder = new SD('utf8') + } + data = this._decoder.write(data) + } - // the point at which it stops calling _read() to fill the buffer - // Note: 0 is a valid value, means "don't call _read preemptively ever" - this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); + this._parser.write(data.toString()) + this.emit('data', data) + return true + } - // A linked list is used to store data chunks instead of an array because the - // linked list can remove elements from the beginning faster than - // array.shift() - this.buffer = new BufferList(); - this.length = 0; - this.pipes = null; - this.pipesCount = 0; - this.flowing = null; - this.ended = false; - this.endEmitted = false; - this.reading = false; + SAXStream.prototype.end = function (chunk) { + if (chunk && chunk.length) { + this.write(chunk) + } + this._parser.end() + return true + } - // a flag to be able to tell if the event 'readable'/'data' is emitted - // immediately, or on a later tick. We set this to true at first, because - // any actions that shouldn't happen until "later" should generally also - // not happen before the first read call. - this.sync = true; + SAXStream.prototype.on = function (ev, handler) { + var me = this + if (!me._parser['on' + ev] && streamWraps.indexOf(ev) !== -1) { + me._parser['on' + ev] = function () { + var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments) + args.splice(0, 0, ev) + me.emit.apply(me, args) + } + } - // whenever we return null, then we set a flag to say - // that we're awaiting a 'readable' event emission. - this.needReadable = false; - this.emittedReadable = false; - this.readableListening = false; - this.resumeScheduled = false; - this.paused = true; + return Stream.prototype.on.call(me, ev, handler) + } - // Should close be emitted on destroy. Defaults to true. - this.emitClose = options.emitClose !== false; + // this really needs to be replaced with character classes. + // XML allows all manner of ridiculous numbers and digits. + var CDATA = '[CDATA[' + var DOCTYPE = 'DOCTYPE' + var XML_NAMESPACE = 'http://www.w3.org/XML/1998/namespace' + var XMLNS_NAMESPACE = 'http://www.w3.org/2000/xmlns/' + var rootNS = { xml: XML_NAMESPACE, xmlns: XMLNS_NAMESPACE } - // Should .destroy() be called after 'end' (and potentially 'finish') - this.autoDestroy = !!options.autoDestroy; + // http://www.w3.org/TR/REC-xml/#NT-NameStartChar + // This implementation works on strings, a single character at a time + // as such, it cannot ever support astral-plane characters (10000-EFFFF) + // without a significant breaking change to either this parser, or the + // JavaScript language. Implementation of an emoji-capable xml parser + // is left as an exercise for the reader. + var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ - // has it been destroyed - this.destroyed = false; + var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ - // Crypto is kind of old and crusty. Historically, its default string - // encoding is 'binary' so we have to make this configurable. - // Everything else in the universe uses 'utf8', though. - this.defaultEncoding = options.defaultEncoding || 'utf8'; + var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/ + var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/ - // the number of writers that are awaiting a drain event in .pipe()s - this.awaitDrain = 0; + function isWhitespace (c) { + return c === ' ' || c === '\n' || c === '\r' || c === '\t' + } - // if true, a maybeReadMore has been scheduled - this.readingMore = false; - this.decoder = null; - this.encoding = null; - if (options.encoding) { - if (!StringDecoder) StringDecoder = (__nccwpck_require__(94841)/* .StringDecoder */ .s); - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; + function isQuote (c) { + return c === '"' || c === '\'' } -} -function Readable(options) { - Duplex = Duplex || __nccwpck_require__(41359); - if (!(this instanceof Readable)) return new Readable(options); - // Checking for a Stream.Duplex instance is faster here instead of inside - // the ReadableState constructor, at least with V8 6.5 - var isDuplex = this instanceof Duplex; - this._readableState = new ReadableState(options, this, isDuplex); + function isAttribEnd (c) { + return c === '>' || isWhitespace(c) + } - // legacy - this.readable = true; - if (options) { - if (typeof options.read === 'function') this._read = options.read; - if (typeof options.destroy === 'function') this._destroy = options.destroy; + function isMatch (regex, c) { + return regex.test(c) } - Stream.call(this); -} -Object.defineProperty(Readable.prototype, 'destroyed', { - // making it explicit this property is not enumerable - // because otherwise some prototype manipulation in - // userland will fail - enumerable: false, - get: function get() { - if (this._readableState === undefined) { - return false; - } - return this._readableState.destroyed; - }, - set: function set(value) { - // we ignore the value if the stream - // has not been initialized yet - if (!this._readableState) { - return; - } - // backward compatibility, the user is explicitly - // managing destroyed - this._readableState.destroyed = value; + function notMatch (regex, c) { + return !isMatch(regex, c) } -}); -Readable.prototype.destroy = destroyImpl.destroy; -Readable.prototype._undestroy = destroyImpl.undestroy; -Readable.prototype._destroy = function (err, cb) { - cb(err); -}; -// Manually shove something into the read() buffer. -// This returns true if the highWaterMark has not been hit yet, -// similar to how Writable.write() returns true if you should -// write() some more. -Readable.prototype.push = function (chunk, encoding) { - var state = this._readableState; - var skipChunkCheck; - if (!state.objectMode) { - if (typeof chunk === 'string') { - encoding = encoding || state.defaultEncoding; - if (encoding !== state.encoding) { - chunk = Buffer.from(chunk, encoding); - encoding = ''; - } - skipChunkCheck = true; - } - } else { - skipChunkCheck = true; + var S = 0 + sax.STATE = { + BEGIN: S++, // leading byte order mark or whitespace + BEGIN_WHITESPACE: S++, // leading whitespace + TEXT: S++, // general stuff + TEXT_ENTITY: S++, // & and such. + OPEN_WAKA: S++, // < + SGML_DECL: S++, // + SCRIPT: S++, //