From 97dcf9491ed59f6caa3a9380403aa6a065366655 Mon Sep 17 00:00:00 2001 From: Peter Muessig Date: Mon, 18 Dec 2023 16:13:00 +0100 Subject: [PATCH] fix(ui5-tooling-modules): improved packaging of npm packages The packaging of npm packages resolves the browser modules also from the exports section of the package.json. This provides a better coverage to detect the browser modules inside the npm packages. In addition, this fix also allows to add polyfill overrides in the current working directory. Fixes #927 Fixes #915 --- .eslintignore | 1 + .../lib/rollup-plugin-logger.js | 10 +- .../lib/rollup-plugin-pnpm-resolve.js | 21 +- .../lib/rollup-plugin-polyfill-node-ignore.js | 28 - .../rollup-plugin-polyfill-node-override.js | 85 +- packages/ui5-tooling-modules/lib/util.js | 77 +- packages/ui5-tooling-modules/package.json | 2 +- .../test/__snap__/@octokit/core.js | 2222 +- .../test/__snap__/@supabase/supabase-js.js | 9 +- .../test/__snap__/axios.js | 2303 +- .../ui5-tooling-modules/test/__snap__/cmis.js | 3996 +- .../test/__snap__/jspdf.js | 2 +- .../jspdf/{Ho2Fpw1t.js => Ovurvj05.js} | 59 +- .../__snap__/ui5-app/bundledefs/firebase.js | 39735 +++++++++++- .../test/__snap__/ui5-app/bundledefs/react.js | 23013 +------ .../ui5-tooling-modules/test/__snap__/xlsx.js | 51145 ++++++++-------- .../test/__snap__/xml-js.js | 7466 +++ .../ui5-tooling-modules/test/__snap__/zod.js | 8184 ++- .../ui5-tooling-modules/test/util.test.js | 16 +- pnpm-lock.yaml | 307 +- .../_polyfill-overrides_/async_hooks.js | 1 + .../ui5-app/_polyfill-overrides_/buffer.js | 1934 + .../diagnostics_channel.js | 1 + .../ui5-app/_polyfill-overrides_/http2.js | 9 + .../ui5-app/_polyfill-overrides_/util.js | 713 + showcases/ui5-app/package.json | 5 +- .../controller/Thirdparty.controller.js | 8 +- 27 files changed, 83930 insertions(+), 57422 deletions(-) delete mode 100644 packages/ui5-tooling-modules/lib/rollup-plugin-polyfill-node-ignore.js rename packages/ui5-tooling-modules/test/__snap__/jspdf/{Ho2Fpw1t.js => Ovurvj05.js} (98%) create mode 100644 packages/ui5-tooling-modules/test/__snap__/xml-js.js create mode 100644 showcases/ui5-app/_polyfill-overrides_/async_hooks.js create mode 100644 showcases/ui5-app/_polyfill-overrides_/buffer.js create mode 100644 showcases/ui5-app/_polyfill-overrides_/diagnostics_channel.js create mode 100644 showcases/ui5-app/_polyfill-overrides_/http2.js create mode 100644 showcases/ui5-app/_polyfill-overrides_/util.js diff --git a/.eslintignore b/.eslintignore index 43a640816..334d9023b 100644 --- a/.eslintignore +++ b/.eslintignore @@ -10,6 +10,7 @@ /**/*.png # Additionally ignore folders for lint-staged +/showcases/ui5-app/_polyfill-overrides_/** /showcases/ui5-app/bundledefs/** /packages/ui5-middleware-onelogin/lib/** /packages/ui5-middleware-approuter/test/** diff --git a/packages/ui5-tooling-modules/lib/rollup-plugin-logger.js b/packages/ui5-tooling-modules/lib/rollup-plugin-logger.js index fe6ab2a76..403055ac4 100644 --- a/packages/ui5-tooling-modules/lib/rollup-plugin-logger.js +++ b/packages/ui5-tooling-modules/lib/rollup-plugin-logger.js @@ -1,8 +1,14 @@ module.exports = function ({ log } = {}) { + let c_id = 0, + c_l = 0; return { name: "logger", - resolveId(source) { - log?.verbose(`Bundling resource ${source}`); + resolveId(importee, importer) { + log?.verbose(`${c_id++} Bundling resource ${importee} from ${importer?.split("/").pop()}`); + return undefined; + }, + load(importee) { + log?.verbose(` ${c_l++} Loading resource ${importee}`); return undefined; }, }; diff --git a/packages/ui5-tooling-modules/lib/rollup-plugin-pnpm-resolve.js b/packages/ui5-tooling-modules/lib/rollup-plugin-pnpm-resolve.js index 642e12420..2633d5c9e 100644 --- a/packages/ui5-tooling-modules/lib/rollup-plugin-pnpm-resolve.js +++ b/packages/ui5-tooling-modules/lib/rollup-plugin-pnpm-resolve.js @@ -1,14 +1,27 @@ const path = require("path"); +const fs = require("fs"); module.exports = function ({ resolveModule } = {}) { return { name: "pnpm-resolve", - resolveId(source) { - // ignore absolute paths - if (path.isAbsolute(source)) { + resolveId: function (importee, importer) { + if (path.isAbsolute(importee)) { + // ignore absolute paths return null; + } else if (importee.startsWith("./") || importee.startsWith("../")) { + // resolve relative paths + const file = path.resolve(path.dirname(importer), importee); + if (fs.existsSync(file) && fs.statSync(file).isFile()) { + return file; + } else if (fs.existsSync(`${file}.js`)) { + return `${file}.js`; + } else if (fs.existsSync(`${file}.cjs`)) { + return `${file}.cjs`; + } else if (fs.existsSync(`${file}.mjs`)) { + return `${file}.mjs`; + } } // needs to be in sync with nodeResolve - return resolveModule(source); + return resolveModule(importee); }, }; }; diff --git a/packages/ui5-tooling-modules/lib/rollup-plugin-polyfill-node-ignore.js b/packages/ui5-tooling-modules/lib/rollup-plugin-polyfill-node-ignore.js deleted file mode 100644 index cb016b81b..000000000 --- a/packages/ui5-tooling-modules/lib/rollup-plugin-polyfill-node-ignore.js +++ /dev/null @@ -1,28 +0,0 @@ -/* eslint-disable no-unused-vars */ -module.exports = function ({ log } = {}) { - const isBuiltInModule = function (module) { - try { - if (!require("path").isAbsolute(module) && require.resolve(module) === module) { - return true; - } - } catch (ex) { - /* */ - } - return false; - }; - return { - name: "polyfill-node-ignore", - resolveId: function (source) { - if (isBuiltInModule(source)) { - return { id: `${source}?polyfill-node-ignore`, moduleSideEffects: false }; - } - return null; - }, - load: function (source) { - if (source.endsWith("?polyfill-node-ignore")) { - return ""; - } - return null; - }, - }; -}; diff --git a/packages/ui5-tooling-modules/lib/rollup-plugin-polyfill-node-override.js b/packages/ui5-tooling-modules/lib/rollup-plugin-polyfill-node-override.js index 924c0dbc8..77a8e9bf1 100644 --- a/packages/ui5-tooling-modules/lib/rollup-plugin-polyfill-node-override.js +++ b/packages/ui5-tooling-modules/lib/rollup-plugin-polyfill-node-override.js @@ -1,37 +1,72 @@ /* eslint-disable no-unused-vars */ +const { existsSync, readFileSync } = require("fs"); +const { join } = require("path"); + +// reuse logic from polyfill-node plugin const nodePolyfills = require("rollup-plugin-polyfill-node"); -module.exports = function ({ log } = {}) { - const { resolveId } = nodePolyfills(); +const PREFIX = `\0polyfill-node.`; +const PREFIX_LENGTH = PREFIX.length; +const DIRNAME_PATH = "\0node-polyfills:dirname"; +const FILENAME_PATH = "\0node-polyfills:filename"; +const inject = require("@rollup/plugin-inject"); + +const isBuiltInModule = function isBuiltInModule(module) { + try { + if (!require("path").isAbsolute(module) && require.resolve(module) === module) { + return true; + } + } catch (ex) { + /* */ + } + return false; +}; + +module.exports = function nodePolyfillsOverride({ log, cwd } = {}) { + const { resolveId, load, transform } = nodePolyfills(); + const overridesDir = join(cwd, "_polyfill-overrides_"); return { name: "polyfill-node-override", resolveId: function (importee, importer, options) { - if (importee === "http2") { - return { id: "http2?node-polyfill-override", moduleSideEffects: false }; - } - if (importee === "async_hooks") { - return { id: "async_hooks?node-polyfill-override", moduleSideEffects: false }; - } - if (importee.startsWith("node:")) { - return resolveId.call(this, importee.substr("node:".length), importer, options); + if (isBuiltInModule(importee)) { + const builtInModule = importee.startsWith("node:") ? importee.substr("node:".length) : importee; + if (existsSync(join(overridesDir, `${builtInModule}.js`))) { + return { id: `${PREFIX}${builtInModule}.js`, moduleSideEffects: false }; + } + const resolvedId = resolveId.call(this, builtInModule, importer, options); + if (resolvedId) { + return resolvedId; + } else { + return { id: `${builtInModule}?polyfill-node-ignore`, moduleSideEffects: false }; + } } - return null; }, - load: function (source) { - if (source === "http2?node-polyfill-override") { - return `export const constants = { - HTTP2_HEADER_AUTHORITY: "authority", - HTTP2_HEADER_METHOD: "method", - HTTP2_HEADER_PATH: "path", - HTTP2_HEADER_SCHEME: "scheme", - HTTP2_HEADER_CONTENT_LENGTH: "content-length", - HTTP2_HEADER_EXPECT: "expect", - HTTP2_HEADER_STATUS: "status" - };`; - } - if (source === "async_hooks?node-polyfill-override") { - return `export class AsyncResource {};`; + load: function (importee) { + if (importee.startsWith(PREFIX)) { + const builtInModule = importee.substr(PREFIX_LENGTH); + let content; + if (existsSync(join(overridesDir, `${builtInModule}`))) { + content = readFileSync(join(overridesDir, `${builtInModule}`), { encoding: "utf8" }); + } else { + content = load.apply(this, arguments); + } + return content; + } else if (importee.endsWith("?polyfill-node-ignore")) { + return ""; } return null; }, }; }; + +// prevent the renaming of global, process, Buffer in any module +// => needs to be used as a standalone rollup plugin in build +// !!!! KEEP IN SYNC WITH >> rollup-plugin-polyfill-node << !!!! +module.exports.inject = function nodePolyfillsOverrideInject() { + return inject({ + process: PREFIX + "process", + Buffer: [PREFIX + "buffer", "Buffer"], + global: PREFIX + "global", + __filename: FILENAME_PATH, + __dirname: DIRNAME_PATH, + }); +}; diff --git a/packages/ui5-tooling-modules/lib/util.js b/packages/ui5-tooling-modules/lib/util.js index 9d90b7230..1d6d879ab 100755 --- a/packages/ui5-tooling-modules/lib/util.js +++ b/packages/ui5-tooling-modules/lib/util.js @@ -4,12 +4,10 @@ const { existsSync } = require("fs"); const { readFile, stat } = require("fs").promises; const rollup = require("rollup"); -const { nodeResolve } = require("@rollup/plugin-node-resolve"); const commonjs = require("@rollup/plugin-commonjs"); const json = require("@rollup/plugin-json"); const nodePolyfills = require("rollup-plugin-polyfill-node"); const nodePolyfillsOverride = require("./rollup-plugin-polyfill-node-override"); -const nodePolyfillsIgnore = require("./rollup-plugin-polyfill-node-ignore"); const amdCustom = require("./rollup-plugin-amd-custom"); const skipAssets = require("./rollup-plugin-skip-assets"); const injectESModule = require("./rollup-plugin-inject-esmodule"); @@ -31,6 +29,9 @@ const chunkToModulePath = {}; // local cache of negative modules (avoid additional lookups) const modulesNegativeCache = []; +// main field processing order (for resolveModule) +const defaultExportsFields = ["browser", "import", "require", "default"]; + // main field processing order (for nodeResolve and resolveModule) const defaultMainFields = ["browser", "module", "main"]; @@ -104,10 +105,11 @@ module.exports = function (log) { * @param {string} options.cwd current working directory * @param {string[]} options.depPaths paths of the dependencies (in addition for cwd) * @param {string[]} options.mainFields an order of main fields to check in package.json + * @param {string[]} options.exportsFields an order of exports fields to check in package.json * @returns {string} the path of the module in the filesystem */ // ignore module paths starting with a segment from the ignore list (TODO: maybe a better check?) - resolveModule: function resolveModule(moduleName, { cwd, depPaths, mainFields } = {}) { + resolveModule: function resolveModule(moduleName, { cwd, depPaths, mainFields, exportsFields } = {}) { // default the current working directory cwd = cwd || process.cwd(); // if a module is listed in the negative cache, we ignore it! @@ -116,8 +118,9 @@ module.exports = function (log) { } // package.json of app const pkg = require(path.join(cwd, "package.json")); - // default the mainFields + // default the mainFields and exportsFields mainFields = mainFields || defaultMainFields; + exportsFields = exportsFields || defaultExportsFields; // retrieve or create a resolved module log.verbose(`Resolving ${moduleName} [${mainFields}]...`); // no module found => resolve it @@ -131,16 +134,42 @@ module.exports = function (log) { try { const pckJsonModuleName = path.join(moduleName, "package.json"); const pkgJson = require(pckJsonModuleName); - // resolve the main field from the package.json - for (const field of mainFields) { - if (typeof pkgJson?.[field] === "string") { - modulePath = path.join(path.dirname(resolveNodeModule(pckJsonModuleName, cwd, depPaths)), pkgJson?.[field]); - break; + const resolveModulePath = function (exports, fields) { + for (const field of fields) { + if (typeof exports[field] === "string") { + modulePath = path.join(path.dirname(resolveNodeModule(pckJsonModuleName, cwd, depPaths)), exports[field]); + // reset the module path if it doesn't exist + if (!existsSync(modulePath)) { + modulePath = undefined; + } else { + return modulePath; + } + } } + }; + // resolve the module path from exports information + // 1.) the browser field in package.json > exports > "." + if (typeof pkgJson?.exports?.["."] === "object" && typeof pkgJson?.exports?.["."].browser === "object") { + modulePath = resolveModulePath(pkgJson.exports["."].browser, exportsFields); } - // reset the module path if it doesn't exist - if (!existsSync(modulePath)) { - modulePath = undefined; + // 2.) the browser field in package.json + if (!modulePath) { + modulePath = resolveModulePath(pkgJson, ["browser"]); + } + // 3.) the fields in package.json > exports > "." + if (!modulePath && typeof pkgJson?.exports?.["."] === "object") { + Object.values(pkgJson?.exports?.["."]).forEach((entry) => { + if (!modulePath && typeof entry === "object") { + modulePath = resolveModulePath([entry, exportsFields]); + } + }); + if (!modulePath) { + modulePath = resolveModulePath([pkgJson?.exports?.["."], exportsFields]); + } + } + // 4.) the fields in package.json + if (!modulePath) { + modulePath = resolveModulePath(pkgJson, mainFields); } } catch (err) { // gracefully ignore the error @@ -174,7 +203,6 @@ module.exports = function (log) { * @returns {string} the bundle */ createBundle: async function createBundle(moduleName, { cwd, depPaths, mainFields, beforePlugins, afterPlugins, isMiddleware } = {}) { - // create a bundle const bundle = await rollup.rollup({ input: moduleName, context: "exports" /* this is normally converted to undefined, but should be exports in our case! */, @@ -182,27 +210,31 @@ module.exports = function (log) { ...(beforePlugins || []), replace({ preventAssignment: false, + delimiters: ["\\b", "\\b"], values: { - "process.env.NODE_ENV": JSON.stringify("development"), + "process.env.NODE_ENV": JSON.stringify(isMiddleware ? "development" : "production"), + "process.versions.node": JSON.stringify("18.15.0"), // needed for some modules to select features }, }), - nodePolyfillsOverride(), - nodePolyfills(), - nodePolyfillsIgnore(), injectESModule(), skipAssets({ log, extensions: ["css"], }), + json(), commonjs({ defaultIsModuleExports: true, }), amdCustom(), - json(), - nodeResolve({ - mainFields, - preferBuiltins: false, + // node polyfills/resolution must happen after + // commonjs and amd to ensure e.g. exports is + // properly handled by those plugins + nodePolyfillsOverride({ + log, + cwd, }), + nodePolyfills(), + nodePolyfillsOverride.inject(), pnpmResolve({ resolveModule: function (moduleName) { return that.resolveModule(moduleName, { cwd, depPaths, mainFields }); @@ -233,6 +265,7 @@ module.exports = function (log) { amd: { define: "sap.ui.define", }, + //generatedCode: "es2015", entryFileNames: `${moduleName}.js`, chunkFileNames: `${moduleName}/[hash].js`, sourcemap: false, // isMiddleware ? "inline" : true @@ -261,6 +294,7 @@ module.exports = function (log) { */ getResource: async function getResource(moduleName, { skipCache, debug, keepDynamicImports } = {}, { cwd, depPaths, skipTransform, isMiddleware } = {}) { let bundling = false; + cwd = cwd || process.cwd(); try { // in case of chunks are requested, we lookup the original module @@ -369,6 +403,7 @@ module.exports = function (log) { if (bundling) { log.error(`Couldn't bundle ${moduleName}: ${err}`, err); } + console.error(err); } }, diff --git a/packages/ui5-tooling-modules/package.json b/packages/ui5-tooling-modules/package.json index dce9ce8aa..06d85993e 100644 --- a/packages/ui5-tooling-modules/package.json +++ b/packages/ui5-tooling-modules/package.json @@ -27,8 +27,8 @@ "@buxlabs/amd-to-es6": "^0.16.3", "@javascript-obfuscator/escodegen": "^2.3.0", "@rollup/plugin-commonjs": "^25.0.7", + "@rollup/plugin-inject": "^5.0.5", "@rollup/plugin-json": "^6.0.1", - "@rollup/plugin-node-resolve": "^15.2.3", "@rollup/plugin-replace": "^5.0.5", "@rollup/pluginutils": "^5.1.0", "espree": "^9.6.1", diff --git a/packages/ui5-tooling-modules/test/__snap__/@octokit/core.js b/packages/ui5-tooling-modules/test/__snap__/@octokit/core.js index 18c44817c..d64cb5365 100644 --- a/packages/ui5-tooling-modules/test/__snap__/@octokit/core.js +++ b/packages/ui5-tooling-modules/test/__snap__/@octokit/core.js @@ -1,1164 +1,1396 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; - function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - if (typeof process === "object" && "version" in process) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; - } - return ""; - } - - var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - - var beforeAfterHook = {exports: {}}; + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$1.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$1.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } - var register_1 = register$1; - function register$1(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); } - - if (!options) { - options = {}; + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); } - - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register$1.bind(null, state, name, callback, options); - }, method)(); + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } } - return Promise.resolve().then(function () { - if (!state.registry[name]) { - return method(options); - } - return state.registry[name].reduce(function (method, registered) { - return registered.hook.bind(null, method, options); - }, method)(); - }); - } - var add = addHook$1; + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; - function addHook$1(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; } - - if (kind === "before") { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)); - }; + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; } - - 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; - }); - }; + if (queue.length) { + drainQueue(); } + } - if (kind === "error") { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options); - }); - }; + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser$1 = true; + var env = {}; + var argv = []; + var version = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop() {} + + var on = noop; + var addListener = noop; + var once$2 = noop; + var off = noop; + var removeListener = noop; + var removeAllListeners = noop; + var emit = noop; + + function binding(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance = global$1.performance || {}; + var performanceNow = + performance.now || + performance.mozNow || + performance.msNow || + performance.oNow || + performance.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var browser$1$1 = { + nextTick: nextTick, + title: title, + browser: browser$1, + env: env, + argv: argv, + version: version, + versions: versions, + on: on, + addListener: addListener, + once: once$2, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; + + function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; + } + if (typeof browser$1$1 === "object" && "version" in browser$1$1) { + return `Node.js/${browser$1$1.version.substr(1)} (${browser$1$1.platform}; ${browser$1$1.arch})`; } + return ""; + } - state.registry[name].push({ - hook: hook, - orig: orig, - }); + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; + + var beforeAfterHook = {exports: {}}; + + var register_1 = register$1; + + function register$1(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); } - var remove = removeHook$1; + if (!options) { + options = {}; + } - function removeHook$1(state, name, method) { + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register$1.bind(null, state, name, callback, options); + }, method)(); + } + + return Promise.resolve().then(function () { if (!state.registry[name]) { - return; + return method(options); } - var index = state.registry[name] - .map(function (registered) { - return registered.orig; - }) - .indexOf(method); + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); + } - if (index === -1) { - return; - } + var add = addHook$1; - state.registry[name].splice(index, 1); + function addHook$1(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; } - var register = register_1; - var addHook = add; - var removeHook = remove; - - // 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); - }); + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; } - function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {}, + 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; + }); }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; } - function HookCollection() { - var state = { - registry: {}, + if (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); }; + } - var hook = register.bind(null, state); - bindApi(hook, state); + state.registry[name].push({ + hook: hook, + orig: orig, + }); + } - return hook; + var remove = removeHook$1; + + function removeHook$1(state, name, method) { + if (!state.registry[name]) { + return; } - 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; - } - return HookCollection(); + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); + + if (index === -1) { + return; } - Hook.Singular = HookSingular.bind(); - Hook.Collection = HookCollection.bind(); + state.registry[name].splice(index, 1); + } + + var register = register_1; + var addHook = add; + var removeHook = remove; + + // 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); + }); + } - beforeAfterHook.exports = Hook; - // expose constructors as a named property for TypeScript - beforeAfterHook.exports.Hook = Hook; - beforeAfterHook.exports.Singular = Hook.Singular; - var Collection = beforeAfterHook.exports.Collection = Hook.Collection; + function HookSingular() { + var singularHookName = "h"; + var singularHookState = { + registry: {}, + }; + var singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; + } + + function HookCollection() { + var state = { + registry: {}, + }; - /*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ + var hook = register.bind(null, state); + bindApi(hook, state); + + return hook; + } - function isObject(o) { - return Object.prototype.toString.call(o) === '[object Object]'; + 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; } + return HookCollection(); + } - function isPlainObject(o) { - var ctor,prot; + Hook.Singular = HookSingular.bind(); + Hook.Collection = HookCollection.bind(); - if (isObject(o) === false) return false; + beforeAfterHook.exports = Hook; + // expose constructors as a named property for TypeScript + beforeAfterHook.exports.Hook = Hook; + beforeAfterHook.exports.Singular = Hook.Singular; + var Collection = beforeAfterHook.exports.Collection = Hook.Collection; - // If has modified constructor - ctor = o.constructor; - if (ctor === undefined) return true; + var isPlainObject$1 = {}; - // If has modified prototype - prot = ctor.prototype; - if (isObject(prot) === false) return false; + Object.defineProperty(isPlainObject$1, '__esModule', { value: true }); - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; - } + /*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ - // Most likely a plain Object - return true; - } + function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; + } - // pkg/dist-src/util/lowercase-keys.js - function lowercaseKeys(object) { - if (!object) { - return {}; - } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); - } - function mergeDeep(defaults, options) { - const result = Object.assign({}, defaults); - Object.keys(options).forEach((key) => { - if (isPlainObject(options[key])) { - if (!(key in defaults)) - Object.assign(result, { [key]: options[key] }); - else - result[key] = mergeDeep(defaults[key], options[key]); - } else { - Object.assign(result, { [key]: options[key] }); - } - }); - return result; - } + function isPlainObject(o) { + var ctor,prot; - // pkg/dist-src/util/remove-undefined-properties.js - function removeUndefinedProperties(obj) { - for (const key in obj) { - if (obj[key] === void 0) { - delete obj[key]; - } - } - return obj; + 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; + + // If constructor does not have an Object-specific method + if (prot.hasOwnProperty('isPrototypeOf') === false) { + return false; } - // pkg/dist-src/merge.js - function merge(defaults, route, options) { - if (typeof route === "string") { - let [method, url] = route.split(" "); - options = Object.assign(url ? { method, url } : { url: method }, options); + // Most likely a plain Object + return true; + } + + var isPlainObject_2 = isPlainObject$1.isPlainObject = isPlainObject; + + // pkg/dist-src/util/lowercase-keys.js + function lowercaseKeys(object) { + if (!object) { + return {}; + } + return Object.keys(object).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object[key]; + return newObj; + }, {}); + } + function mergeDeep(defaults, options) { + const result = Object.assign({}, defaults); + Object.keys(options).forEach((key) => { + if (isPlainObject_2(options[key])) { + if (!(key in defaults)) + Object.assign(result, { [key]: options[key] }); + else + result[key] = mergeDeep(defaults[key], options[key]); } else { - options = Object.assign({}, route); + Object.assign(result, { [key]: options[key] }); } - options.headers = lowercaseKeys(options.headers); - removeUndefinedProperties(options); - removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); - if (defaults && defaults.mediaType.previews.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter((preview) => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); + }); + return result; + } + + // pkg/dist-src/util/remove-undefined-properties.js + function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === void 0) { + delete obj[key]; } - mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map( - (preview) => preview.replace(/-preview/, "") - ); - return mergedOptions; } - - // pkg/dist-src/util/add-query-parameters.js - function addQueryParameters(url, parameters) { - const separator = /\?/.test(url) ? "&" : "?"; - const names = Object.keys(parameters); - if (names.length === 0) { - return url; - } - return url + separator + names.map((name) => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); - } - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); + return obj; + } + + // pkg/dist-src/merge.js + function merge(defaults, route, options) { + if (typeof route === "string") { + let [method, url] = route.split(" "); + options = Object.assign(url ? { method, url } : { url: method }, options); + } else { + options = Object.assign({}, route); } - - // pkg/dist-src/util/extract-url-variable-names.js - var urlVariableRegex = /\{[^}]+\}/g; - function removeNonChars(variableName) { - return variableName.replace(/^\W+|\W+$/g, "").split(/,/); + options.headers = lowercaseKeys(options.headers); + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); + if (defaults && defaults.mediaType.previews.length) { + mergedOptions.mediaType.previews = defaults.mediaType.previews.filter((preview) => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); + } + mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map( + (preview) => preview.replace(/-preview/, "") + ); + return mergedOptions; + } + + // pkg/dist-src/util/add-query-parameters.js + function addQueryParameters(url, parameters) { + const separator = /\?/.test(url) ? "&" : "?"; + const names = Object.keys(parameters); + if (names.length === 0) { + return url; } - function extractUrlVariableNames(url) { - const matches = url.match(urlVariableRegex); - if (!matches) { - return []; + return url + separator + names.map((name) => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); } - return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); + } + + // pkg/dist-src/util/extract-url-variable-names.js + var urlVariableRegex = /\{[^}]+\}/g; + function removeNonChars(variableName) { + return variableName.replace(/^\W+|\W+$/g, "").split(/,/); + } + function extractUrlVariableNames(url) { + const matches = url.match(urlVariableRegex); + if (!matches) { + return []; } + return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); + } - // pkg/dist-src/util/omit.js - function omit(object, keysToOmit) { - return Object.keys(object).filter((option) => !keysToOmit.includes(option)).reduce((obj, key) => { - obj[key] = object[key]; - return obj; - }, {}); + // pkg/dist-src/util/omit.js + function omit(object, keysToOmit) { + return Object.keys(object).filter((option) => !keysToOmit.includes(option)).reduce((obj, key) => { + obj[key] = object[key]; + return obj; + }, {}); + } + + // pkg/dist-src/util/url-template.js + function encodeReserved(str) { + return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { + if (!/%[0-9A-Fa-f]/.test(part)) { + part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); + } + return part; + }).join(""); + } + function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); + } + function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; } - - // pkg/dist-src/util/url-template.js - function encodeReserved(str) { - return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { - if (!/%[0-9A-Fa-f]/.test(part)) { - part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); + } + function isDefined(value) { + return value !== void 0 && value !== null; + } + function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; + } + function getValues(context, operator, key, modifier) { + var value = context[key], result = []; + if (isDefined(value) && value !== "") { + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + value = value.toString(); + if (modifier && modifier !== "*") { + value = value.substring(0, parseInt(modifier, 10)); } - return part; - }).join(""); - } - function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); - } - function encodeValue(operator, value, key) { - value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); - if (key) { - return encodeUnreserved(key) + "=" + value; + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") + ); } else { - return value; - } - } - function isDefined(value) { - return value !== void 0 && value !== null; - } - function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; - } - function getValues(context, operator, key, modifier) { - var value = context[key], result = []; - if (isDefined(value) && value !== "") { - if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { - value = value.toString(); - if (modifier && modifier !== "*") { - value = value.substring(0, parseInt(modifier, 10)); + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined(value[k])) { - result.push(encodeValue(operator, value[k], k)); - } - }); - } + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); - } - }); - } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); - } + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + tmp.push(encodeUnreserved(k)); + tmp.push(encodeValue(operator, value[k].toString())); + } + }); } - } - } else { - if (operator === ";") { - if (isDefined(value)) { - result.push(encodeUnreserved(key)); + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); } } - return result; - } - function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } } - function expand(template, context) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - return template.replace( - /\{([^\{\}]+)\}|([^\{\}]+)/g, - function(_, expression, literal) { - if (expression) { - let operator = ""; - const values = []; - if (operators.indexOf(expression.charAt(0)) !== -1) { - operator = expression.charAt(0); - expression = expression.substr(1); - } - expression.split(/,/g).forEach(function(variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; - } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); + return result; + } + function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; + } + function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + return template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); + } + expression.split(/,/g).forEach(function(variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); + if (operator && operator !== "+") { + var separator = ","; + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; } + return (values.length !== 0 ? operator : "") + values.join(separator); } else { - return encodeReserved(literal); + return values.join(","); } + } else { + return encodeReserved(literal); } - ); + } + ); + } + + // pkg/dist-src/parse.js + function parse(options) { + let method = options.method.toUpperCase(); + let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit(options, [ + "method", + "baseUrl", + "url", + "headers", + "request", + "mediaType" + ]); + const urlVariableNames = extractUrlVariableNames(url); + url = parseUrl(url).expand(parameters); + if (!/^http/.test(url)) { + url = options.baseUrl + url; } - - // pkg/dist-src/parse.js - function parse(options) { - let method = options.method.toUpperCase(); - let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); - let headers = Object.assign({}, options.headers); - let body; - let parameters = omit(options, [ - "method", - "baseUrl", - "url", - "headers", - "request", - "mediaType" - ]); - const urlVariableNames = extractUrlVariableNames(url); - url = parseUrl(url).expand(parameters); - if (!/^http/.test(url)) { - url = options.baseUrl + url; + const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit(parameters, omittedParameters); + const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); + if (!isBinaryRequest) { + if (options.mediaType.format) { + headers.accept = headers.accept.split(/,/).map( + (preview) => preview.replace( + /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, + `application/vnd$1$2.${options.mediaType.format}` + ) + ).join(","); } - const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit(parameters, omittedParameters); - const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); - if (!isBinaryRequest) { - if (options.mediaType.format) { - headers.accept = headers.accept.split(/,/).map( - (preview) => preview.replace( - /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, - `application/vnd$1$2.${options.mediaType.format}` - ) - ).join(","); - } - if (options.mediaType.previews.length) { - const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; - headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); - } + if (options.mediaType.previews.length) { + const previewsFromAcceptHeader = headers.accept.match(/[\w-]+(?=-preview)/g) || []; + headers.accept = previewsFromAcceptHeader.concat(options.mediaType.previews).map((preview) => { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); } - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); + } + if (["GET", "HEAD"].includes(method)) { + url = addQueryParameters(url, remainingParameters); + } else { + if ("data" in remainingParameters) { + body = remainingParameters.data; } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; - } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } + if (Object.keys(remainingParameters).length) { + body = remainingParameters; } } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; - } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; - } - return Object.assign( - { method, url, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); } - - // pkg/dist-src/endpoint-with-defaults.js - function endpointWithDefaults(defaults, route, options) { - return parse(merge(defaults, route, options)); + if (!headers["content-type"] && typeof body !== "undefined") { + headers["content-type"] = "application/json; charset=utf-8"; } - - // pkg/dist-src/with-defaults.js - function withDefaults$2(oldDefaults, newDefaults) { - const DEFAULTS2 = merge(oldDefaults, newDefaults); - const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); - return Object.assign(endpoint2, { - DEFAULTS: DEFAULTS2, - defaults: withDefaults$2.bind(null, DEFAULTS2), - merge: merge.bind(null, DEFAULTS2), - parse - }); + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; } + return Object.assign( + { method, url, headers }, + typeof body !== "undefined" ? { body } : null, + options.request ? { request: options.request } : null + ); + } + + // pkg/dist-src/endpoint-with-defaults.js + function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); + } + + // pkg/dist-src/with-defaults.js + function withDefaults$2(oldDefaults, newDefaults) { + const DEFAULTS2 = merge(oldDefaults, newDefaults); + const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); + return Object.assign(endpoint2, { + DEFAULTS: DEFAULTS2, + defaults: withDefaults$2.bind(null, DEFAULTS2), + merge: merge.bind(null, DEFAULTS2), + parse + }); + } + + // pkg/dist-src/version.js + var VERSION$3 = "7.0.6"; + + // pkg/dist-src/defaults.js + var userAgent = `octokit-endpoint.js/${VERSION$3} ${getUserAgent()}`; + var DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "", + previews: [] + } + }; - // pkg/dist-src/version.js - var VERSION$3 = "7.0.6"; - - // pkg/dist-src/defaults.js - var userAgent = `octokit-endpoint.js/${VERSION$3} ${getUserAgent()}`; - var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "", - previews: [] - } - }; - - // pkg/dist-src/index.js - var endpoint = withDefaults$2(null, DEFAULTS); - - var browser = {exports: {}}; + // pkg/dist-src/index.js + var endpoint = withDefaults$2(null, DEFAULTS); - (function (module, exports) { + var browser = {exports: {}}; - // ref: https://github.com/tc39/proposal-global - var getGlobal = function () { - // the only reliable means to get the global object is - // `Function('return this')()` - // However, this causes CSP violations in Chrome apps. - if (typeof self !== 'undefined') { return self; } - if (typeof window !== 'undefined') { return window; } - if (typeof commonjsGlobal !== 'undefined') { return commonjsGlobal; } - throw new Error('unable to locate global object'); - }; + (function (module, exports) { - var globalObject = getGlobal(); + // ref: https://github.com/tc39/proposal-global + var getGlobal = function () { + // the only reliable means to get the global object is + // `Function('return this')()` + // However, this causes CSP violations in Chrome apps. + if (typeof self !== 'undefined') { return self; } + if (typeof window !== 'undefined') { return window; } + if (typeof commonjsGlobal !== 'undefined') { return commonjsGlobal; } + throw new Error('unable to locate global object'); + }; - module.exports = exports = globalObject.fetch; + var globalObject = getGlobal(); - // Needed for TypeScript and Webpack. - if (globalObject.fetch) { - exports.default = globalObject.fetch.bind(globalObject); - } + module.exports = exports = globalObject.fetch; - exports.Headers = globalObject.Headers; - exports.Request = globalObject.Request; - exports.Response = globalObject.Response; - } (browser, browser.exports)); + // Needed for TypeScript and Webpack. + if (globalObject.fetch) { + exports.default = globalObject.fetch.bind(globalObject); + } - var browserExports = browser.exports; + exports.Headers = globalObject.Headers; + exports.Request = globalObject.Request; + exports.Response = globalObject.Response; + } (browser, browser.exports)); - class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) + var browserExports = browser.exports; - /* istanbul ignore next */ + class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } + /* istanbul ignore next */ - this.name = 'Deprecation'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); } + this.name = 'Deprecation'; } - var once$1 = {exports: {}}; + } - // Returns a wrapper function that returns a wrapped callback - // The wrapper function should do some stuff, and return a - // presumably different callback function. - // This makes sure that own properties are retained, so that - // decorations and such are not lost along the way. - var wrappy_1 = wrappy$1; - function wrappy$1 (fn, cb) { - if (fn && cb) return wrappy$1(fn)(cb) + var once$1 = {exports: {}}; - if (typeof fn !== 'function') - throw new TypeError('need wrapper function') + // Returns a wrapper function that returns a wrapped callback + // The wrapper function should do some stuff, and return a + // presumably different callback function. + // This makes sure that own properties are retained, so that + // decorations and such are not lost along the way. + var wrappy_1 = wrappy$1; + function wrappy$1 (fn, cb) { + if (fn && cb) return wrappy$1(fn)(cb) - Object.keys(fn).forEach(function (k) { - wrapper[k] = fn[k]; - }); + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') - return wrapper + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k]; + }); - function wrapper() { - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - var ret = fn.apply(this, args); - var cb = args[args.length-1]; - if (typeof ret === 'function' && ret !== cb) { - Object.keys(cb).forEach(function (k) { - ret[k] = cb[k]; - }); - } - return ret + return wrapper + + function wrapper() { + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; } + var ret = fn.apply(this, args); + var cb = args[args.length-1]; + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k]; + }); + } + return ret } + } - var wrappy = wrappy_1; - once$1.exports = wrappy(once); - once$1.exports.strict = wrappy(onceStrict); + var wrappy = wrappy_1; + once$1.exports = wrappy(once); + once$1.exports.strict = wrappy(onceStrict); - once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }); - - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }); + once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true }); - 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 - } - - 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 - } + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }); + }); - var onceExports = once$1.exports; + 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 + } + + 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 + } + + var onceExports = once$1.exports; + + const logOnceCode = onceExports((deprecation) => console.warn(deprecation)); + const logOnceHeaders = onceExports((deprecation) => console.warn(deprecation)); + /** + * Error with extra properties to help with debugging + */ + class RequestError extends Error { + constructor(message, statusCode, options) { + super(message); + // Maintains proper stack trace (only available on V8) + /* istanbul ignore next */ + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "HttpError"; + this.status = statusCode; + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; + } + // redact request credentials without mutating original request options + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]"), + }); + } + requestCopy.url = requestCopy.url + // client_id & client_secret can be passed as URL query parameters to increase rate limit + // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications + .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") + // OAuth tokens can be passed as URL query parameters, although it is not recommended + // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header + .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); + this.request = requestCopy; + // deprecations + Object.defineProperty(this, "code", { + get() { + logOnceCode(new Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); + return statusCode; + }, + }); + Object.defineProperty(this, "headers", { + get() { + logOnceHeaders(new Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`.")); + return headers || {}; + }, + }); + } + } - const logOnceCode = onceExports((deprecation) => console.warn(deprecation)); - const logOnceHeaders = onceExports((deprecation) => console.warn(deprecation)); - /** - * Error with extra properties to help with debugging - */ - class RequestError extends Error { - constructor(message, statusCode, options) { - super(message); - // Maintains proper stack trace (only available on V8) - /* istanbul ignore next */ - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.name = "HttpError"; - this.status = statusCode; - let headers; - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; - } - if ("response" in options) { - this.response = options.response; - headers = options.response.headers; - } - // redact request credentials without mutating original request options - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace(/ .*$/, " [REDACTED]"), - }); - } - requestCopy.url = requestCopy.url - // client_id & client_secret can be passed as URL query parameters to increase rate limit - // see https://developer.github.com/v3/#increasing-the-unauthenticated-rate-limit-for-oauth-applications - .replace(/\bclient_secret=\w+/g, "client_secret=[REDACTED]") - // OAuth tokens can be passed as URL query parameters, although it is not recommended - // see https://developer.github.com/v3/#oauth2-token-sent-in-a-header - .replace(/\baccess_token=\w+/g, "access_token=[REDACTED]"); - this.request = requestCopy; - // deprecations - Object.defineProperty(this, "code", { - get() { - logOnceCode(new Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); - return statusCode; - }, - }); - Object.defineProperty(this, "headers", { - get() { - logOnceHeaders(new Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`.")); - return headers || {}; - }, - }); - } - } + // pkg/dist-src/index.js - // pkg/dist-src/index.js + // pkg/dist-src/version.js + var VERSION$2 = "6.2.8"; - // pkg/dist-src/version.js - var VERSION$2 = "6.2.8"; + // pkg/dist-src/get-buffer-response.js + function getBufferResponse(response) { + return response.arrayBuffer(); + } - // pkg/dist-src/get-buffer-response.js - function getBufferResponse(response) { - return response.arrayBuffer(); + // pkg/dist-src/fetch-wrapper.js + function fetchWrapper(requestOptions) { + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + if (isPlainObject_2(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); } - - // pkg/dist-src/fetch-wrapper.js - function fetchWrapper(requestOptions) { - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); + let headers = {}; + let status; + let url; + const fetch = requestOptions.request && requestOptions.request.fetch || globalThis.fetch || /* istanbul ignore next */ + browserExports; + return fetch( + requestOptions.url, + Object.assign( + { + method: requestOptions.method, + body: requestOptions.body, + headers: requestOptions.headers, + redirect: requestOptions.redirect, + // duplex must be set if request.body is ReadableStream or Async Iterables. + // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. + ...requestOptions.body && { duplex: "half" } + }, + // `requestOptions.request.agent` type is incompatible + // see https://github.com/octokit/types.ts/pull/264 + requestOptions.request + ) + ).then(async (response) => { + url = response.url; + status = response.status; + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; } - let headers = {}; - let status; - let url; - const fetch = requestOptions.request && requestOptions.request.fetch || globalThis.fetch || /* istanbul ignore next */ - browserExports; - return fetch( - requestOptions.url, - Object.assign( - { - method: requestOptions.method, - body: requestOptions.body, - headers: requestOptions.headers, - redirect: requestOptions.redirect, - // duplex must be set if request.body is ReadableStream or Async Iterables. - // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. - ...requestOptions.body && { duplex: "half" } - }, - // `requestOptions.request.agent` type is incompatible - // see https://github.com/octokit/types.ts/pull/264 - requestOptions.request - ) - ).then(async (response) => { - url = response.url; - status = response.status; - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - if ("deprecation" in headers) { - const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/); - const deprecationLink = matches && matches.pop(); - log.warn( - `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { + if ("deprecation" in headers) { + const matches = headers.link && headers.link.match(/<([^>]+)>; rel="deprecation"/); + const deprecationLink = matches && matches.pop(); + log.warn( + `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { return; } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - throw new RequestError(response.statusText, status, { - response: { - url, - status, - headers, - data: void 0 - }, - request: requestOptions - }); - } - if (status === 304) { - throw new RequestError("Not modified", status, { - response: { - url, - status, - headers, - data: await getResponseData(response) - }, - request: requestOptions - }); - } - if (status >= 400) { - const data = await getResponseData(response); - const error = new RequestError(toErrorMessage(data), status, { - response: { - url, - status, - headers, - data - }, - request: requestOptions - }); - throw error; - } - return getResponseData(response); - }).then((data) => { - return { - status, - url, - headers, - data - }; - }).catch((error) => { - if (error instanceof RequestError) - throw error; - else if (error.name === "AbortError") - throw error; - throw new RequestError(error.message, 500, { + throw new RequestError(response.statusText, status, { + response: { + url, + status, + headers, + data: void 0 + }, request: requestOptions }); - }); - } - async function getResponseData(response) { - const contentType = response.headers.get("content-type"); - if (/application\/json/.test(contentType)) { - return response.json(); } - if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { - return response.text(); + if (status === 304) { + throw new RequestError("Not modified", status, { + response: { + url, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); } - return getBufferResponse(response); + if (status >= 400) { + const data = await getResponseData(response); + const error = new RequestError(toErrorMessage(data), status, { + response: { + url, + status, + headers, + data + }, + request: requestOptions + }); + throw error; + } + return getResponseData(response); + }).then((data) => { + return { + status, + url, + headers, + data + }; + }).catch((error) => { + if (error instanceof RequestError) + throw error; + else if (error.name === "AbortError") + throw error; + throw new RequestError(error.message, 500, { + request: requestOptions + }); + }); + } + async function getResponseData(response) { + const contentType = response.headers.get("content-type"); + if (/application\/json/.test(contentType)) { + return response.json(); } - function toErrorMessage(data) { - if (typeof data === "string") - return data; - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`; - } - return data.message; + if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { + return response.text(); + } + return getBufferResponse(response); + } + function toErrorMessage(data) { + if (typeof data === "string") + return data; + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`; } - return `Unknown error: ${JSON.stringify(data)}`; + return data.message; } - - // pkg/dist-src/with-defaults.js - function withDefaults$1(oldEndpoint, newDefaults) { - const endpoint2 = oldEndpoint.defaults(newDefaults); - const newApi = function(route, parameters) { - const endpointOptions = endpoint2.merge(route, parameters); - if (!endpointOptions.request || !endpointOptions.request.hook) { - return fetchWrapper(endpoint2.parse(endpointOptions)); - } - const request2 = (route2, parameters2) => { - return fetchWrapper( - endpoint2.parse(endpoint2.merge(route2, parameters2)) - ); - }; - Object.assign(request2, { - endpoint: endpoint2, - defaults: withDefaults$1.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); + return `Unknown error: ${JSON.stringify(data)}`; + } + + // pkg/dist-src/with-defaults.js + function withDefaults$1(oldEndpoint, newDefaults) { + const endpoint2 = oldEndpoint.defaults(newDefaults); + const newApi = function(route, parameters) { + const endpointOptions = endpoint2.merge(route, parameters); + if (!endpointOptions.request || !endpointOptions.request.hook) { + return fetchWrapper(endpoint2.parse(endpointOptions)); + } + const request2 = (route2, parameters2) => { + return fetchWrapper( + endpoint2.parse(endpoint2.merge(route2, parameters2)) + ); }; - return Object.assign(newApi, { + Object.assign(request2, { endpoint: endpoint2, defaults: withDefaults$1.bind(null, endpoint2) }); - } - - // pkg/dist-src/index.js - var request = withDefaults$1(endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION$2} ${getUserAgent()}` - } + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults$1.bind(null, endpoint2) }); + } - // pkg/dist-src/index.js + // pkg/dist-src/index.js + var request = withDefaults$1(endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION$2} ${getUserAgent()}` + } + }); + + // pkg/dist-src/index.js - // pkg/dist-src/version.js - var VERSION$1 = "5.0.6"; + // pkg/dist-src/version.js + var VERSION$1 = "5.0.6"; - // pkg/dist-src/error.js - function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: + // pkg/dist-src/error.js + function _buildMessageForResponseErrors(data) { + return `Request failed due to following response errors: ` + data.errors.map((e) => ` - ${e.message}`).join("\n"); + } + var GraphqlResponseError = class extends Error { + constructor(request2, headers, response) { + super(_buildMessageForResponseErrors(response)); + this.request = request2; + this.headers = headers; + this.response = response; + this.name = "GraphqlResponseError"; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } } - var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.name = "GraphqlResponseError"; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } + }; + + // pkg/dist-src/graphql.js + var NON_VARIABLE_OPTIONS = [ + "method", + "baseUrl", + "url", + "headers", + "request", + "query", + "mediaType" + ]; + var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; + var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; + function graphql(request2, query, options) { + if (options) { + if (typeof query === "string" && "query" in options) { + return Promise.reject( + new Error(`[@octokit/graphql] "query" cannot be used as variable name`) + ); } - }; - - // pkg/dist-src/graphql.js - var NON_VARIABLE_OPTIONS = [ - "method", - "baseUrl", - "url", - "headers", - "request", - "query", - "mediaType" - ]; - var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; - var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; - function graphql(request2, query, options) { - if (options) { - if (typeof query === "string" && "query" in options) { - return Promise.reject( - new Error(`[@octokit/graphql] "query" cannot be used as variable name`) - ); - } - for (const key in options) { - if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) - continue; - return Promise.reject( - new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`) - ); - } + for (const key in options) { + if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) + continue; + return Promise.reject( + new Error(`[@octokit/graphql] "${key}" cannot be used as variable name`) + ); } - const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; - const requestOptions = Object.keys( - parsedOptions - ).reduce((result, key) => { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; - } - if (!result.variables) { - result.variables = {}; - } - result.variables[key] = parsedOptions[key]; + } + const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; + const requestOptions = Object.keys( + parsedOptions + ).reduce((result, key) => { + if (NON_VARIABLE_OPTIONS.includes(key)) { + result[key] = parsedOptions[key]; return result; - }, {}); - const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; - if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { - requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; - } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data - ); - } - return response.data.data; - }); - } - - // pkg/dist-src/with-defaults.js - function withDefaults(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); - }; - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: newRequest.endpoint - }); + if (!result.variables) { + result.variables = {}; + } + result.variables[key] = parsedOptions[key]; + return result; + }, {}); + const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; + if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { + requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); } + return request2(requestOptions).then((response) => { + if (response.data.errors) { + const headers = {}; + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } + throw new GraphqlResponseError( + requestOptions, + headers, + response.data + ); + } + return response.data.data; + }); + } - // pkg/dist-src/index.js - withDefaults(request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION$1} ${getUserAgent()}` - }, + // pkg/dist-src/with-defaults.js + function withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); + } + + // pkg/dist-src/index.js + withDefaults(request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION$1} ${getUserAgent()}` + }, + method: "POST", + url: "/graphql" + }); + function withCustomRequest(customRequest) { + return withDefaults(customRequest, { method: "POST", url: "/graphql" }); - function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" - }); - } + } + + // pkg/dist-src/auth.js + var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; + var REGEX_IS_INSTALLATION = /^ghs_/; + var REGEX_IS_USER_TO_SERVER = /^ghu_/; + async function auth(token) { + const isApp = token.split(/\./).length === 3; + const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); + const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); + const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; + return { + type: "token", + token, + tokenType + }; + } - // pkg/dist-src/auth.js - var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; - var REGEX_IS_INSTALLATION = /^ghs_/; - var REGEX_IS_USER_TO_SERVER = /^ghu_/; - async function auth(token) { - const isApp = token.split(/\./).length === 3; - const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); - const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); - const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; - return { - type: "token", - token, - tokenType - }; + // pkg/dist-src/with-authorization-prefix.js + function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; } - - // pkg/dist-src/with-authorization-prefix.js - function withAuthorizationPrefix(token) { - if (token.split(/\./).length === 3) { - return `bearer ${token}`; - } - return `token ${token}`; + return `token ${token}`; + } + + // pkg/dist-src/hook.js + async function hook(token, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); + } + + // pkg/dist-src/index.js + var createTokenAuth = function createTokenAuth2(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); } - - // pkg/dist-src/hook.js - async function hook(token, request, route, parameters) { - const endpoint = request.endpoint.merge( - route, - parameters + if (typeof token !== "string") { + throw new Error( + "[@octokit/auth-token] Token passed to createTokenAuth is not a string" ); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); } + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); + }; - // pkg/dist-src/index.js - var createTokenAuth = function createTokenAuth2(token) { - if (!token) { - throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); - } - if (typeof token !== "string") { - throw new Error( - "[@octokit/auth-token] Token passed to createTokenAuth is not a string" - ); - } - token = token.replace(/^(token|bearer) +/i, ""); - return Object.assign(auth.bind(null, token), { - hook: hook.bind(null, token) - }); - }; - - // pkg/dist-src/index.js + // pkg/dist-src/index.js - // pkg/dist-src/version.js - var VERSION = "4.2.4"; + // pkg/dist-src/version.js + var VERSION = "4.2.4"; - // pkg/dist-src/index.js - var Octokit = class { - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; - if (typeof defaults === "function") { - super(defaults(options)); - return; - } - super( - Object.assign( - {}, - defaults, - options, - options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null - ) - ); - } - }; - return OctokitWithDefaults; - } - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ - static plugin(...newPlugins) { - var _a; - const currentPlugins = this.plugins; - const NewOctokit = (_a = class extends this { - }, _a.plugins = currentPlugins.concat( - newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) - ), _a); - return NewOctokit; - } - constructor(options = {}) { - const hook = new Collection(); - const requestDefaults = { - baseUrl: request.endpoint.DEFAULTS.baseUrl, - headers: {}, - request: Object.assign({}, options.request, { - // @ts-ignore internal usage only, no need to type - hook: hook.bind(null, "request") - }), - mediaType: { - previews: [], - format: "" + // pkg/dist-src/index.js + var Octokit = class { + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; + if (typeof defaults === "function") { + super(defaults(options)); + return; } - }; - requestDefaults.headers["user-agent"] = [ - options.userAgent, - `octokit-core.js/${VERSION} ${getUserAgent()}` - ].filter(Boolean).join(" "); - if (options.baseUrl) { - requestDefaults.baseUrl = options.baseUrl; - } - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; + super( + Object.assign( + {}, + defaults, + options, + options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null + ) + ); } - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; + }; + return OctokitWithDefaults; + } + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ + static plugin(...newPlugins) { + var _a; + const currentPlugins = this.plugins; + const NewOctokit = (_a = class extends this { + }, _a.plugins = currentPlugins.concat( + newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) + ), _a); + return NewOctokit; + } + constructor(options = {}) { + const hook = new Collection(); + const requestDefaults = { + baseUrl: request.endpoint.DEFAULTS.baseUrl, + headers: {}, + request: Object.assign({}, options.request, { + // @ts-ignore internal usage only, no need to type + hook: hook.bind(null, "request") + }), + mediaType: { + previews: [], + format: "" } - this.request = request.defaults(requestDefaults); - this.graphql = withCustomRequest(this.request).defaults(requestDefaults); - this.log = Object.assign( - { - debug: () => { - }, - info: () => { - }, - warn: console.warn.bind(console), - error: console.error.bind(console) + }; + requestDefaults.headers["user-agent"] = [ + options.userAgent, + `octokit-core.js/${VERSION} ${getUserAgent()}` + ].filter(Boolean).join(" "); + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; + } + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } + this.request = request.defaults(requestDefaults); + this.graphql = withCustomRequest(this.request).defaults(requestDefaults); + this.log = Object.assign( + { + debug: () => { }, - options.log - ); - this.hook = hook; - if (!options.authStrategy) { - if (!options.auth) { - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - const auth = createTokenAuth(options.auth); - hook.wrap("request", auth.hook); - this.auth = auth; - } + info: () => { + }, + warn: console.warn.bind(console), + error: console.error.bind(console) + }, + options.log + ); + this.hook = hook; + if (!options.authStrategy) { + if (!options.auth) { + this.auth = async () => ({ + type: "unauthenticated" + }); } else { - const { authStrategy, ...otherOptions } = options; - const auth = authStrategy( - Object.assign( - { - request: this.request, - log: this.log, - // we pass the current octokit instance as well as its constructor options - // to allow for authentication strategies that return a new octokit instance - // that shares the same internal state as the current one. The original - // requirement for this was the "event-octokit" authentication strategy - // of https://github.com/probot/octokit-auth-probot. - octokit: this, - octokitOptions: otherOptions - }, - options.auth - ) - ); + const auth = createTokenAuth(options.auth); hook.wrap("request", auth.hook); this.auth = auth; } - const classConstructor = this.constructor; - classConstructor.plugins.forEach((plugin) => { - Object.assign(this, plugin(this, options)); - }); + } else { + const { authStrategy, ...otherOptions } = options; + const auth = authStrategy( + Object.assign( + { + request: this.request, + log: this.log, + // we pass the current octokit instance as well as its constructor options + // to allow for authentication strategies that return a new octokit instance + // that shares the same internal state as the current one. The original + // requirement for this was the "event-octokit" authentication strategy + // of https://github.com/probot/octokit-auth-probot. + octokit: this, + octokitOptions: otherOptions + }, + options.auth + ) + ); + hook.wrap("request", auth.hook); + this.auth = auth; } - }; - Octokit.VERSION = VERSION; - Octokit.plugins = []; + const classConstructor = this.constructor; + classConstructor.plugins.forEach((plugin) => { + Object.assign(this, plugin(this, options)); + }); + } + }; + Octokit.VERSION = VERSION; + Octokit.plugins = []; - const __esModule = true; + const __esModule = true; - exports.Octokit = Octokit; - exports.__esModule = __esModule; + exports.Octokit = Octokit; + exports.__esModule = __esModule; })); diff --git a/packages/ui5-tooling-modules/test/__snap__/@supabase/supabase-js.js b/packages/ui5-tooling-modules/test/__snap__/@supabase/supabase-js.js index e60bf5e1b..090be11aa 100644 --- a/packages/ui5-tooling-modules/test/__snap__/@supabase/supabase-js.js +++ b/packages/ui5-tooling-modules/test/__snap__/@supabase/supabase-js.js @@ -185,11 +185,10 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } (browser$1, browser$1.exports)); var browserExports = browser$1.exports; - var nodeFetch = browserExports; var browser = /*#__PURE__*/_mergeNamespaces({ __proto__: null, - default: nodeFetch + default: browserExports }, [browserExports]); // @ts-ignore @@ -208,7 +207,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; this.fetch = builder.fetch; } else if (typeof fetch === 'undefined') { - this.fetch = nodeFetch; + this.fetch = browserExports; } else { this.fetch = fetch; @@ -3586,7 +3585,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } } - const version$1 = '2.37.0'; + const version$1 = '2.39.0'; // constants.ts let JS_ENV = ''; @@ -3620,7 +3619,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; _fetch = customFetch; } else if (typeof fetch === 'undefined') { - _fetch = nodeFetch; + _fetch = browserExports; } else { _fetch = fetch; diff --git a/packages/ui5-tooling-modules/test/__snap__/axios.js b/packages/ui5-tooling-modules/test/__snap__/axios.js index 6a6ea1b18..1f37ad196 100644 --- a/packages/ui5-tooling-modules/test/__snap__/axios.js +++ b/packages/ui5-tooling-modules/test/__snap__/axios.js @@ -1,4 +1,1933 @@ -sap.ui.define(['exports'], (function (exports) { 'use strict'; +sap.ui.define((function () { 'use strict'; + + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; + var inited = false; + function init() { + inited = true; + var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + revLookup["-".charCodeAt(0)] = 62; + revLookup["_".charCodeAt(0)] = 63; + } + + function toByteArray(b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; + + if (len % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); + } + + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === "=" ? 2 : b64[len - 1] === "=" ? 1 : 0; + + // base64 is 4/3 + up to two characters of the original data + arr = new Arr((len * 3) / 4 - placeHolders); + + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; + + var L = 0; + + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xff; + arr[L++] = (tmp >> 8) & 0xff; + arr[L++] = tmp & 0xff; + } + + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xff; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xff; + arr[L++] = tmp & 0xff; + } + + return arr; + } + + function tripletToBase64(num) { + return lookup[(num >> 18) & 0x3f] + lookup[(num >> 12) & 0x3f] + lookup[(num >> 6) & 0x3f] + lookup[num & 0x3f]; + } + + function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2]; + output.push(tripletToBase64(tmp)); + } + return output.join(""); + } + + function fromByteArray(uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ""; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3f]; + output += "=="; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3f]; + output += lookup[(tmp << 2) & 0x3f]; + output += "="; + } + + parts.push(output); + + return parts.join(""); + } + + function read(buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << -nBits) - 1); + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << -nBits) - 1); + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); + } + + function write(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + } + + var toString$1 = {}.toString; + + var isArray$1 = + Array.isArray || + function (arr) { + return toString$1.call(arr) == "[object Array]"; + }; + + /*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ + /* eslint-disable no-proto */ + + var INSPECT_MAX_BYTES = 50; + + /** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Use Object implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * Due to various browser bugs, sometimes the Object implementation will be used even + * when the browser supports typed arrays. + * + * Note: + * + * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, + * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. + * + * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. + * + * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of + * incorrect length in some situations. + + * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they + * get the Object implementation, which is slower but behaves correctly. + */ + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; + + /* + * Export kMaxLength after typed array support is determined. + */ + kMaxLength(); + + function kMaxLength() { + return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff; + } + + function createBuffer(that, length) { + if (kMaxLength() < length) { + throw new RangeError("Invalid typed array length"); + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } + + return that; + } + + /** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + + function Buffer(arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length); + } + + // Common case. + if (typeof arg === "number") { + if (typeof encodingOrOffset === "string") { + throw new Error("If encoding is specified then the first argument must be a string"); + } + return allocUnsafe(this, arg); + } + return from(this, arg, encodingOrOffset, length); + } + + Buffer.poolSize = 8192; // not used by this implementation + + // TODO: Legacy, not needed anymore. Remove in next major version. + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr; + }; + + function from(that, value, encodingOrOffset, length) { + if (typeof value === "number") { + throw new TypeError('"value" argument must not be a number'); + } + + if (typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length); + } + + if (typeof value === "string") { + return fromString(that, value, encodingOrOffset); + } + + return fromObject(that, value); + } + + /** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length); + }; + + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== "undefined" && Symbol.species && Buffer[Symbol.species] === Buffer); + } + + function assertSize(size) { + if (typeof size !== "number") { + throw new TypeError('"size" argument must be a number'); + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative'); + } + } + + function alloc(that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size); + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === "string" ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill); + } + return createBuffer(that, size); + } + + /** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding); + }; + + function allocUnsafe(that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that; + } + + /** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size); + }; + /** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size); + }; + + function fromString(that, string, encoding) { + if (typeof encoding !== "string" || encoding === "") { + encoding = "utf8"; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding'); + } + + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); + + var actual = that.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } + + return that; + } + + function fromArrayLike(that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that; + } + + function fromArrayBuffer(that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer + + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError("'offset' is out of bounds"); + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError("'length' is out of bounds"); + } + + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } + + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that; + } + + function fromObject(that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); + + if (that.length === 0) { + return that; + } + + obj.copy(that, 0, 0, len); + return that; + } + + if (obj) { + if ((typeof ArrayBuffer !== "undefined" && obj.buffer instanceof ArrayBuffer) || "length" in obj) { + if (typeof obj.length !== "number" || isnan(obj.length)) { + return createBuffer(that, 0); + } + return fromArrayLike(that, obj); + } + + if (obj.type === "Buffer" && isArray$1(obj.data)) { + return fromArrayLike(that, obj.data); + } + } + + throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object."); + } + + function checked(length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError("Attempt to allocate Buffer larger than maximum " + "size: 0x" + kMaxLength().toString(16) + " bytes"); + } + return length | 0; + } + Buffer.isBuffer = isBuffer$1; + function internalIsBuffer(b) { + return !!(b != null && b._isBuffer); + } + + Buffer.compare = function compare(a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError("Arguments must be Buffers"); + } + + if (a === b) return 0; + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; + + Buffer.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "latin1": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return true; + default: + return false; + } + }; + + Buffer.concat = function concat(list, length) { + if (!isArray$1(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + + if (list.length === 0) { + return Buffer.alloc(0); + } + + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer; + }; + + function byteLength(string, encoding) { + if (internalIsBuffer(string)) { + return string.length; + } + if (typeof ArrayBuffer !== "undefined" && typeof ArrayBuffer.isView === "function" && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength; + } + if (typeof string !== "string") { + string = "" + string; + } + + var len = string.length; + if (len === 0) return 0; + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case "ascii": + case "latin1": + case "binary": + return len; + case "utf8": + case "utf-8": + case undefined: + return utf8ToBytes(string).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return len * 2; + case "hex": + return len >>> 1; + case "base64": + return base64ToBytes(string).length; + default: + if (loweredCase) return utf8ToBytes(string).length; // assume utf8 + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + } + Buffer.byteLength = byteLength; + + function slowToString(encoding, start, end) { + var loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return ""; + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return ""; + } + + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return ""; + } + + if (!encoding) encoding = "utf8"; + + while (true) { + switch (encoding) { + case "hex": + return hexSlice(this, start, end); + + case "utf8": + case "utf-8": + return utf8Slice(this, start, end); + + case "ascii": + return asciiSlice(this, start, end); + + case "latin1": + case "binary": + return latin1Slice(this, start, end); + + case "base64": + return base64Slice(this, start, end); + + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return utf16leSlice(this, start, end); + + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); + encoding = (encoding + "").toLowerCase(); + loweredCase = true; + } + } + } + + // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect + // Buffer instances. + Buffer.prototype._isBuffer = true; + + function swap(b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; + } + + Buffer.prototype.swap16 = function swap16() { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError("Buffer size must be a multiple of 16-bits"); + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this; + }; + + Buffer.prototype.swap32 = function swap32() { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError("Buffer size must be a multiple of 32-bits"); + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this; + }; + + Buffer.prototype.swap64 = function swap64() { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError("Buffer size must be a multiple of 64-bits"); + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this; + }; + + Buffer.prototype.toString = function toString() { + var length = this.length | 0; + if (length === 0) return ""; + if (arguments.length === 0) return utf8Slice(this, 0, length); + return slowToString.apply(this, arguments); + }; + + Buffer.prototype.equals = function equals(b) { + if (!internalIsBuffer(b)) throw new TypeError("Argument must be a Buffer"); + if (this === b) return true; + return Buffer.compare(this, b) === 0; + }; + + Buffer.prototype.inspect = function inspect() { + var str = ""; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString("hex", 0, max).match(/.{2}/g).join(" "); + if (this.length > max) str += " ... "; + } + return ""; + }; + + Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError("Argument must be a Buffer"); + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError("out of range index"); + } + + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return -1; + } + if (start >= end) { + return 1; + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0; + + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); + + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); + + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break; + } + } + + if (x < y) return -1; + if (y < x) return 1; + return 0; + }; + + // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, + // OR the last index of `val` in `buffer` at offset <= `byteOffset`. + // + // Arguments: + // - buffer - a Buffer to search + // - val - a string, Buffer, or number + // - byteOffset - an index into `buffer`; will be clamped to an int32 + // - encoding - an optional encoding, relevant is val is a string + // - dir - true for indexOf, false for lastIndexOf + function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1; + + // Normalize byteOffset + if (typeof byteOffset === "string") { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : buffer.length - 1; + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1; + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1; + } + + // Normalize val + if (typeof val === "string") { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1; + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === "number") { + val = val & 0xff; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === "function") { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); + } + + throw new TypeError("val must be string, number or Buffer"); + } + + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { + if (arr.length < 2 || val.length < 2) { + return -1; + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read(buf, i) { + if (indexSize === 1) { + return buf[i]; + } else { + return buf.readUInt16BE(i * indexSize); + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break; + } + } + if (found) return i; + } + } + + return -1; + } + + Buffer.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; + }; + + Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); + }; + + Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); + }; + + function hexWrite(buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError("Invalid hex string"); + + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i; + buf[offset + i] = parsed; + } + return i; + } + + function utf8Write(buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); + } + + function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length); + } + + function latin1Write(buf, string, offset, length) { + return asciiWrite(buf, string, offset, length); + } + + function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length); + } + + function ucs2Write(buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); + } + + Buffer.prototype.write = function write(string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = "utf8"; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === "string") { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = "utf8"; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported"); + } + + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError("Attempt to write outside buffer bounds"); + } + + if (!encoding) encoding = "utf8"; + + var loweredCase = false; + for (;;) { + switch (encoding) { + case "hex": + return hexWrite(this, string, offset, length); + + case "utf8": + case "utf-8": + return utf8Write(this, string, offset, length); + + case "ascii": + return asciiWrite(this, string, offset, length); + + case "latin1": + case "binary": + return latin1Write(this, string, offset, length); + + case "base64": + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length); + + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ucs2Write(this, string, offset, length); + + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } + }; + + Buffer.prototype.toJSON = function toJSON() { + return { + type: "Buffer", + data: Array.prototype.slice.call(this._arr || this, 0), + }; + }; + + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf); + } else { + return fromByteArray(buf.slice(start, end)); + } + } + + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = firstByte > 0xef ? 4 : firstByte > 0xdf ? 3 : firstByte > 0xbf ? 2 : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xc0) === 0x80) { + tempCodePoint = ((firstByte & 0x1f) << 0x6) | (secondByte & 0x3f); + if (tempCodePoint > 0x7f) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80) { + tempCodePoint = ((firstByte & 0xf) << 0xc) | ((secondByte & 0x3f) << 0x6) | (thirdByte & 0x3f); + if (tempCodePoint > 0x7ff && (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff)) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80 && (fourthByte & 0xc0) === 0x80) { + tempCodePoint = ((firstByte & 0xf) << 0x12) | ((secondByte & 0x3f) << 0xc) | ((thirdByte & 0x3f) << 0x6) | (fourthByte & 0x3f); + if (tempCodePoint > 0xffff && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xfffd; + bytesPerSequence = 1; + } else if (codePoint > 0xffff) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(((codePoint >>> 10) & 0x3ff) | 0xd800); + codePoint = 0xdc00 | (codePoint & 0x3ff); + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res); + } + + // Based on http://stackoverflow.com/a/22747272/680742, the browser with + // the lowest limit is Chrome, with 0x10000 args. + // We go 1 magnitude less, for safety + var MAX_ARGUMENTS_LENGTH = 0x1000; + + function decodeCodePointsArray(codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + var res = ""; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply(String, codePoints.slice(i, (i += MAX_ARGUMENTS_LENGTH))); + } + return res; + } + + function asciiSlice(buf, start, end) { + var ret = ""; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7f); + } + return ret; + } + + function latin1Slice(buf, start, end) { + var ret = ""; + end = Math.min(buf.length, end); + + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret; + } + + function hexSlice(buf, start, end) { + var len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + var out = ""; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out; + } + + function utf16leSlice(buf, start, end) { + var bytes = buf.slice(start, end); + var res = ""; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res; + } + + Buffer.prototype.slice = function slice(start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } + + return newBuf; + }; + + /* + * Need to make sure that buffer isn't trying to write out of bounds. + */ + function checkOffset(offset, ext, length) { + if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint"); + if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length"); + } + + Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val; + }; + + Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val; + }; + + Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset]; + }; + + Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8); + }; + + Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1]; + }; + + Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + this[offset + 3] * 0x1000000; + }; + + Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return this[offset] * 0x1000000 + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]); + }; + + Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val; + }; + + Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val; + }; + + Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return this[offset]; + return (0xff - this[offset] + 1) * -1; + }; + + Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return val & 0x8000 ? val | 0xffff0000 : val; + }; + + Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return val & 0x8000 ? val | 0xffff0000 : val; + }; + + Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24); + }; + + Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]; + }; + + Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4); + }; + + Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4); + }; + + Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8); + }; + + Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8); + }; + + function checkInt(buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) throw new RangeError("Index out of range"); + } + + Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var mul = 1; + var i = 0; + this[offset] = value & 0xff; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xff; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xff; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xff; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = value & 0xff; + return offset + 1; + }; + + function objectWriteUInt16(buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> ((littleEndian ? i : 1 - i) * 8); + } + } + + Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2; + }; + + Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2; + }; + + function objectWriteUInt32(buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> ((littleEndian ? i : 3 - i) * 8)) & 0xff; + } + } + + Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 0xff; + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4; + }; + + Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4; + }; + + Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xff; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = (((value / mul) >> 0) - sub) & 0xff; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xff; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = (((value / mul) >> 0) - sub) & 0xff; + } + + return offset + byteLength; + }; + + Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = value & 0xff; + return offset + 1; + }; + + Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2; + }; + + Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2; + }; + + Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4; + }; + + Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4; + }; + + function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError("Index out of range"); + if (offset < 0) throw new RangeError("Index out of range"); + } + + function writeFloat(buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; + } + + Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); + }; + + Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); + }; + + function writeDouble(buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; + } + + Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); + }; + + Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); + }; + + // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) + Buffer.prototype.copy = function copy(target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0; + if (target.length === 0 || this.length === 0) return 0; + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError("targetStart out of bounds"); + } + if (start < 0 || start >= this.length) throw new RangeError("sourceStart out of bounds"); + if (end < 0) throw new RangeError("sourceEnd out of bounds"); + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart); + } + + return len; + }; + + // Usage: + // buffer.fill(number[, offset[, end]]) + // buffer.fill(buffer[, offset[, end]]) + // buffer.fill(string[, offset[, end]][, encoding]) + Buffer.prototype.fill = function fill(val, start, end, encoding) { + // Handle string cases: + if (typeof val === "string") { + if (typeof start === "string") { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === "string") { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== "string") { + throw new TypeError("encoding must be a string"); + } + if (typeof encoding === "string" && !Buffer.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + } else if (typeof val === "number") { + val = val & 255; + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError("Out of range index"); + } + + if (end <= start) { + return this; + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === "number") { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this; + }; + + // HELPER FUNCTIONS + // ================ + + var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; + + function base64clean(str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ""); + // Node converts strings with length < 2 to '' + if (str.length < 2) return ""; + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + "="; + } + return str; + } + + function stringtrim(str) { + if (str.trim) return str.trim(); + return str.replace(/^\s+|\s+$/g, ""); + } + + function toHex(n) { + if (n < 16) return "0" + n.toString(16); + return n.toString(16); + } + + function utf8ToBytes(string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xd7ff && codePoint < 0xe000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xdbff) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + continue; + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + continue; + } + + // valid lead + leadSurrogate = codePoint; + + continue; + } + + // 2 leads in a row + if (codePoint < 0xdc00) { + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + leadSurrogate = codePoint; + continue; + } + + // valid surrogate pair + codePoint = (((leadSurrogate - 0xd800) << 10) | (codePoint - 0xdc00)) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break; + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break; + bytes.push((codePoint >> 0x6) | 0xc0, (codePoint & 0x3f) | 0x80); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break; + bytes.push((codePoint >> 0xc) | 0xe0, ((codePoint >> 0x6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break; + bytes.push((codePoint >> 0x12) | 0xf0, ((codePoint >> 0xc) & 0x3f) | 0x80, ((codePoint >> 0x6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80); + } else { + throw new Error("Invalid code point"); + } + } + + return bytes; + } + + function asciiToBytes(str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xff); + } + return byteArray; + } + + function utf16leToBytes(str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break; + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray; + } + + function base64ToBytes(str) { + return toByteArray(base64clean(str)); + } + + function blitBuffer(src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if (i + offset >= dst.length || i >= src.length) break; + dst[i + offset] = src[i]; + } + return i; + } + + function isnan(val) { + return val !== val; // eslint-disable-line no-self-compare + } + + // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence + // The _isBuffer check is for Safari 5-7 support, because it's missing + // Object.prototype.constructor. Remove this eventually + function isBuffer$1(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)); + } + + function isFastBuffer(obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj); + } + + // For Node v0.10 support. Remove this eventually. + function isSlowBuffer(obj) { + return typeof obj.readFloatLE === "function" && typeof obj.slice === "function" && isFastBuffer(obj.slice(0, 0)); + } + + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; function bind(fn, thisArg) { return function wrap() { @@ -288,7 +2217,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; const _global = (() => { /*eslint no-undef:0*/ if (typeof globalThis !== "undefined") return globalThis; - return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : global) + return typeof self !== "undefined" ? self : (typeof window !== 'undefined' ? window : commonjsGlobal) })(); const isContextDefined = (context) => !isUndefined(context) && context !== _global; @@ -737,7 +2666,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @returns {Error} The created error. */ - function AxiosError$1(message, code, config, request, response) { + function AxiosError(message, code, config, request, response) { Error.call(this); if (Error.captureStackTrace) { @@ -754,7 +2683,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; response && (this.response = response); } - utils$1.inherits(AxiosError$1, Error, { + utils$1.inherits(AxiosError, Error, { toJSON: function toJSON() { return { // Standard @@ -776,7 +2705,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } }); - const prototype$1 = AxiosError$1.prototype; + const prototype$1 = AxiosError.prototype; const descriptors = {}; [ @@ -797,11 +2726,11 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; descriptors[code] = {value: code}; }); - Object.defineProperties(AxiosError$1, descriptors); + Object.defineProperties(AxiosError, descriptors); Object.defineProperty(prototype$1, 'isAxiosError', {value: true}); // eslint-disable-next-line func-names - AxiosError$1.from = (error, code, config, request, response, customProps) => { + AxiosError.from = (error, code, config, request, response, customProps) => { const axiosError = Object.create(prototype$1); utils$1.toFlatObject(error, axiosError, function filter(obj) { @@ -810,7 +2739,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return prop !== 'isAxiosError'; }); - AxiosError$1.call(axiosError, error.message, code, config, request, response); + AxiosError.call(axiosError, error.message, code, config, request, response); axiosError.cause = error; @@ -824,103 +2753,214 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; // eslint-disable-next-line strict var httpAdapter = null; + /** + * Determines if the given thing is a array or js object. + * + * @param {string} thing - The object or array to be visited. + * + * @returns {boolean} + */ function isVisitable(thing) { return utils$1.isPlainObject(thing) || utils$1.isArray(thing); } + + /** + * It removes the brackets from the end of a string + * + * @param {string} key - The key of the parameter. + * + * @returns {string} the key without the brackets. + */ function removeBrackets(key) { - return utils$1.endsWith(key, "[]") ? key.slice(0, -2) : key; + return utils$1.endsWith(key, '[]') ? key.slice(0, -2) : key; } + + /** + * It takes a path, a key, and a boolean, and returns a string + * + * @param {string} path - The path to the current key. + * @param {string} key - The key of the current object being iterated over. + * @param {string} dots - If true, the key will be rendered with dots instead of brackets. + * + * @returns {string} The path to the current key. + */ function renderKey(path, key, dots) { if (!path) return key; return path.concat(key).map(function each(token, i) { + // eslint-disable-next-line no-param-reassign token = removeBrackets(token); - return !dots && i ? "[" + token + "]" : token; - }).join(dots ? "." : ""); + return !dots && i ? '[' + token + ']' : token; + }).join(dots ? '.' : ''); } + + /** + * If the array is an array and none of its elements are visitable, then it's a flat array. + * + * @param {Array} arr - The array to check + * + * @returns {boolean} + */ function isFlatArray(arr) { return utils$1.isArray(arr) && !arr.some(isVisitable); } + const predicates = utils$1.toFlatObject(utils$1, {}, null, function filter(prop) { - return (/^is[A-Z]/).test(prop); + return /^is[A-Z]/.test(prop); }); - function toFormData$1(obj, formData, options) { + + /** + * Convert a data object to FormData + * + * @param {Object} obj + * @param {?Object} [formData] + * @param {?Object} [options] + * @param {Function} [options.visitor] + * @param {Boolean} [options.metaTokens = true] + * @param {Boolean} [options.dots = false] + * @param {?Boolean} [options.indexes = false] + * + * @returns {Object} + **/ + + /** + * It converts an object into a FormData object + * + * @param {Object} obj - The object to convert to form data. + * @param {string} formData - The FormData object to append to. + * @param {Object} options + * + * @returns + */ + function toFormData(obj, formData, options) { if (!utils$1.isObject(obj)) { - throw new TypeError("target must be an object"); + throw new TypeError('target must be an object'); } + + // eslint-disable-next-line no-param-reassign formData = formData || new (FormData)(); + + // eslint-disable-next-line no-param-reassign options = utils$1.toFlatObject(options, { metaTokens: true, dots: false, indexes: false }, false, function defined(option, source) { + // eslint-disable-next-line no-eq-null,eqeqeq return !utils$1.isUndefined(source[option]); }); + const metaTokens = options.metaTokens; + // eslint-disable-next-line no-use-before-define const visitor = options.visitor || defaultVisitor; const dots = options.dots; const indexes = options.indexes; - const _Blob = options.Blob || typeof Blob !== "undefined" && Blob; + const _Blob = options.Blob || typeof Blob !== 'undefined' && Blob; const useBlob = _Blob && utils$1.isSpecCompliantForm(formData); + if (!utils$1.isFunction(visitor)) { - throw new TypeError("visitor must be a function"); + throw new TypeError('visitor must be a function'); } + function convertValue(value) { - if (value === null) return ""; + if (value === null) return ''; + if (utils$1.isDate(value)) { return value.toISOString(); } + if (!useBlob && utils$1.isBlob(value)) { - throw new AxiosError$1("Blob is not supported. Use a Buffer instead."); + throw new AxiosError('Blob is not supported. Use a Buffer instead.'); } + if (utils$1.isArrayBuffer(value) || utils$1.isTypedArray(value)) { - return useBlob && typeof Blob === "function" ? new Blob([value]) : Buffer.from(value); + return useBlob && typeof Blob === 'function' ? new Blob([value]) : Buffer.from(value); } + return value; } + + /** + * Default visitor. + * + * @param {*} value + * @param {String|Number} key + * @param {Array} path + * @this {FormData} + * + * @returns {boolean} return true to visit the each prop of the value recursively + */ function defaultVisitor(value, key, path) { let arr = value; - if (value && !path && typeof value === "object") { - if (utils$1.endsWith(key, "{}")) { + + if (value && !path && typeof value === 'object') { + if (utils$1.endsWith(key, '{}')) { + // eslint-disable-next-line no-param-reassign key = metaTokens ? key : key.slice(0, -2); + // eslint-disable-next-line no-param-reassign value = JSON.stringify(value); - } else if (utils$1.isArray(value) && isFlatArray(value) || (utils$1.isFileList(value) || utils$1.endsWith(key, "[]")) && (arr = utils$1.toArray(value))) { + } else if ( + (utils$1.isArray(value) && isFlatArray(value)) || + ((utils$1.isFileList(value) || utils$1.endsWith(key, '[]')) && (arr = utils$1.toArray(value)) + )) { + // eslint-disable-next-line no-param-reassign key = removeBrackets(key); + arr.forEach(function each(el, index) { - !(utils$1.isUndefined(el) || el === null) && formData.append(indexes === true ? renderKey([key], index, dots) : indexes === null ? key : key + "[]", convertValue(el)); + !(utils$1.isUndefined(el) || el === null) && formData.append( + // eslint-disable-next-line no-nested-ternary + indexes === true ? renderKey([key], index, dots) : (indexes === null ? key : key + '[]'), + convertValue(el) + ); }); return false; } } + if (isVisitable(value)) { return true; } + formData.append(renderKey(path, key, dots), convertValue(value)); + return false; } + const stack = []; + const exposedHelpers = Object.assign(predicates, { defaultVisitor, convertValue, isVisitable }); + function build(value, path) { if (utils$1.isUndefined(value)) return; + if (stack.indexOf(value) !== -1) { - throw Error("Circular reference detected in " + path.join(".")); + throw Error('Circular reference detected in ' + path.join('.')); } + stack.push(value); + utils$1.forEach(value, function each(el, key) { - const result = !(utils$1.isUndefined(el) || el === null) && visitor.call(formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers); + const result = !(utils$1.isUndefined(el) || el === null) && visitor.call( + formData, el, utils$1.isString(key) ? key.trim() : key, path, exposedHelpers + ); + if (result === true) { build(el, path ? path.concat(key) : [key]); } }); + stack.pop(); } + if (!utils$1.isObject(obj)) { - throw new TypeError("data must be an object"); + throw new TypeError('data must be an object'); } + build(obj); + return formData; } @@ -958,7 +2998,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; function AxiosURLSearchParams(params, options) { this._pairs = []; - params && toFormData$1(params, this, options); + params && toFormData(params, this, options); } const prototype = AxiosURLSearchParams.prototype; @@ -1171,8 +3211,8 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; var utils = /*#__PURE__*/Object.freeze({ __proto__: null, hasBrowserEnv: hasBrowserEnv, - hasStandardBrowserEnv: hasStandardBrowserEnv, - hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv + hasStandardBrowserWebWorkerEnv: hasStandardBrowserWebWorkerEnv, + hasStandardBrowserEnv: hasStandardBrowserEnv }); var platform = { @@ -1181,7 +3221,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; }; function toURLEncodedForm(data, options) { - return toFormData$1(data, new platform.classes.URLSearchParams(), Object.assign({ + return toFormData(data, new platform.classes.URLSearchParams(), Object.assign({ visitor: function(value, key, path, helpers) { if (platform.isNode && utils$1.isBuffer(value)) { this.append(key, value.toString('base64')); @@ -1355,7 +3395,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; if ((isFileList = utils$1.isFileList(data)) || contentType.indexOf('multipart/form-data') > -1) { const _FormData = this.env && this.env.FormData; - return toFormData$1( + return toFormData( isFileList ? {'files[]': data} : data, _FormData && new _FormData(), this.formSerializer @@ -1385,7 +3425,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } catch (e) { if (strictJSONParsing) { if (e.name === 'SyntaxError') { - throw AxiosError$1.from(e, AxiosError$1.ERR_BAD_RESPONSE, this, null, this.response); + throw AxiosError.from(e, AxiosError.ERR_BAD_RESPONSE, this, null, this.response); } throw e; } @@ -1550,7 +3590,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; }); } - let AxiosHeaders$1 = class AxiosHeaders { + class AxiosHeaders { constructor(headers) { headers && this.set(headers); } @@ -1757,12 +3797,12 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return this; } - }; + } - AxiosHeaders$1.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); + AxiosHeaders.accessor(['Content-Type', 'Content-Length', 'Accept', 'Accept-Encoding', 'User-Agent', 'Authorization']); // reserved names hotfix - utils$1.reduceDescriptors(AxiosHeaders$1.prototype, ({value}, key) => { + utils$1.reduceDescriptors(AxiosHeaders.prototype, ({value}, key) => { let mapped = key[0].toUpperCase() + key.slice(1); // map `set` => `Set` return { get: () => value, @@ -1772,9 +3812,9 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } }); - utils$1.freezeMethods(AxiosHeaders$1); + utils$1.freezeMethods(AxiosHeaders); - var AxiosHeaders$2 = AxiosHeaders$1; + var AxiosHeaders$1 = AxiosHeaders; /** * Transform the data for a request or a response @@ -1787,7 +3827,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; function transformData(fns, response) { const config = this || defaults$1; const context = response || config; - const headers = AxiosHeaders$2.from(context.headers); + const headers = AxiosHeaders$1.from(context.headers); let data = context.data; utils$1.forEach(fns, function transform(fn) { @@ -1799,7 +3839,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return data; } - function isCancel$1(value) { + function isCancel(value) { return !!(value && value.__CANCEL__); } @@ -1812,13 +3852,13 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @returns {CanceledError} The created error. */ - function CanceledError$1(message, config, request) { + function CanceledError(message, config, request) { // eslint-disable-next-line no-eq-null,eqeqeq - AxiosError$1.call(this, message == null ? 'canceled' : message, AxiosError$1.ERR_CANCELED, config, request); + AxiosError.call(this, message == null ? 'canceled' : message, AxiosError.ERR_CANCELED, config, request); this.name = 'CanceledError'; } - utils$1.inherits(CanceledError$1, AxiosError$1, { + utils$1.inherits(CanceledError, AxiosError, { __CANCEL__: true }); @@ -1836,9 +3876,9 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; if (!response.status || !validateStatus || validateStatus(response.status)) { resolve(response); } else { - reject(new AxiosError$1( + reject(new AxiosError( 'Request failed with status code ' + response.status, - [AxiosError$1.ERR_BAD_REQUEST, AxiosError$1.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], + [AxiosError.ERR_BAD_REQUEST, AxiosError.ERR_BAD_RESPONSE][Math.floor(response.status / 100) - 4], response.config, response.request, response @@ -2084,7 +4124,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; var xhrAdapter = isXHRAdapterSupported && function (config) { return new Promise(function dispatchXhrRequest(resolve, reject) { let requestData = config.data; - const requestHeaders = AxiosHeaders$2.from(config.headers).normalize(); + const requestHeaders = AxiosHeaders$1.from(config.headers).normalize(); let {responseType, withXSRFToken} = config; let onCanceled; function done() { @@ -2130,7 +4170,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return; } // Prepare the response - const responseHeaders = AxiosHeaders$2.from( + const responseHeaders = AxiosHeaders$1.from( 'getAllResponseHeaders' in request && request.getAllResponseHeaders() ); const responseData = !responseType || responseType === 'text' || responseType === 'json' ? @@ -2185,7 +4225,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return; } - reject(new AxiosError$1('Request aborted', AxiosError$1.ECONNABORTED, config, request)); + reject(new AxiosError('Request aborted', AxiosError.ECONNABORTED, config, request)); // Clean up request request = null; @@ -2195,7 +4235,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; request.onerror = function handleError() { // Real errors are hidden from us by the browser // onerror should only fire if it's a network error - reject(new AxiosError$1('Network Error', AxiosError$1.ERR_NETWORK, config, request)); + reject(new AxiosError('Network Error', AxiosError.ERR_NETWORK, config, request)); // Clean up request request = null; @@ -2208,9 +4248,9 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; if (config.timeoutErrorMessage) { timeoutErrorMessage = config.timeoutErrorMessage; } - reject(new AxiosError$1( + reject(new AxiosError( timeoutErrorMessage, - transitional.clarifyTimeoutError ? AxiosError$1.ETIMEDOUT : AxiosError$1.ECONNABORTED, + transitional.clarifyTimeoutError ? AxiosError.ETIMEDOUT : AxiosError.ECONNABORTED, config, request)); @@ -2271,7 +4311,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; if (!request) { return; } - reject(!cancel || cancel.type ? new CanceledError$1(null, config, request) : cancel); + reject(!cancel || cancel.type ? new CanceledError(null, config, request) : cancel); request.abort(); request = null; }; @@ -2285,7 +4325,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; const protocol = parseProtocol(fullPath); if (protocol && platform.protocols.indexOf(protocol) === -1) { - reject(new AxiosError$1('Unsupported protocol ' + protocol + ':', AxiosError$1.ERR_BAD_REQUEST, config)); + reject(new AxiosError('Unsupported protocol ' + protocol + ':', AxiosError.ERR_BAD_REQUEST, config)); return; } @@ -2335,7 +4375,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; adapter = knownAdapters[(id = String(nameOrAdapter)).toLowerCase()]; if (adapter === undefined) { - throw new AxiosError$1(`Unknown adapter '${id}'`); + throw new AxiosError(`Unknown adapter '${id}'`); } } @@ -2357,7 +4397,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; (reasons.length > 1 ? 'since :\n' + reasons.map(renderReason).join('\n') : ' ' + renderReason(reasons[0])) : 'as no adapter specified'; - throw new AxiosError$1( + throw new AxiosError( `There is no suitable adapter to dispatch the request ` + s, 'ERR_NOT_SUPPORT' ); @@ -2381,7 +4421,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } if (config.signal && config.signal.aborted) { - throw new CanceledError$1(null, config); + throw new CanceledError(null, config); } } @@ -2395,7 +4435,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; function dispatchRequest(config) { throwIfCancellationRequested(config); - config.headers = AxiosHeaders$2.from(config.headers); + config.headers = AxiosHeaders$1.from(config.headers); // Transform request data config.data = transformData.call( @@ -2419,11 +4459,11 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; response ); - response.headers = AxiosHeaders$2.from(response.headers); + response.headers = AxiosHeaders$1.from(response.headers); return response; }, function onAdapterRejection(reason) { - if (!isCancel$1(reason)) { + if (!isCancel(reason)) { throwIfCancellationRequested(config); // Transform response data @@ -2433,7 +4473,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; config.transformResponse, reason.response ); - reason.response.headers = AxiosHeaders$2.from(reason.response.headers); + reason.response.headers = AxiosHeaders$1.from(reason.response.headers); } } @@ -2441,7 +4481,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; }); } - const headersToObject = (thing) => thing instanceof AxiosHeaders$2 ? thing.toJSON() : thing; + const headersToObject = (thing) => thing instanceof AxiosHeaders$1 ? thing.toJSON() : thing; /** * Config-specific merge-function which creates a new config-object @@ -2452,7 +4492,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @returns {Object} New object resulting from merging config2 to config1 */ - function mergeConfig$1(config1, config2) { + function mergeConfig(config1, config2) { // eslint-disable-next-line no-param-reassign config2 = config2 || {}; const config = {}; @@ -2543,7 +4583,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return config; } - const VERSION$1 = "1.6.2"; + const VERSION = "1.6.2"; const validators$1 = {}; @@ -2567,15 +4607,15 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; */ validators$1.transitional = function transitional(validator, version, message) { function formatMessage(opt, desc) { - return '[Axios v' + VERSION$1 + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); + return '[Axios v' + VERSION + '] Transitional option \'' + opt + '\'' + desc + (message ? '. ' + message : ''); } // eslint-disable-next-line func-names return (value, opt, opts) => { if (validator === false) { - throw new AxiosError$1( + throw new AxiosError( formatMessage(opt, ' has been removed' + (version ? ' in ' + version : '')), - AxiosError$1.ERR_DEPRECATED + AxiosError.ERR_DEPRECATED ); } @@ -2606,7 +4646,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; function assertOptions(options, schema, allowUnknown) { if (typeof options !== 'object') { - throw new AxiosError$1('options must be an object', AxiosError$1.ERR_BAD_OPTION_VALUE); + throw new AxiosError('options must be an object', AxiosError.ERR_BAD_OPTION_VALUE); } const keys = Object.keys(options); let i = keys.length; @@ -2617,12 +4657,12 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; const value = options[opt]; const result = value === undefined || validator(value, opt, options); if (result !== true) { - throw new AxiosError$1('option ' + opt + ' must be ' + result, AxiosError$1.ERR_BAD_OPTION_VALUE); + throw new AxiosError('option ' + opt + ' must be ' + result, AxiosError.ERR_BAD_OPTION_VALUE); } continue; } if (allowUnknown !== true) { - throw new AxiosError$1('Unknown option ' + opt, AxiosError$1.ERR_BAD_OPTION); + throw new AxiosError('Unknown option ' + opt, AxiosError.ERR_BAD_OPTION); } } } @@ -2641,7 +4681,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @return {Axios} A new instance of Axios */ - let Axios$1 = class Axios { + class Axios { constructor(instanceConfig) { this.defaults = instanceConfig; this.interceptors = { @@ -2668,7 +4708,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; config = configOrUrl || {}; } - config = mergeConfig$1(this.defaults, config); + config = mergeConfig(this.defaults, config); const {transitional, paramsSerializer, headers} = config; @@ -2709,7 +4749,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } ); - config.headers = AxiosHeaders$2.concat(contextHeaders, headers); + config.headers = AxiosHeaders$1.concat(contextHeaders, headers); // filter out skipped interceptors const requestInterceptorChain = []; @@ -2782,17 +4822,17 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } getUri(config) { - config = mergeConfig$1(this.defaults, config); + config = mergeConfig(this.defaults, config); const fullPath = buildFullPath(config.baseURL, config.url); return buildURL(fullPath, config.params, config.paramsSerializer); } - }; + } // Provide aliases for supported request methods utils$1.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) { /*eslint func-names:0*/ - Axios$1.prototype[method] = function(url, config) { - return this.request(mergeConfig$1(config || {}, { + Axios.prototype[method] = function(url, config) { + return this.request(mergeConfig(config || {}, { method, url, data: (config || {}).data @@ -2805,7 +4845,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; function generateHTTPMethod(isForm) { return function httpMethod(url, data, config) { - return this.request(mergeConfig$1(config || {}, { + return this.request(mergeConfig(config || {}, { method, headers: isForm ? { 'Content-Type': 'multipart/form-data' @@ -2816,12 +4856,12 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; }; } - Axios$1.prototype[method] = generateHTTPMethod(); + Axios.prototype[method] = generateHTTPMethod(); - Axios$1.prototype[method + 'Form'] = generateHTTPMethod(true); + Axios.prototype[method + 'Form'] = generateHTTPMethod(true); }); - var Axios$2 = Axios$1; + var Axios$1 = Axios; /** * A `CancelToken` is an object that can be used to request cancellation of an operation. @@ -2830,7 +4870,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @returns {CancelToken} */ - let CancelToken$1 = class CancelToken { + class CancelToken { constructor(executor) { if (typeof executor !== 'function') { throw new TypeError('executor must be a function.'); @@ -2878,7 +4918,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return; } - token.reason = new CanceledError$1(message, config, request); + token.reason = new CanceledError(message, config, request); resolvePromise(token.reason); }); } @@ -2937,9 +4977,9 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; cancel }; } - }; + } - var CancelToken$2 = CancelToken$1; + var CancelToken$1 = CancelToken; /** * Syntactic sugar for invoking a function and expanding an array for arguments. @@ -2962,7 +5002,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @returns {Function} */ - function spread$1(callback) { + function spread(callback) { return function wrap(arr) { return callback.apply(null, arr); }; @@ -2975,11 +5015,11 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @returns {boolean} True if the payload is an error thrown by Axios, otherwise false */ - function isAxiosError$1(payload) { + function isAxiosError(payload) { return utils$1.isObject(payload) && (payload.isAxiosError === true); } - const HttpStatusCode$1 = { + const HttpStatusCode = { Continue: 100, SwitchingProtocols: 101, Processing: 102, @@ -3045,11 +5085,11 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; NetworkAuthenticationRequired: 511, }; - Object.entries(HttpStatusCode$1).forEach(([key, value]) => { - HttpStatusCode$1[value] = key; + Object.entries(HttpStatusCode).forEach(([key, value]) => { + HttpStatusCode[value] = key; }); - var HttpStatusCode$2 = HttpStatusCode$1; + var HttpStatusCode$1 = HttpStatusCode; /** * Create an instance of Axios @@ -3059,18 +5099,18 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * @returns {Axios} A new instance of Axios */ function createInstance(defaultConfig) { - const context = new Axios$2(defaultConfig); - const instance = bind(Axios$2.prototype.request, context); + const context = new Axios$1(defaultConfig); + const instance = bind(Axios$1.prototype.request, context); // Copy axios.prototype to instance - utils$1.extend(instance, Axios$2.prototype, context, {allOwnKeys: true}); + utils$1.extend(instance, Axios$1.prototype, context, {allOwnKeys: true}); // Copy context to instance utils$1.extend(instance, context, null, {allOwnKeys: true}); // Factory for creating new instances instance.create = function create(instanceConfig) { - return createInstance(mergeConfig$1(defaultConfig, instanceConfig)); + return createInstance(mergeConfig(defaultConfig, instanceConfig)); }; return instance; @@ -3080,17 +5120,17 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; const axios = createInstance(defaults$1); // Expose Axios class to allow class inheritance - axios.Axios = Axios$2; + axios.Axios = Axios$1; // Expose Cancel & CancelToken - axios.CanceledError = CanceledError$1; - axios.CancelToken = CancelToken$2; - axios.isCancel = isCancel$1; - axios.VERSION = VERSION$1; - axios.toFormData = toFormData$1; + axios.CanceledError = CanceledError; + axios.CancelToken = CancelToken$1; + axios.isCancel = isCancel; + axios.VERSION = VERSION; + axios.toFormData = toFormData; // Expose AxiosError class - axios.AxiosError = AxiosError$1; + axios.AxiosError = AxiosError; // alias for CanceledError for backward compatibility axios.Cancel = axios.CanceledError; @@ -3100,69 +5140,28 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return Promise.all(promises); }; - axios.spread = spread$1; + axios.spread = spread; // Expose isAxiosError - axios.isAxiosError = isAxiosError$1; + axios.isAxiosError = isAxiosError; // Expose mergeConfig - axios.mergeConfig = mergeConfig$1; + axios.mergeConfig = mergeConfig; - axios.AxiosHeaders = AxiosHeaders$2; + axios.AxiosHeaders = AxiosHeaders$1; axios.formToJSON = thing => formDataToJSON(utils$1.isHTMLForm(thing) ? new FormData(thing) : thing); axios.getAdapter = adapters.getAdapter; - axios.HttpStatusCode = HttpStatusCode$2; + axios.HttpStatusCode = HttpStatusCode$1; axios.default = axios; - // this module should only have a default export - var defaultExport = axios; - - // This module is intended to unwrap Axios default export as named. - // Keep top-level export same with static properties - // so that it can keep same with es module or cjs - const { - Axios, - AxiosError, - CanceledError, - isCancel, - CancelToken, - VERSION, - all, - Cancel, - isAxiosError, - spread, - toFormData, - AxiosHeaders, - HttpStatusCode, - formToJSON, - getAdapter, - mergeConfig - } = defaultExport; - - try { Object.defineProperty(defaultExport, "__" + "esModule", { value: true }); } catch (ex) {} - - exports.Axios = Axios; - exports.AxiosError = AxiosError; - exports.AxiosHeaders = AxiosHeaders; - exports.Cancel = Cancel; - exports.CancelToken = CancelToken; - exports.CanceledError = CanceledError; - exports.HttpStatusCode = HttpStatusCode; - exports.VERSION = VERSION; - exports.all = all; - exports.default = defaultExport; - exports.formToJSON = formToJSON; - exports.getAdapter = getAdapter; - exports.isAxiosError = isAxiosError; - exports.isCancel = isCancel; - exports.mergeConfig = mergeConfig; - exports.spread = spread; - exports.toFormData = toFormData; - - Object.defineProperty(exports, '__esModule', { value: true }); + var axios_1 = axios; + + try { Object.defineProperty(axios_1, "__" + "esModule", { value: true }); } catch (ex) {} + + return axios_1; })); diff --git a/packages/ui5-tooling-modules/test/__snap__/cmis.js b/packages/ui5-tooling-modules/test/__snap__/cmis.js index 24376378e..4544b9144 100644 --- a/packages/ui5-tooling-modules/test/__snap__/cmis.js +++ b/packages/ui5-tooling-modules/test/__snap__/cmis.js @@ -503,204 +503,206 @@ sap.ui.define((function () { 'use strict'; var lookup = []; var revLookup = []; - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; var inited = false; - function init () { - inited = true; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; - } + function init() { + inited = true; + var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; + revLookup["-".charCodeAt(0)] = 62; + revLookup["_".charCodeAt(0)] = 63; } - function toByteArray (b64) { - if (!inited) { - init(); - } - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; + function toByteArray(b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } + if (len % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); + } - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === "=" ? 2 : b64[len - 1] === "=" ? 1 : 0; - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(len * 3 / 4 - placeHolders); + // base64 is 4/3 + up to two characters of the original data + arr = new Arr((len * 3) / 4 - placeHolders); - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len; + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; - var L = 0; + var L = 0; - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; - arr[L++] = (tmp >> 16) & 0xFF; - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xff; + arr[L++] = (tmp >> 8) & 0xff; + arr[L++] = tmp & 0xff; + } - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); - arr[L++] = tmp & 0xFF; - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xff; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xff; + arr[L++] = tmp & 0xff; + } - return arr + return arr; } - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + function tripletToBase64(num) { + return lookup[(num >> 18) & 0x3f] + lookup[(num >> 12) & 0x3f] + lookup[(num >> 6) & 0x3f] + lookup[num & 0x3f]; } - function encodeChunk (uint8, start, end) { - var tmp; - var output = []; - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output.push(tripletToBase64(tmp)); - } - return output.join('') + function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2]; + output.push(tripletToBase64(tmp)); + } + return output.join(""); } - function fromByteArray (uint8) { - if (!inited) { - init(); - } - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - var output = ''; - var parts = []; - var maxChunkLength = 16383; // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); - } + function fromByteArray(uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ""; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); + } - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1]; - output += lookup[tmp >> 2]; - output += lookup[(tmp << 4) & 0x3F]; - output += '=='; - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); - output += lookup[tmp >> 10]; - output += lookup[(tmp >> 4) & 0x3F]; - output += lookup[(tmp << 2) & 0x3F]; - output += '='; - } + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3f]; + output += "=="; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3f]; + output += lookup[(tmp << 2) & 0x3f]; + output += "="; + } - parts.push(output); + parts.push(output); - return parts.join('') + return parts.join(""); } - function read (buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? (nBytes - 1) : 0; - var d = isLE ? -1 : 1; - var s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + function read(buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << -nBits) - 1); + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << -nBits) - 1); + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); } - function write (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); - var i = isLE ? 0 : (nBytes - 1); - var d = isLE ? 1 : -1; - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } + function write(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - buffer[offset + i - d] |= s * 128; + buffer[offset + i - d] |= s * 128; } var toString = {}.toString; - var isArray$2 = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; + var isArray$2 = + Array.isArray || + function (arr) { + return toString.call(arr) == "[object Array]"; + }; /*! * The buffer module from node.js, for the browser. @@ -710,7 +712,6 @@ sap.ui.define((function () { 'use strict'; */ /* eslint-disable no-proto */ - var INSPECT_MAX_BYTES = 50; /** @@ -737,38 +738,34 @@ sap.ui.define((function () { 'use strict'; * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ - Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined - ? global$1.TYPED_ARRAY_SUPPORT - : true; + Buffer.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined ? global$1.TYPED_ARRAY_SUPPORT : true; /* * Export kMaxLength after typed array support is determined. */ kMaxLength(); - function kMaxLength () { - return Buffer$1.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff + function kMaxLength() { + return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff; } - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer$1(length); - } - that.length = length; - } + function createBuffer(that, length) { + if (kMaxLength() < length) { + throw new RangeError("Invalid typed array length"); + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } - return that + return that; } /** @@ -781,45 +778,43 @@ sap.ui.define((function () { 'use strict'; * The `Uint8Array` prototype remains unmodified. */ - function Buffer$1 (arg, encodingOrOffset, length) { - if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { - return new Buffer$1(arg, encodingOrOffset, length) - } + function Buffer(arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length); + } - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) + // Common case. + if (typeof arg === "number") { + if (typeof encodingOrOffset === "string") { + throw new Error("If encoding is specified then the first argument must be a string"); + } + return allocUnsafe(this, arg); + } + return from(this, arg, encodingOrOffset, length); } - Buffer$1.poolSize = 8192; // not used by this implementation + Buffer.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$1._augment = function (arr) { - arr.__proto__ = Buffer$1.prototype; - return arr + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr; }; - function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } + function from(that, value, encodingOrOffset, length) { + if (typeof value === "number") { + throw new TypeError('"value" argument must not be a number'); + } - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } + if (typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length); + } - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } + if (typeof value === "string") { + return fromString(that, value, encodingOrOffset); + } - return fromObject(that, value) + return fromObject(that, value); } /** @@ -830,494 +825,488 @@ sap.ui.define((function () { 'use strict'; * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer$1.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length); }; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - Buffer$1.prototype.__proto__ = Uint8Array.prototype; - Buffer$1.__proto__ = Uint8Array; - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer$1[Symbol.species] === Buffer$1) ; + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== "undefined" && Symbol.species && Buffer[Symbol.species] === Buffer); } - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } + function assertSize(size) { + if (typeof size !== "number") { + throw new TypeError('"size" argument must be a number'); + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative'); + } } - function alloc (that, size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) + function alloc(that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size); + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === "string" ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill); + } + return createBuffer(that, size); } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer$1.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding); }; - function allocUnsafe (that, size) { - assertSize(size); - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0; - } - } - return that + function allocUnsafe(that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that; } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer$1.allocUnsafe = function (size) { - return allocUnsafe(null, size) + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size); }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer$1.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size); }; - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; - } + function fromString(that, string, encoding) { + if (typeof encoding !== "string" || encoding === "") { + encoding = "utf8"; + } - if (!Buffer$1.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding'); + } - var length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); - var actual = that.write(string, encoding); + var actual = that.write(string, encoding); - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual); - } + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } - return that + return that; } - function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - that = createBuffer(that, length); - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255; - } - return that + function fromArrayLike(that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that; } - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer + function fromArrayBuffer(that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError("'offset' is out of bounds"); + } - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError("'length' is out of bounds"); + } - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); - } else { - array = new Uint8Array(array, byteOffset, length); - } + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array; - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array); - } - return that + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that; } - function fromObject (that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); + function fromObject(that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); - if (that.length === 0) { - return that - } + if (that.length === 0) { + return that; + } - obj.copy(that, 0, 0, len); - return that - } + obj.copy(that, 0, 0, len); + return that; + } - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } + if (obj) { + if ((typeof ArrayBuffer !== "undefined" && obj.buffer instanceof ArrayBuffer) || "length" in obj) { + if (typeof obj.length !== "number" || isnan(obj.length)) { + return createBuffer(that, 0); + } + return fromArrayLike(that, obj); + } - if (obj.type === 'Buffer' && isArray$2(obj.data)) { - return fromArrayLike(that, obj.data) - } - } + if (obj.type === "Buffer" && isArray$2(obj.data)) { + return fromArrayLike(that, obj.data); + } + } - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object."); } - function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 + function checked(length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError("Attempt to allocate Buffer larger than maximum " + "size: 0x" + kMaxLength().toString(16) + " bytes"); + } + return length | 0; } - Buffer$1.isBuffer = isBuffer$1; - function internalIsBuffer (b) { - return !!(b != null && b._isBuffer) + Buffer.isBuffer = isBuffer$1; + function internalIsBuffer(b) { + return !!(b != null && b._isBuffer); } - Buffer$1.compare = function compare (a, b) { - if (!internalIsBuffer(a) || !internalIsBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } + Buffer.compare = function compare(a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError("Arguments must be Buffers"); + } - if (a === b) return 0 + if (a === b) return 0; - var x = a.length; - var y = b.length; + var x = a.length; + var y = b.length; - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break - } - } + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } - if (x < y) return -1 - if (y < x) return 1 - return 0 + if (x < y) return -1; + if (y < x) return 1; + return 0; }; - Buffer$1.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } + Buffer.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "latin1": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return true; + default: + return false; + } }; - Buffer$1.concat = function concat (list, length) { - if (!isArray$2(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } + Buffer.concat = function concat(list, length) { + if (!isArray$2(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } - if (list.length === 0) { - return Buffer$1.alloc(0) - } + if (list.length === 0) { + return Buffer.alloc(0); + } - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } - var buffer = Buffer$1.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (!internalIsBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer; }; - function byteLength (string, encoding) { - if (internalIsBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string; - } + function byteLength(string, encoding) { + if (internalIsBuffer(string)) { + return string.length; + } + if (typeof ArrayBuffer !== "undefined" && typeof ArrayBuffer.isView === "function" && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength; + } + if (typeof string !== "string") { + string = "" + string; + } - var len = string.length; - if (len === 0) return 0 - - // Use a for loop to avoid recursion - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } + var len = string.length; + if (len === 0) return 0; + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case "ascii": + case "latin1": + case "binary": + return len; + case "utf8": + case "utf-8": + case undefined: + return utf8ToBytes(string).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return len * 2; + case "hex": + return len >>> 1; + case "base64": + return base64ToBytes(string).length; + default: + if (loweredCase) return utf8ToBytes(string).length; // assume utf8 + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } } - Buffer$1.byteLength = byteLength; + Buffer.byteLength = byteLength; - function slowToString (encoding, start, end) { - var loweredCase = false; + function slowToString(encoding, start, end) { + var loweredCase = false; - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0; - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return ""; + } - if (end === undefined || end > this.length) { - end = this.length; - } + if (end === undefined || end > this.length) { + end = this.length; + } - if (end <= 0) { - return '' - } + if (end <= 0) { + return ""; + } - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0; - start >>>= 0; + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; - if (end <= start) { - return '' - } + if (end <= start) { + return ""; + } - if (!encoding) encoding = 'utf8'; + if (!encoding) encoding = "utf8"; - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) + while (true) { + switch (encoding) { + case "hex": + return hexSlice(this, start, end); - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) + case "utf8": + case "utf-8": + return utf8Slice(this, start, end); - case 'ascii': - return asciiSlice(this, start, end) + case "ascii": + return asciiSlice(this, start, end); - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) + case "latin1": + case "binary": + return latin1Slice(this, start, end); - case 'base64': - return base64Slice(this, start, end) + case "base64": + return base64Slice(this, start, end); - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return utf16leSlice(this, start, end); - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase(); - loweredCase = true; - } - } + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); + encoding = (encoding + "").toLowerCase(); + loweredCase = true; + } + } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. - Buffer$1.prototype._isBuffer = true; + Buffer.prototype._isBuffer = true; - function swap (b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; + function swap(b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; } - Buffer$1.prototype.swap16 = function swap16 () { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - return this + Buffer.prototype.swap16 = function swap16() { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError("Buffer size must be a multiple of 16-bits"); + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this; }; - Buffer$1.prototype.swap32 = function swap32 () { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - return this + Buffer.prototype.swap32 = function swap32() { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError("Buffer size must be a multiple of 32-bits"); + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this; }; - Buffer$1.prototype.swap64 = function swap64 () { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); - } - return this + Buffer.prototype.swap64 = function swap64() { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError("Buffer size must be a multiple of 64-bits"); + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this; }; - Buffer$1.prototype.toString = function toString () { - var length = this.length | 0; - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) + Buffer.prototype.toString = function toString() { + var length = this.length | 0; + if (length === 0) return ""; + if (arguments.length === 0) return utf8Slice(this, 0, length); + return slowToString.apply(this, arguments); }; - Buffer$1.prototype.equals = function equals (b) { - if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer$1.compare(this, b) === 0 + Buffer.prototype.equals = function equals(b) { + if (!internalIsBuffer(b)) throw new TypeError("Argument must be a Buffer"); + if (this === b) return true; + return Buffer.compare(this, b) === 0; }; - Buffer$1.prototype.inspect = function inspect () { - var str = ''; - var max = INSPECT_MAX_BYTES; - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) str += ' ... '; - } - return '' + Buffer.prototype.inspect = function inspect() { + var str = ""; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString("hex", 0, max).match(/.{2}/g).join(" "); + if (this.length > max) str += " ... "; + } + return ""; }; - Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } + Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError("Argument must be a Buffer"); + } - if (start === undefined) { - start = 0; - } - if (end === undefined) { - end = target ? target.length : 0; - } - if (thisStart === undefined) { - thisStart = 0; - } - if (thisEnd === undefined) { - thisEnd = this.length; - } + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError("out of range index"); + } - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return -1; + } + if (start >= end) { + return 1; + } - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; - if (this === target) return 0 + if (this === target) return 0; - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break - } - } + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break; + } + } - if (x < y) return -1 - if (y < x) return 1 - return 0 + if (x < y) return -1; + if (y < x) return 1; + return 0; }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, @@ -1329,336 +1318,329 @@ sap.ui.define((function () { 'use strict'; // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf - function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; - } - byteOffset = +byteOffset; // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1); - } + function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1; + + // Normalize byteOffset + if (typeof byteOffset === "string") { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : buffer.length - 1; + } - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0; - else return -1 - } + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1; + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1; + } - // Normalize val - if (typeof val === 'string') { - val = Buffer$1.from(val, encoding); - } + // Normalize val + if (typeof val === "string") { + val = Buffer.from(val, encoding); + } - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (internalIsBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$1.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1; + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === "number") { + val = val & 0xff; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === "function") { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); + } - throw new TypeError('val must be string, number or Buffer') + throw new TypeError("val must be string, number or Buffer"); } - function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; - - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase(); - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { + if (arr.length < 2 || val.length < 2) { + return -1; + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } - var i; - if (dir) { - var foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - for (i = byteOffset; i >= 0; i--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break - } - } - if (found) return i - } - } + function read(buf, i) { + if (indexSize === 1) { + return buf[i]; + } else { + return buf.readUInt16BE(i * indexSize); + } + } + + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break; + } + } + if (found) return i; + } + } - return -1 + return -1; } - Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 + Buffer.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; }; - Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); }; - Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); }; - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } + function hexWrite(buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError("Invalid hex string"); - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(parsed)) return i - buf[offset + i] = parsed; - } - return i + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i; + buf[offset + i] = parsed; + } + return i; } - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + function utf8Write(buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); } - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) + function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length); } - function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) + function latin1Write(buf, string, offset, length) { + return asciiWrite(buf, string, offset, length); } - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) + function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length); } - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + function ucs2Write(buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); } - Buffer$1.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; - length = this.length; - offset = 0; - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; - length = this.length; - offset = 0; - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0; - if (isFinite(length)) { - length = length | 0; - if (encoding === undefined) encoding = 'utf8'; - } else { - encoding = length; - length = undefined; - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } + Buffer.prototype.write = function write(string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = "utf8"; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === "string") { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = "utf8"; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported"); + } - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError("Attempt to write outside buffer bounds"); + } - if (!encoding) encoding = 'utf8'; + if (!encoding) encoding = "utf8"; - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) + var loweredCase = false; + for (;;) { + switch (encoding) { + case "hex": + return hexWrite(this, string, offset, length); - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) + case "utf8": + case "utf-8": + return utf8Write(this, string, offset, length); - case 'ascii': - return asciiWrite(this, string, offset, length) + case "ascii": + return asciiWrite(this, string, offset, length); - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) + case "latin1": + case "binary": + return latin1Write(this, string, offset, length); - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) + case "base64": + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length); - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ucs2Write(this, string, offset, length); - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } }; - Buffer$1.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } + Buffer.prototype.toJSON = function toJSON() { + return { + type: "Buffer", + data: Array.prototype.slice.call(this._arr || this, 0), + }; }; - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return fromByteArray(buf) - } else { - return fromByteArray(buf.slice(start, end)) - } + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf); + } else { + return fromByteArray(buf.slice(start, end)); + } } - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1; - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; - } - break - case 2: - secondByte = buf[i + 1]; - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint; - } - } - break - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint; - } - } - break - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; - bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } - - res.push(codePoint); - i += bytesPerSequence; - } + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = firstByte > 0xef ? 4 : firstByte > 0xdf ? 3 : firstByte > 0xbf ? 2 : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xc0) === 0x80) { + tempCodePoint = ((firstByte & 0x1f) << 0x6) | (secondByte & 0x3f); + if (tempCodePoint > 0x7f) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80) { + tempCodePoint = ((firstByte & 0xf) << 0xc) | ((secondByte & 0x3f) << 0x6) | (thirdByte & 0x3f); + if (tempCodePoint > 0x7ff && (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff)) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80 && (fourthByte & 0xc0) === 0x80) { + tempCodePoint = ((firstByte & 0xf) << 0x12) | ((secondByte & 0x3f) << 0xc) | ((thirdByte & 0x3f) << 0x6) | (fourthByte & 0x3f); + if (tempCodePoint > 0xffff && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xfffd; + bytesPerSequence = 1; + } else if (codePoint > 0xffff) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(((codePoint >>> 10) & 0x3ff) | 0xd800); + codePoint = 0xdc00 | (codePoint & 0x3ff); + } + + res.push(codePoint); + i += bytesPerSequence; + } - return decodeCodePointsArray(res) + return decodeCodePointsArray(res); } // Based on http://stackoverflow.com/a/22747272/680742, the browser with @@ -1666,650 +1648,628 @@ sap.ui.define((function () { 'use strict'; // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000; - function decodeCodePointsArray (codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } + function decodeCodePointsArray(codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); // avoid extra slice() + } - // Decode in chunks to avoid "call stack size exceeded". - var res = ''; - var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); - } - return res + // Decode in chunks to avoid "call stack size exceeded". + var res = ""; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply(String, codePoints.slice(i, (i += MAX_ARGUMENTS_LENGTH))); + } + return res; } - function asciiSlice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); + function asciiSlice(buf, start, end) { + var ret = ""; + end = Math.min(buf.length, end); - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - return ret + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7f); + } + return ret; } - function latin1Slice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); + function latin1Slice(buf, start, end) { + var ret = ""; + end = Math.min(buf.length, end); - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - return ret + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret; } - function hexSlice (buf, start, end) { - var len = buf.length; + function hexSlice(buf, start, end) { + var len = buf.length; - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; - var out = ''; - for (var i = start; i < end; ++i) { - out += toHex(buf[i]); - } - return out + var out = ""; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out; } - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - return res + function utf16leSlice(buf, start, end) { + var bytes = buf.slice(start, end); + var res = ""; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res; } - Buffer$1.prototype.slice = function slice (start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; - - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } + Buffer.prototype.slice = function slice(start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } - if (end < start) end = start; + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } - var newBuf; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$1.prototype; - } else { - var sliceLen = end - start; - newBuf = new Buffer$1(sliceLen, undefined); - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; - } - } + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } - return newBuf + return newBuf; }; /* * Need to make sure that buffer isn't trying to write out of bounds. */ - function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + function checkOffset(offset, ext, length) { + if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint"); + if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length"); } - Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } - return val + return val; }; - Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } + Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } - return val + return val; }; - Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset] + Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset]; }; - Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8) + Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8); }; - Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1] + Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1]; }; - Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) + return (this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + this[offset + 3] * 0x1000000; }; - Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) + return this[offset] * 0x1000000 + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]); }; - Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - mul *= 0x80; + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - return val + return val; }; - Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; - } - mul *= 0x80; + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - return val + return val; }; - Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) + Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return this[offset]; + return (0xff - this[offset] + 1) * -1; }; - Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val + Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return val & 0x8000 ? val | 0xffff0000 : val; }; - Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val + Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return val & 0x8000 ? val | 0xffff0000 : val; }; - Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) + return this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24); }; - Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) + return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]; }; - Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, true, 23, 4) + Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4); }; - Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, false, 23, 4) + Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4); }; - Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, true, 52, 8) + Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8); }; - Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, false, 52, 8) + Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8); }; - function checkInt (buf, value, offset, ext, max, min) { - if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') + function checkInt(buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) throw new RangeError("Index out of range"); } - Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } + Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } + var mul = 1; + var i = 0; + this[offset] = value & 0xff; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xff; + } - return offset + byteLength + return offset + byteLength; }; - Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } + Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xff; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xff; + } - return offset + byteLength + return offset + byteLength; }; - Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - this[offset] = (value & 0xff); - return offset + 1 + Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = value & 0xff; + return offset + 1; }; - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8; - } + function objectWriteUInt16(buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> ((littleEndian ? i : 1 - i) * 8); + } } - Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 + Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2; }; - Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 + Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2; }; - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; - } + function objectWriteUInt32(buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> ((littleEndian ? i : 3 - i) * 8)) & 0xff; + } } - Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24); - this[offset + 2] = (value >>> 16); - this[offset + 1] = (value >>> 8); - this[offset] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 + Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 0xff; + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4; }; - Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 + Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4; }; - Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); + Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - var i = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xff; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = (((value / mul) >> 0) - sub) & 0xff; + } - return offset + byteLength + return offset + byteLength; }; - Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); + Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - var i = byteLength - 1; - var mul = 1; - var sub = 0; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xff; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = (((value / mul) >> 0) - sub) & 0xff; + } - return offset + byteLength + return offset + byteLength; }; - Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - if (value < 0) value = 0xff + value + 1; - this[offset] = (value & 0xff); - return offset + 1 + Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = value & 0xff; + return offset + 1; }; - Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 + Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2; }; - Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 + Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2; }; - Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - this[offset + 2] = (value >>> 16); - this[offset + 3] = (value >>> 24); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 + Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4; }; - Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 + Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4; }; - function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') + function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError("Index out of range"); + if (offset < 0) throw new RangeError("Index out of range"); } - function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4); - } - write(buf, value, offset, littleEndian, 23, 4); - return offset + 4 + function writeFloat(buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write(buf, value, offset, littleEndian, 23, 4); + return offset + 4; } - Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) + Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); }; - Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) + Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); }; - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8); - } - write(buf, value, offset, littleEndian, 52, 8); - return offset + 8 + function writeDouble(buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write(buf, value, offset, littleEndian, 52, 8); + return offset + 8; } - Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) + Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); }; - Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) + Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$1.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (targetStart >= target.length) targetStart = target.length; - if (!targetStart) targetStart = 0; - if (end > 0 && end < start) end = start; - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } + Buffer.prototype.copy = function copy(target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0; + if (target.length === 0 || this.length === 0) return 0; + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError("targetStart out of bounds"); + } + if (start < 0 || start >= this.length) throw new RangeError("sourceStart out of bounds"); + if (end < 0) throw new RangeError("sourceEnd out of bounds"); - var len = end - start; - var i; + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start]; - } - } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start]; - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ); - } + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart); + } - return len + return len; }; // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$1.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === 'string') { - encoding = end; - end = this.length; - } - if (val.length === 1) { - var code = val.charCodeAt(0); - if (code < 256) { - val = code; - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255; - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } + Buffer.prototype.fill = function fill(val, start, end, encoding) { + // Handle string cases: + if (typeof val === "string") { + if (typeof start === "string") { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === "string") { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== "string") { + throw new TypeError("encoding must be a string"); + } + if (typeof encoding === "string" && !Buffer.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + } else if (typeof val === "number") { + val = val & 255; + } - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError("Out of range index"); + } - if (!val) val = 0; + if (end <= start) { + return this; + } - var i; - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = internalIsBuffer(val) - ? val - : utf8ToBytes(new Buffer$1(val, encoding).toString()); - var len = bytes.length; - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === "number") { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } - return this + return this; }; // HELPER FUNCTIONS @@ -2317,165 +2277,151 @@ sap.ui.define((function () { 'use strict'; var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, ''); - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '='; - } - return str + function base64clean(str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ""); + // Node converts strings with length < 2 to '' + if (str.length < 2) return ""; + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + "="; + } + return str; } - function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') + function stringtrim(str) { + if (str.trim) return str.trim(); + return str.replace(/^\s+|\s+$/g, ""); } - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) + function toHex(n) { + if (n < 16) return "0" + n.toString(16); + return n.toString(16); } - function utf8ToBytes (string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } - - // valid lead - leadSurrogate = codePoint; - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue - } + function utf8ToBytes(string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xd7ff && codePoint < 0xe000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xdbff) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + continue; + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + continue; + } + + // valid lead + leadSurrogate = codePoint; + + continue; + } - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - } + // 2 leads in a row + if (codePoint < 0xdc00) { + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + leadSurrogate = codePoint; + continue; + } - leadSurrogate = null; - - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint); - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else { - throw new Error('Invalid code point') - } - } + // valid surrogate pair + codePoint = (((leadSurrogate - 0xd800) << 10) | (codePoint - 0xdc00)) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break; + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break; + bytes.push((codePoint >> 0x6) | 0xc0, (codePoint & 0x3f) | 0x80); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break; + bytes.push((codePoint >> 0xc) | 0xe0, ((codePoint >> 0x6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break; + bytes.push((codePoint >> 0x12) | 0xf0, ((codePoint >> 0xc) & 0x3f) | 0x80, ((codePoint >> 0x6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80); + } else { + throw new Error("Invalid code point"); + } + } - return bytes + return bytes; } - function asciiToBytes (str) { - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); - } - return byteArray + function asciiToBytes(str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xff); + } + return byteArray; } - function utf16leToBytes (str, units) { - var c, hi, lo; - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } + function utf16leToBytes(str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break; + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } - return byteArray + return byteArray; } - - function base64ToBytes (str) { - return toByteArray(base64clean(str)) + function base64ToBytes(str) { + return toByteArray(base64clean(str)); } - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i]; - } - return i + function blitBuffer(src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if (i + offset >= dst.length || i >= src.length) break; + dst[i + offset] = src[i]; + } + return i; } - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare + function isnan(val) { + return val !== val; // eslint-disable-line no-self-compare } - // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually function isBuffer$1(obj) { - return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)); } - function isFastBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + function isFastBuffer(obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj); } // For Node v0.10 support. Remove this eventually. - function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + function isSlowBuffer(obj) { + return typeof obj.readFloatLE === "function" && typeof obj.slice === "function" && isFastBuffer(obj.slice(0, 0)); } // shim for using process in browser @@ -2725,106 +2671,108 @@ sap.ui.define((function () { 'use strict'; } var inherits$1 = inherits; - var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || - function getOwnPropertyDescriptors(obj) { - var keys = Object.keys(obj); - var descriptors = {}; - for (var i = 0; i < keys.length; i++) { - descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); - } - return descriptors; - }; + var getOwnPropertyDescriptors = + Object.getOwnPropertyDescriptors || + function getOwnPropertyDescriptors(obj) { + var keys = Object.keys(obj); + var descriptors = {}; + for (var i = 0; i < keys.length; i++) { + descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); + } + return descriptors; + }; var formatRegExp = /%[sdj%]/g; function format$1(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect(arguments[i])); + } + return objects.join(" "); + } - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function (x) { + if (x === "%%") return "%"; + if (i >= len) return x; + switch (x) { + case "%s": + return String(args[i++]); + case "%d": + return Number(args[i++]); + case "%j": + try { + return JSON.stringify(args[i++]); + } catch (_) { + return "[Circular]"; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += " " + x; + } else { + str += " " + inspect(x); + } + } + return str; } // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. function deprecate(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global$1.process)) { - return function() { - return deprecate(fn, msg).apply(this, arguments); - }; - } + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$1.process)) { + return function () { + return deprecate(fn, msg).apply(this, arguments); + }; + } - if (browser$1.noDeprecation === true) { - return fn; - } + if (browser$1.noDeprecation === true) { + return fn; + } - var warned = false; - function deprecated() { - if (!warned) { - if (browser$1.throwDeprecation) { - throw new Error(msg); - } else if (browser$1.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } + var warned = false; + function deprecated() { + if (!warned) { + if (browser$1.throwDeprecation) { + throw new Error(msg); + } else if (browser$1.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } - return deprecated; + return deprecated; } var debugs = {}; var debugEnviron; function debuglog(set) { - if (isUndefined(debugEnviron)) - debugEnviron = browser$1.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = 0; - debugs[set] = function() { - var msg = format$1.apply(null, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; + if (isUndefined(debugEnviron)) debugEnviron = browser$1.env.NODE_DEBUG || ""; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp("\\b" + set + "\\b", "i").test(debugEnviron)) { + var pid = 0; + debugs[set] = function () { + var msg = format$1.apply(null, arguments); + console.error("%s %d: %s", set, pid, msg); + }; + } else { + debugs[set] = function () {}; + } + } + return debugs[set]; } /** @@ -2836,573 +2784,571 @@ sap.ui.define((function () { 'use strict'; */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - _extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor, + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); } // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] + bold: [1, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + white: [37, 39], + grey: [90, 39], + black: [30, 39], + blue: [34, 39], + cyan: [36, 39], + green: [32, 39], + magenta: [35, 39], + red: [31, 39], + yellow: [33, 39], }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' + special: "cyan", + number: "yellow", + boolean: "yellow", + undefined: "grey", + null: "bold", + string: "green", + date: "magenta", + // "name": intentionally not styling + regexp: "red", }; - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + var style = inspect.styles[styleType]; - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } + if (style) { + return "\u001b[" + inspect.colors[style][0] + "m" + str + "\u001b[" + inspect.colors[style][1] + "m"; + } else { + return str; + } } - function stylizeNoColor(str, styleType) { - return str; + return str; } - function arrayToHash(array) { - var hash = {}; + var hash = {}; - array.forEach(function(val, idx) { - hash[val] = true; - }); + array.forEach(function (val, idx) { + hash[val] = true; + }); - return hash; + return hash; } - function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction$1(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if ( + ctx.customInspect && + value && + isFunction$1(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value) + ) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) { + return formatError(value); + } - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction$1(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction$1(value)) { + var name = value.name ? ": " + value.name : ""; + return ctx.stylize("[Function" + name + "]", "special"); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), "date"); + } + if (isError(value)) { + return formatError(value); + } + } - var base = '', array = false, braces = ['{', '}']; + var base = "", + array = false, + braces = ["{", "}"]; - // Make Array say that they are Array - if (isArray$1(value)) { - array = true; - braces = ['[', ']']; - } + // Make Array say that they are Array + if (isArray$1(value)) { + array = true; + braces = ["[", "]"]; + } - // Make functions say that they are functions - if (isFunction$1(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } + // Make functions say that they are functions + if (isFunction$1(value)) { + var n = value.name ? ": " + value.name : ""; + base = " [Function" + n + "]"; + } - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = " " + RegExp.prototype.toString.call(value); + } - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } + // Make dates with properties first say the date + if (isDate(value)) { + base = " " + Date.prototype.toUTCString.call(value); + } - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } + // Make error with message first say the error + if (isError(value)) { + base = " " + formatError(value); + } - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); + } else { + return ctx.stylize("[Object]", "special"); + } + } - ctx.seen.push(value); + ctx.seen.push(value); - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function (key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } - ctx.seen.pop(); + ctx.seen.pop(); - return reduceToSingleString(output, base, braces); + return reduceToSingleString(output, base, braces); } - function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); + if (isUndefined(value)) return ctx.stylize("undefined", "undefined"); + if (isString(value)) { + var simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'"; + return ctx.stylize(simple, "string"); + } + if (isNumber(value)) return ctx.stylize("" + value, "number"); + if (isBoolean(value)) return ctx.stylize("" + value, "boolean"); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) return ctx.stylize("null", "null"); } - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; + return "[" + Error.prototype.toString.call(value) + "]"; } - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty$1(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty$1(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); + } else { + output.push(""); + } + } + keys.forEach(function (key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); + } + }); + return output; } - function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty$1(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize("[Getter/Setter]", "special"); + } else { + str = ctx.stylize("[Getter]", "special"); + } + } else { + if (desc.set) { + str = ctx.stylize("[Setter]", "special"); + } + } + if (!hasOwnProperty$1(visibleKeys, key)) { + name = "[" + key + "]"; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf("\n") > -1) { + if (array) { + str = str + .split("\n") + .map(function (line) { + return " " + line; + }) + .join("\n") + .substr(2); + } else { + str = + "\n" + + str + .split("\n") + .map(function (line) { + return " " + line; + }) + .join("\n"); + } + } + } else { + str = ctx.stylize("[Circular]", "special"); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify("" + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, "name"); + } else { + name = name + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, "string"); + } + } - return name + ': ' + str; + return name + ": " + str; } - function reduceToSingleString(output, base, braces) { - var length = output.reduce(function(prev, cur) { - if (cur.indexOf('\n') >= 0) ; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); - - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } + var length = output.reduce(function (prev, cur) { + if (cur.indexOf("\n") >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, "").length + 1; + }, 0); - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } + if (length > 60) { + return braces[0] + (base === "" ? "" : base + "\n ") + " " + output.join(",\n ") + " " + braces[1]; + } + return braces[0] + base + " " + output.join(", ") + " " + braces[1]; + } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray$1(ar) { - return Array.isArray(ar); + return Array.isArray(ar); } function isBoolean(arg) { - return typeof arg === 'boolean'; + return typeof arg === "boolean"; } function isNull(arg) { - return arg === null; + return arg === null; } function isNullOrUndefined(arg) { - return arg == null; + return arg == null; } function isNumber(arg) { - return typeof arg === 'number'; + return typeof arg === "number"; } function isString(arg) { - return typeof arg === 'string'; + return typeof arg === "string"; } function isSymbol(arg) { - return typeof arg === 'symbol'; + return typeof arg === "symbol"; } function isUndefined(arg) { - return arg === void 0; + return arg === void 0; } function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; + return isObject(re) && objectToString(re) === "[object RegExp]"; } function isObject(arg) { - return typeof arg === 'object' && arg !== null; + return typeof arg === "object" && arg !== null; } function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; + return isObject(d) && objectToString(d) === "[object Date]"; } function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); + return isObject(e) && (objectToString(e) === "[object Error]" || e instanceof Error); } function isFunction$1(arg) { - return typeof arg === 'function'; + return typeof arg === "function"; } function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; + return ( + arg === null || + typeof arg === "boolean" || + typeof arg === "number" || + typeof arg === "string" || + typeof arg === "symbol" || // ES6 symbol + typeof arg === "undefined" + ); } function isBuffer(maybeBuf) { - return Buffer$1.isBuffer(maybeBuf); + return Buffer.isBuffer(maybeBuf); } function objectToString(o) { - return Object.prototype.toString.call(o); + return Object.prototype.toString.call(o); } - function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); + return n < 10 ? "0" + n.toString(10) : n.toString(10); } - - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; + var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; // 26 Feb 16:19:34 function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); + var d = new Date(); + var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(":"); + return [d.getDate(), months[d.getMonth()], time].join(" "); } - // log is just a thin wrapper to console.log that prepends a timestamp function log() { - console.log('%s - %s', timestamp(), format$1.apply(null, arguments)); + console.log("%s - %s", timestamp(), format$1.apply(null, arguments)); } function _extend(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; } + function hasOwnProperty$1(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); + return Object.prototype.hasOwnProperty.call(obj, prop); } - var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; + var kCustomPromisifiedSymbol = typeof Symbol !== "undefined" ? Symbol("util.promisify.custom") : undefined; function promisify(original) { - if (typeof original !== 'function') - throw new TypeError('The "original" argument must be of type Function'); - - if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { - var fn = original[kCustomPromisifiedSymbol]; - if (typeof fn !== 'function') { - throw new TypeError('The "util.promisify.custom" argument must be of type Function'); - } - Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return fn; - } + if (typeof original !== "function") throw new TypeError('The "original" argument must be of type Function'); + + if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { + var fn = original[kCustomPromisifiedSymbol]; + if (typeof fn !== "function") { + throw new TypeError('The "util.promisify.custom" argument must be of type Function'); + } + Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, + enumerable: false, + writable: false, + configurable: true, + }); + return fn; + } - function fn() { - var promiseResolve, promiseReject; - var promise = new Promise(function (resolve, reject) { - promiseResolve = resolve; - promiseReject = reject; - }); + function fn() { + var promiseResolve, promiseReject; + var promise = new Promise(function (resolve, reject) { + promiseResolve = resolve; + promiseReject = reject; + }); - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } - args.push(function (err, value) { - if (err) { - promiseReject(err); - } else { - promiseResolve(value); - } - }); + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + args.push(function (err, value) { + if (err) { + promiseReject(err); + } else { + promiseResolve(value); + } + }); - try { - original.apply(this, args); - } catch (err) { - promiseReject(err); - } + try { + original.apply(this, args); + } catch (err) { + promiseReject(err); + } - return promise; - } + return promise; + } - Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); + Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); - if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return Object.defineProperties( - fn, - getOwnPropertyDescriptors(original) - ); + if (kCustomPromisifiedSymbol) + Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, + enumerable: false, + writable: false, + configurable: true, + }); + return Object.defineProperties(fn, getOwnPropertyDescriptors(original)); } promisify.custom = kCustomPromisifiedSymbol; function callbackifyOnRejected(reason, cb) { - // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). - // Because `null` is a special error value in callbacks which means "no error - // occurred", we error-wrap so the callback consumer can distinguish between - // "the promise rejected with null" or "the promise fulfilled with undefined". - if (!reason) { - var newReason = new Error('Promise was rejected with a falsy value'); - newReason.reason = reason; - reason = newReason; - } - return cb(reason); + // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). + // Because `null` is a special error value in callbacks which means "no error + // occurred", we error-wrap so the callback consumer can distinguish between + // "the promise rejected with null" or "the promise fulfilled with undefined". + if (!reason) { + var newReason = new Error("Promise was rejected with a falsy value"); + newReason.reason = reason; + reason = newReason; + } + return cb(reason); } function callbackify(original) { - if (typeof original !== 'function') { - throw new TypeError('The "original" argument must be of type Function'); - } + if (typeof original !== "function") { + throw new TypeError('The "original" argument must be of type Function'); + } - // We DO NOT return the promise as it gives the user a false sense that - // the promise is actually somehow related to the callback's execution - // and that the callback throwing will reject the promise. - function callbackified() { - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); - } + // We DO NOT return the promise as it gives the user a false sense that + // the promise is actually somehow related to the callback's execution + // and that the callback throwing will reject the promise. + function callbackified() { + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + + var maybeCb = args.pop(); + if (typeof maybeCb !== "function") { + throw new TypeError("The last argument must be of type Function"); + } + var self = this; + var cb = function () { + return maybeCb.apply(self, arguments); + }; + // In true node style we process the callback on `nextTick` with all the + // implications (stack, `uncaughtException`, `async_hooks`) + original.apply(this, args).then( + function (ret) { + browser$1.nextTick(cb.bind(null, null, ret)); + }, + function (rej) { + browser$1.nextTick(callbackifyOnRejected.bind(null, rej, cb)); + } + ); + } - var maybeCb = args.pop(); - if (typeof maybeCb !== 'function') { - throw new TypeError('The last argument must be of type Function'); - } - var self = this; - var cb = function() { - return maybeCb.apply(self, arguments); - }; - // In true node style we process the callback on `nextTick` with all the - // implications (stack, `uncaughtException`, `async_hooks`) - original.apply(this, args) - .then(function(ret) { browser$1.nextTick(cb.bind(null, null, ret)); }, - function(rej) { browser$1.nextTick(callbackifyOnRejected.bind(null, rej, cb)); }); - } + Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); + Object.defineProperties(callbackified, getOwnPropertyDescriptors(original)); + return callbackified; + } - Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); - Object.defineProperties(callbackified, getOwnPropertyDescriptors(original)); - return callbackified; + function isPromise(obj) { + return obj && typeof obj.then === "function"; } - var _polyfillNode_util = { - inherits: inherits$1, - _extend: _extend, - log: log, - isBuffer: isBuffer, - isPrimitive: isPrimitive, - isFunction: isFunction$1, - isError: isError, - isDate: isDate, - isObject: isObject, - isRegExp: isRegExp, - isUndefined: isUndefined, - isSymbol: isSymbol, - isString: isString, - isNumber: isNumber, - isNullOrUndefined: isNullOrUndefined, - isNull: isNull, - isBoolean: isBoolean, - isArray: isArray$1, - inspect: inspect, - deprecate: deprecate, - format: format$1, - debuglog: debuglog, - promisify: promisify, - callbackify: callbackify, + const types = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer, + isPrimitive: isPrimitive, + isFunction: isFunction$1, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray$1, + inspect: inspect, + deprecate: deprecate, + format: format$1, + debuglog: debuglog, + promisify: promisify, + callbackify: callbackify, + isPromise: isPromise, }; - var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({ + var _polyfillNode_util = /*#__PURE__*/Object.freeze({ __proto__: null, _extend: _extend, callbackify: callbackify, debuglog: debuglog, - default: _polyfillNode_util, + default: types, deprecate: deprecate, format: format$1, inherits: inherits$1, @@ -3418,15 +3364,17 @@ sap.ui.define((function () { 'use strict'; isNumber: isNumber, isObject: isObject, isPrimitive: isPrimitive, + isPromise: isPromise, isRegExp: isRegExp, isString: isString, isSymbol: isSymbol, isUndefined: isUndefined, log: log, - promisify: promisify + promisify: promisify, + types: types }); - var require$$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util$1); + var require$$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util); var domain; @@ -3943,9 +3891,9 @@ sap.ui.define((function () { 'use strict'; }; BufferList.prototype.concat = function (n) { - if (this.length === 0) return Buffer$1.alloc(0); + if (this.length === 0) return Buffer.alloc(0); if (this.length === 1) return this.head.data; - var ret = Buffer$1.allocUnsafe(n >>> 0); + var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { @@ -3977,7 +3925,7 @@ sap.ui.define((function () { 'use strict'; // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. - var isBufferEncoding = Buffer$1.isEncoding + var isBufferEncoding = Buffer.isEncoding || function(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; @@ -4026,7 +3974,7 @@ sap.ui.define((function () { 'use strict'; // Enough space to store all bytes of a single character. UTF-8 needs 4 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). - this.charBuffer = new Buffer$1(6); + this.charBuffer = new Buffer(6); // Number of bytes received for the current incomplete multi-byte character. this.charReceived = 0; // Number of bytes expected for the current incomplete multi-byte character. @@ -4291,7 +4239,7 @@ sap.ui.define((function () { 'use strict'; if (!state.objectMode && typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { - chunk = Buffer$1.from(chunk, encoding); + chunk = Buffer.from(chunk, encoding); encoding = ''; } } @@ -4517,7 +4465,7 @@ sap.ui.define((function () { 'use strict'; function chunkInvalid(state, chunk) { var er = null; - if (!Buffer$1.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; @@ -5001,7 +4949,7 @@ sap.ui.define((function () { 'use strict'; // 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$1.allocUnsafe(n); + var ret = Buffer.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); @@ -5230,7 +5178,7 @@ sap.ui.define((function () { 'use strict'; // if it is not a buffer, string, or undefined. if (chunk === null) { er = new TypeError('May not write null values to stream'); - } else if (!Buffer$1.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { @@ -5250,7 +5198,7 @@ sap.ui.define((function () { 'use strict'; encoding = null; } - if (Buffer$1.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; @@ -5288,7 +5236,7 @@ sap.ui.define((function () { 'use strict'; function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { - chunk = Buffer$1.from(chunk, encoding); + chunk = Buffer.from(chunk, encoding); } return chunk; } @@ -5299,7 +5247,7 @@ sap.ui.define((function () { 'use strict'; function writeOrBuffer(stream, state, chunk, encoding, cb) { chunk = decodeChunk(state, chunk, encoding); - if (Buffer$1.isBuffer(chunk)) encoding = 'buffer'; + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; var len = state.objectMode ? 1 : chunk.length; state.length += len; @@ -6538,7 +6486,7 @@ sap.ui.define((function () { 'use strict'; self.push(null); return } - self.push(new Buffer$1(result.value)); + self.push(new Buffer(result.value)); read(); }); }; @@ -6606,7 +6554,7 @@ sap.ui.define((function () { 'use strict'; // pass } if (response !== null) { - self.push(new Buffer$1(response)); + self.push(new Buffer(response)); break } // Falls through in IE8 @@ -6620,7 +6568,7 @@ sap.ui.define((function () { 'use strict'; if (response.length > self._pos) { var newData = response.substr(self._pos); if (self._charset === 'x-user-defined') { - var buffer = new Buffer$1(newData.length); + var buffer = new Buffer(newData.length); for (var i = 0; i < newData.length; i++) buffer[i] = newData.charCodeAt(i) & 0xff; @@ -6635,13 +6583,13 @@ sap.ui.define((function () { 'use strict'; if (xhr.readyState !== rStates.DONE || !xhr.response) break response = xhr.response; - self.push(new Buffer$1(new Uint8Array(response))); + self.push(new Buffer(new Uint8Array(response))); break case 'moz-chunked-arraybuffer': // take whole response = xhr.response; if (xhr.readyState !== rStates.LOADING || !response) break - self.push(new Buffer$1(new Uint8Array(response))); + self.push(new Buffer(new Uint8Array(response))); break case 'ms-stream': response = xhr.response; @@ -6650,7 +6598,7 @@ sap.ui.define((function () { 'use strict'; var reader = new global$1.MSStreamReader(); reader.onprogress = function() { if (reader.result.byteLength > self._pos) { - self.push(new Buffer$1(new Uint8Array(reader.result.slice(self._pos)))); + self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))); self._pos = reader.result.byteLength; } }; @@ -6720,7 +6668,7 @@ sap.ui.define((function () { 'use strict'; self._body = []; self._headers = {}; if (opts.auth) - self.setHeader('Authorization', 'Basic ' + new Buffer$1(opts.auth).toString('base64')); + self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64')); Object.keys(opts.headers).forEach(function(name) { self.setHeader(name, opts.headers[name]); }); @@ -6819,7 +6767,7 @@ sap.ui.define((function () { 'use strict'; }); } else { // get utf8 string - body = Buffer$1.concat(self._body).toString(); + body = Buffer.concat(self._body).toString(); } } @@ -19385,8 +19333,8 @@ sap.ui.define((function () { 'use strict'; var nextTick = typeof setImmediate == 'function' ? setImmediate : ( - typeof process == 'object' && typeof process.nextTick == 'function' - ? process.nextTick + typeof browser$1 == 'object' && typeof browser$1.nextTick == 'function' + ? browser$1.nextTick : null ); @@ -20170,7 +20118,7 @@ sap.ui.define((function () { 'use strict'; } if (!this._valuesToMeasure.length) { - process.nextTick(cb.bind(this, null, knownLength)); + browser$1.nextTick(cb.bind(this, null, knownLength)); return; } diff --git a/packages/ui5-tooling-modules/test/__snap__/jspdf.js b/packages/ui5-tooling-modules/test/__snap__/jspdf.js index 49c349484..5531f67b1 100644 --- a/packages/ui5-tooling-modules/test/__snap__/jspdf.js +++ b/packages/ui5-tooling-modules/test/__snap__/jspdf.js @@ -1,4 +1,4 @@ -sap.ui.define(['exports', './jspdf/Ho2Fpw1t'], (function (exports, jspdf_es_min) { 'use strict'; +sap.ui.define(['exports', './jspdf/Ovurvj05'], (function (exports, jspdf_es_min) { 'use strict'; diff --git a/packages/ui5-tooling-modules/test/__snap__/jspdf/Ho2Fpw1t.js b/packages/ui5-tooling-modules/test/__snap__/jspdf/Ovurvj05.js similarity index 98% rename from packages/ui5-tooling-modules/test/__snap__/jspdf/Ho2Fpw1t.js rename to packages/ui5-tooling-modules/test/__snap__/jspdf/Ovurvj05.js index 9d75df6fe..16eb9dfaf 100644 --- a/packages/ui5-tooling-modules/test/__snap__/jspdf/Ho2Fpw1t.js +++ b/packages/ui5-tooling-modules/test/__snap__/jspdf/Ovurvj05.js @@ -1,5 +1,9 @@ sap.ui.define(['require', 'exports'], (function (require, exports) { 'use strict'; + var global$1 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + var _typeof = {exports: {}}; (function (module) { @@ -750,57 +754,7 @@ sap.ui.define(['require', 'exports'], (function (require, exports) { 'use strict return inflt((zlv(data), data.subarray(2, -4)), out); } - /** @license - * - * jsPDF - PDF Document creation from JavaScript - * Version 2.5.1 Built on 2022-01-28T15:37:57.791Z - * CommitID 00000000 - * - * Copyright (c) 2010-2021 James Hall , https://github.com/MrRio/jsPDF - * 2015-2021 yWorks GmbH, http://www.yworks.com - * 2015-2021 Lukas Holländer , https://github.com/HackbrettXXX - * 2016-2018 Aras Abbasi - * 2010 Aaron Spike, https://github.com/acspike - * 2012 Willow Systems Corporation, https://github.com/willowsystems - * 2012 Pablo Hess, https://github.com/pablohess - * 2012 Florian Jenett, https://github.com/fjenett - * 2013 Warren Weckesser, https://github.com/warrenweckesser - * 2013 Youssef Beddad, https://github.com/lifof - * 2013 Lee Driscoll, https://github.com/lsdriscoll - * 2013 Stefan Slonevskiy, https://github.com/stefslon - * 2013 Jeremy Morel, https://github.com/jmorel - * 2013 Christoph Hartmann, https://github.com/chris-rock - * 2014 Juan Pablo Gaviria, https://github.com/juanpgaviria - * 2014 James Makes, https://github.com/dollaruw - * 2014 Diego Casorran, https://github.com/diegocr - * 2014 Steven Spungin, https://github.com/Flamenco - * 2014 Kenneth Glassey, https://github.com/Gavvers - * - * 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. - * - * Contributor(s): - * siefkenj, ahwolf, rickygu, Midnith, saintclair, eaparango, - * kim3er, mfo, alnorth, Flamenco - */ - - var n=function(){return "undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this}();function i(){n.console&&"function"==typeof n.console.log&&n.console.log.apply(n.console,arguments);}var a={log:i,warn:function(t){n.console&&("function"==typeof n.console.warn?n.console.warn.apply(n.console,arguments):i.call(null,arguments));},error:function(t){n.console&&("function"==typeof n.console.error?n.console.error.apply(n.console,arguments):i(t));}};function o(t,e,r){var n=new XMLHttpRequest;n.open("GET",t),n.responseType="blob",n.onload=function(){l(n.response,e,r);},n.onerror=function(){a.error("could not download file");},n.send();}function s(t){var e=new XMLHttpRequest;e.open("HEAD",t,!1);try{e.send();}catch(t){}return e.status>=200&&e.status<=299}function c(t){try{t.dispatchEvent(new MouseEvent("click"));}catch(r){var e=document.createEvent("MouseEvents");e.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),t.dispatchEvent(e);}}var u,h,l=n.saveAs||("object"!==("undefined"==typeof window?"undefined":_typeofExports(window))||window!==n?function(){}:"undefined"!=typeof HTMLAnchorElement&&"download"in HTMLAnchorElement.prototype?function(t,e,r){var i=n.URL||n.webkitURL,a=document.createElement("a");e=e||t.name||"download",a.download=e,a.rel="noopener","string"==typeof t?(a.href=t,a.origin!==location.origin?s(a.href)?o(t,e,r):c(a,a.target="_blank"):c(a)):(a.href=i.createObjectURL(t),setTimeout((function(){i.revokeObjectURL(a.href);}),4e4),setTimeout((function(){c(a);}),0));}:"msSaveOrOpenBlob"in navigator?function(e,r,n){if(r=r||e.name||"download","string"==typeof e)if(s(e))o(e,r,n);else {var i=document.createElement("a");i.href=e,i.target="_blank",setTimeout((function(){c(i);}));}else navigator.msSaveOrOpenBlob(function(e,r){return void 0===r?r={autoBom:!1}:"object"!==_typeofExports(r)&&(a.warn("Deprecated: Expected third argument to be a object"),r={autoBom:!r}),r.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob([String.fromCharCode(65279),e],{type:e.type}):e}(e,n),r);}:function(e,r,i,a){if((a=a||open("","_blank"))&&(a.document.title=a.document.body.innerText="downloading..."),"string"==typeof e)return o(e,r,i);var s="application/octet-stream"===e.type,c=/constructor/i.test(n.HTMLElement)||n.safari,u=/CriOS\/[\d]+/.test(navigator.userAgent);if((u||s&&c)&&"object"===("undefined"==typeof FileReader?"undefined":_typeofExports(FileReader))){var h=new FileReader;h.onloadend=function(){var t=h.result;t=u?t:t.replace(/^data:[^;]*;/,"data:attachment/file;"),a?a.location.href=t:location=t,a=null;},h.readAsDataURL(e);}else {var l=n.URL||n.webkitURL,f=l.createObjectURL(e);a?a.location=f:location.href=f,a=null,setTimeout((function(){l.revokeObjectURL(f);}),4e4);}}); + var n=function(){return "undefined"!=typeof window?window:"undefined"!=typeof global$1?global$1:"undefined"!=typeof self?self:this}();function i(){n.console&&"function"==typeof n.console.log&&n.console.log.apply(n.console,arguments);}var a={log:i,warn:function(t){n.console&&("function"==typeof n.console.warn?n.console.warn.apply(n.console,arguments):i.call(null,arguments));},error:function(t){n.console&&("function"==typeof n.console.error?n.console.error.apply(n.console,arguments):i(t));}};function o(t,e,r){var n=new XMLHttpRequest;n.open("GET",t),n.responseType="blob",n.onload=function(){l(n.response,e,r);},n.onerror=function(){a.error("could not download file");},n.send();}function s(t){var e=new XMLHttpRequest;e.open("HEAD",t,!1);try{e.send();}catch(t){}return e.status>=200&&e.status<=299}function c(t){try{t.dispatchEvent(new MouseEvent("click"));}catch(r){var e=document.createEvent("MouseEvents");e.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),t.dispatchEvent(e);}}var u,h,l=n.saveAs||("object"!==("undefined"==typeof window?"undefined":_typeofExports(window))||window!==n?function(){}:"undefined"!=typeof HTMLAnchorElement&&"download"in HTMLAnchorElement.prototype?function(t,e,r){var i=n.URL||n.webkitURL,a=document.createElement("a");e=e||t.name||"download",a.download=e,a.rel="noopener","string"==typeof t?(a.href=t,a.origin!==location.origin?s(a.href)?o(t,e,r):c(a,a.target="_blank"):c(a)):(a.href=i.createObjectURL(t),setTimeout((function(){i.revokeObjectURL(a.href);}),4e4),setTimeout((function(){c(a);}),0));}:"msSaveOrOpenBlob"in navigator?function(e,r,n){if(r=r||e.name||"download","string"==typeof e)if(s(e))o(e,r,n);else {var i=document.createElement("a");i.href=e,i.target="_blank",setTimeout((function(){c(i);}));}else navigator.msSaveOrOpenBlob(function(e,r){return void 0===r?r={autoBom:!1}:"object"!==_typeofExports(r)&&(a.warn("Deprecated: Expected third argument to be a object"),r={autoBom:!r}),r.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(e.type)?new Blob([String.fromCharCode(65279),e],{type:e.type}):e}(e,n),r);}:function(e,r,i,a){if((a=a||open("","_blank"))&&(a.document.title=a.document.body.innerText="downloading..."),"string"==typeof e)return o(e,r,i);var s="application/octet-stream"===e.type,c=/constructor/i.test(n.HTMLElement)||n.safari,u=/CriOS\/[\d]+/.test(navigator.userAgent);if((u||s&&c)&&"object"===("undefined"==typeof FileReader?"undefined":_typeofExports(FileReader))){var h=new FileReader;h.onloadend=function(){var t=h.result;t=u?t:t.replace(/^data:[^;]*;/,"data:attachment/file;"),a?a.location.href=t:location=t,a=null;},h.readAsDataURL(e);}else {var l=n.URL||n.webkitURL,f=l.createObjectURL(e);a?a.location=f:location.href=f,a=null,setTimeout((function(){l.revokeObjectURL(f);}),4e4);}}); /** * A class to parse color values * @author Stoyan Stefanov @@ -1040,7 +994,7 @@ sap.ui.define(['require', 'exports'], (function (require, exports) { 'use strict * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * ==================================================================== */ - function(t){function e(){return (n.canvg?Promise.resolve(n.canvg):new Promise(function (resolve, reject) { require(['./BU31YdNB'], resolve, reject); }).then(function (n) { return n.index; })).catch((function(t){return Promise.reject(new Error("Could not load canvg: "+t))})).then((function(t){return t.default?t.default:t}))}E.API.addSvgAsImage=function(t,r,n,i,o,s,c,u){if(isNaN(r)||isNaN(n))throw a.error("jsPDF.addSvgAsImage: Invalid coordinates",arguments),new Error("Invalid coordinates passed to jsPDF.addSvgAsImage");if(isNaN(i)||isNaN(o))throw a.error("jsPDF.addSvgAsImage: Invalid measurements",arguments),new Error("Invalid measurements (width and/or height) passed to jsPDF.addSvgAsImage");var h=document.createElement("canvas");h.width=i,h.height=o;var l=h.getContext("2d");l.fillStyle="#fff",l.fillRect(0,0,h.width,h.height);var f={ignoreMouse:!0,ignoreAnimation:!0,ignoreDimensions:!0},d=this;return e().then((function(e){return e.fromString(l,t,f)}),(function(){return Promise.reject(new Error("Could not load canvg."))})).then((function(t){return t.render(f)})).then((function(){d.addImage(h.toDataURL("image/jpeg",1),r,n,i,o,c,u);}))};}(),E.API.putTotalPages=function(t){var e,r=0;parseInt(this.internal.getFont().id.substr(1),10)<15?(e=new RegExp(t,"g"),r=this.internal.getNumberOfPages()):(e=new RegExp(this.pdfEscape16(t,this.internal.getFont()),"g"),r=this.pdfEscape16(this.internal.getNumberOfPages()+"",this.internal.getFont()));for(var n=1;n<=this.internal.getNumberOfPages();n++)for(var i=0;i1){for(l=0;l>");})),this.internal.viewerpreferences.isSubscribed=!0),this.internal.viewerpreferences.configuration=n,this}, + function(t){function e(){return (n.canvg?Promise.resolve(n.canvg):new Promise(function (resolve, reject) { require(['./d1gVbDW6'], resolve, reject); }).then(function (n) { return n.index; })).catch((function(t){return Promise.reject(new Error("Could not load canvg: "+t))})).then((function(t){return t.default?t.default:t}))}E.API.addSvgAsImage=function(t,r,n,i,o,s,c,u){if(isNaN(r)||isNaN(n))throw a.error("jsPDF.addSvgAsImage: Invalid coordinates",arguments),new Error("Invalid coordinates passed to jsPDF.addSvgAsImage");if(isNaN(i)||isNaN(o))throw a.error("jsPDF.addSvgAsImage: Invalid measurements",arguments),new Error("Invalid measurements (width and/or height) passed to jsPDF.addSvgAsImage");var h=document.createElement("canvas");h.width=i,h.height=o;var l=h.getContext("2d");l.fillStyle="#fff",l.fillRect(0,0,h.width,h.height);var f={ignoreMouse:!0,ignoreAnimation:!0,ignoreDimensions:!0},d=this;return e().then((function(e){return e.fromString(l,t,f)}),(function(){return Promise.reject(new Error("Could not load canvg."))})).then((function(t){return t.render(f)})).then((function(){d.addImage(h.toDataURL("image/jpeg",1),r,n,i,o,c,u);}))};}(),E.API.putTotalPages=function(t){var e,r=0;parseInt(this.internal.getFont().id.substr(1),10)<15?(e=new RegExp(t,"g"),r=this.internal.getNumberOfPages()):(e=new RegExp(this.pdfEscape16(t,this.internal.getFont()),"g"),r=this.pdfEscape16(this.internal.getNumberOfPages()+"",this.internal.getFont()));for(var n=1;n<=this.internal.getNumberOfPages();n++)for(var i=0;i1){for(l=0;l>");})),this.internal.viewerpreferences.isSubscribed=!0),this.internal.viewerpreferences.configuration=n,this}, /** ==================================================================== * @license * jsPDF XMP metadata plugin @@ -1095,6 +1049,7 @@ sap.ui.define(['require', 'exports'], (function (require, exports) { 'use strict exports.bt = bt; exports.dt = dt; exports.ft = ft; + exports.global = global$1; exports.gt = gt; exports.j = j; exports.mt = mt; diff --git a/packages/ui5-tooling-modules/test/__snap__/ui5-app/bundledefs/firebase.js b/packages/ui5-tooling-modules/test/__snap__/ui5-app/bundledefs/firebase.js index 8e4cfbf97..a4419b33b 100644 --- a/packages/ui5-tooling-modules/test/__snap__/ui5-app/bundledefs/firebase.js +++ b/packages/ui5-tooling-modules/test/__snap__/ui5-app/bundledefs/firebase.js @@ -27,14 +27,240 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return a; } - var index_cjs$1 = {}; + var index_cjs$2 = {}; + + var global$3 = (typeof global !== "undefined" ? global : + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : {}); + + // shim for using process in browser + // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + var cachedSetTimeout = defaultSetTimout; + var cachedClearTimeout = defaultClearTimeout; + if (typeof global$3.setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } + if (typeof global$3.clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } + + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + function nextTick(fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + } + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + var title = 'browser'; + var platform = 'browser'; + var browser$1 = true; + var env = {}; + var argv = []; + var version$3 = ''; // empty string to avoid regexp issues + var versions = {}; + var release = {}; + var config = {}; + + function noop$2() {} + + var on = noop$2; + var addListener = noop$2; + var once = noop$2; + var off = noop$2; + var removeListener = noop$2; + var removeAllListeners = noop$2; + var emit = noop$2; + + function binding$1(name) { + throw new Error('process.binding is not supported'); + } + + function cwd () { return '/' } + function chdir (dir) { + throw new Error('process.chdir is not supported'); + }function umask() { return 0; } + + // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js + var performance$1 = global$3.performance || {}; + var performanceNow = + performance$1.now || + performance$1.mozNow || + performance$1.msNow || + performance$1.oNow || + performance$1.webkitNow || + function(){ return (new Date()).getTime() }; + + // generate timestamp or delta + // see http://nodejs.org/api/process.html#process_process_hrtime + function hrtime(previousTimestamp){ + var clocktime = performanceNow.call(performance$1)*1e-3; + var seconds = Math.floor(clocktime); + var nanoseconds = Math.floor((clocktime%1)*1e9); + if (previousTimestamp) { + seconds = seconds - previousTimestamp[0]; + nanoseconds = nanoseconds - previousTimestamp[1]; + if (nanoseconds<0) { + seconds--; + nanoseconds += 1e9; + } + } + return [seconds,nanoseconds] + } + + var startTime = new Date(); + function uptime() { + var currentTime = new Date(); + var dif = currentTime - startTime; + return dif / 1000; + } + + var browser$1$1 = { + nextTick: nextTick, + title: title, + browser: browser$1, + env: env, + argv: argv, + version: version$3, + versions: versions, + on: on, + addListener: addListener, + once: once, + off: off, + removeListener: removeListener, + removeAllListeners: removeAllListeners, + emit: emit, + binding: binding$1, + cwd: cwd, + chdir: chdir, + umask: umask, + hrtime: hrtime, + platform: platform, + release: release, + config: config, + uptime: uptime + }; const CONSTANTS = { NODE_CLIENT: false, NODE_ADMIN: false, SDK_VERSION: "${JSCORE_VERSION}" }; - const assert = function (assertion, message) { + const assert$b = function (assertion, message) { if (!assertion) { throw assertionError(message); } @@ -254,17 +480,17 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; if (typeof window !== "undefined") { return window; } - if (typeof global !== "undefined") { - return global; + if (typeof global$3 !== "undefined") { + return global$3; } throw new Error("Unable to locate global object."); } const getDefaultsFromGlobal = () => getGlobal().__FIREBASE_DEFAULTS__; const getDefaultsFromEnvVariable = () => { - if (typeof process === "undefined" || typeof process.env === "undefined") { + if (typeof browser$1$1 === "undefined" || typeof browser$1$1.env === "undefined") { return; } - const defaultsJsonString = process.env.__FIREBASE_DEFAULTS__; + const defaultsJsonString = browser$1$1.env.__FIREBASE_DEFAULTS__; if (defaultsJsonString) { return JSON.parse(defaultsJsonString); } @@ -394,7 +620,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; return false; } try { - return Object.prototype.toString.call(global.process) === "[object process]"; + return Object.prototype.toString.call(global$3.process) === "[object process]"; } catch (e) { return false; } @@ -502,7 +728,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; function jsonEval(str) { return JSON.parse(str); } - function stringify(data) { + function stringify$2(data) { return JSON.stringify(data); } const decode = function (token) { @@ -573,7 +799,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } return true; } - function map(obj, fn, contextObj) { + function map$2(obj, fn, contextObj) { const res = {}; for (const key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { @@ -582,7 +808,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } return res; } - function deepEqual(a, b) { + function deepEqual$1(a, b) { if (a === b) { return true; } @@ -595,7 +821,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; const aProp = a[k]; const bProp = b[k]; if (isObject$1(aProp) && isObject$1(bProp)) { - if (!deepEqual(aProp, bProp)) { + if (!deepEqual$1(aProp, bProp)) { return false; } } else if (aProp !== bProp) { @@ -988,7 +1214,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; if (c >= 55296 && c <= 56319) { const high = c - 55296; i++; - assert(i < str.length, "Surrogate pair missing trail surrogate."); + assert$b(i < str.length, "Surrogate pair missing trail surrogate."); const low = str.charCodeAt(i) - 56320; c = 65536 + (high << 10) + low; } @@ -1074,7 +1300,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } } - var index_esm2017$3 = /*#__PURE__*/Object.freeze({ + var index_esm2017$2 = /*#__PURE__*/Object.freeze({ __proto__: null, CONSTANTS: CONSTANTS, DecodeBase64StringError: DecodeBase64StringError, @@ -1085,7 +1311,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; RANDOM_FACTOR: RANDOM_FACTOR, Sha1: Sha1, areCookiesEnabled: areCookiesEnabled, - assert: assert, + assert: assert$b, assertionError: assertionError, async: async, base64: base64, @@ -1098,7 +1324,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; createSubscribe: createSubscribe, decode: decode, deepCopy: deepCopy, - deepEqual: deepEqual, + deepEqual: deepEqual$1, deepExtend: deepExtend, errorPrefix: errorPrefix, extractQuerystring: extractQuerystring, @@ -1127,7 +1353,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; isValidTimestamp: isValidTimestamp, issuedAtTime: issuedAtTime, jsonEval: jsonEval, - map: map, + map: map$2, ordinal: ordinal, promiseWithTimeout: promiseWithTimeout, querystring: querystring, @@ -1135,7 +1361,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; safeGet: safeGet, stringLength: stringLength, stringToByteArray: stringToByteArray, - stringify: stringify, + stringify: stringify$2, uuidv4: uuidv4, validateArgCount: validateArgCount, validateCallback: validateCallback, @@ -1549,237 +1775,826 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } } - var index_esm2017$2 = /*#__PURE__*/Object.freeze({ + var index_esm2017$1 = /*#__PURE__*/Object.freeze({ __proto__: null, Component: Component, ComponentContainer: ComponentContainer, Provider: Provider }); - /** - * @license - * Copyright 2017 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - /** - * A container for all of the Logger instances - */ - const instances = []; - /** - * The JS SDK supports 5 log levels and also allows a user the ability to - * silence the logs altogether. - * - * The order is a follows: - * DEBUG < VERBOSE < INFO < WARN < ERROR - * - * All of the log types above the current log level will be captured (i.e. if - * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and - * `VERBOSE` logs will not) - */ - var LogLevel; - (function (LogLevel) { - LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG"; - LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE"; - LogLevel[LogLevel["INFO"] = 2] = "INFO"; - LogLevel[LogLevel["WARN"] = 3] = "WARN"; - LogLevel[LogLevel["ERROR"] = 4] = "ERROR"; - LogLevel[LogLevel["SILENT"] = 5] = "SILENT"; - })(LogLevel || (LogLevel = {})); - const levelStringToEnum = { - 'debug': LogLevel.DEBUG, - 'verbose': LogLevel.VERBOSE, - 'info': LogLevel.INFO, - 'warn': LogLevel.WARN, - 'error': LogLevel.ERROR, - 'silent': LogLevel.SILENT - }; - /** - * The default log level - */ - const defaultLogLevel = LogLevel.INFO; - /** - * By default, `console.debug` is not displayed in the developer console (in - * chrome). To avoid forcing users to have to opt-in to these logs twice - * (i.e. once for firebase, and once in the console), we are sending `DEBUG` - * logs to the `console.log` function. - */ - const ConsoleMethod = { - [LogLevel.DEBUG]: 'log', - [LogLevel.VERBOSE]: 'log', - [LogLevel.INFO]: 'info', - [LogLevel.WARN]: 'warn', - [LogLevel.ERROR]: 'error' - }; - /** - * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR - * messages on to their corresponding console counterparts (if the log method - * is supported by the current log level) - */ - const defaultLogHandler = (instance, logType, ...args) => { - if (logType < instance.logLevel) { - return; - } - const now = new Date().toISOString(); - const method = ConsoleMethod[logType]; - if (method) { - console[method](`[${now}] ${instance.name}:`, ...args); - } - else { - throw new Error(`Attempted to log a message with an invalid logType (value: ${logType})`); - } - }; - class Logger { - /** - * Gives you an instance of a Logger to capture messages according to - * Firebase's logging scheme. - * - * @param name The name that the logs will be associated with - */ - constructor(name) { - this.name = name; - /** - * The log level of the given Logger instance. - */ - this._logLevel = defaultLogLevel; - /** - * The main (internal) log handler for the Logger instance. - * Can be set to a new function in internal package code but not by user. - */ - this._logHandler = defaultLogHandler; - /** - * The optional, additional, user-defined log handler for the Logger instance. - */ - this._userLogHandler = null; - /** - * Capture the current instance for later use - */ - instances.push(this); - } - get logLevel() { - return this._logLevel; - } - set logLevel(val) { - if (!(val in LogLevel)) { - throw new TypeError(`Invalid value "${val}" assigned to \`logLevel\``); - } - this._logLevel = val; - } - // Workaround for setter/getter having to be the same type. - setLogLevel(val) { - this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val; - } - get logHandler() { - return this._logHandler; - } - set logHandler(val) { - if (typeof val !== 'function') { - throw new TypeError('Value assigned to `logHandler` must be a function'); - } - this._logHandler = val; - } - get userLogHandler() { - return this._userLogHandler; - } - set userLogHandler(val) { - this._userLogHandler = val; - } - /** - * The functions below are all based on the `console` interface - */ - debug(...args) { - this._userLogHandler && this._userLogHandler(this, LogLevel.DEBUG, ...args); - this._logHandler(this, LogLevel.DEBUG, ...args); - } - log(...args) { - this._userLogHandler && - this._userLogHandler(this, LogLevel.VERBOSE, ...args); - this._logHandler(this, LogLevel.VERBOSE, ...args); - } - info(...args) { - this._userLogHandler && this._userLogHandler(this, LogLevel.INFO, ...args); - this._logHandler(this, LogLevel.INFO, ...args); - } - warn(...args) { - this._userLogHandler && this._userLogHandler(this, LogLevel.WARN, ...args); - this._logHandler(this, LogLevel.WARN, ...args); - } - error(...args) { - this._userLogHandler && this._userLogHandler(this, LogLevel.ERROR, ...args); - this._logHandler(this, LogLevel.ERROR, ...args); - } - } - function setLogLevel$2(level) { - instances.forEach(inst => { - inst.setLogLevel(level); - }); - } - function setUserLogHandler(logCallback, options) { - for (const instance of instances) { - let customLogLevel = null; - if (options && options.level) { - customLogLevel = levelStringToEnum[options.level]; - } - if (logCallback === null) { - instance.userLogHandler = null; - } - else { - instance.userLogHandler = (instance, level, ...args) => { - const message = args - .map(arg => { - if (arg == null) { - return null; - } - else if (typeof arg === 'string') { - return arg; - } - else if (typeof arg === 'number' || typeof arg === 'boolean') { - return arg.toString(); - } - else if (arg instanceof Error) { - return arg.message; - } - else { - try { - return JSON.stringify(arg); - } - catch (ignored) { - return null; - } - } - }) - .filter(arg => arg) - .join(' '); - if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) { - logCallback({ - level: LogLevel[level].toLowerCase(), - message, - args, - type: instance.name - }); - } - }; - } - } - } + var index_cjs$1 = {}; - var index_esm2017$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - get LogLevel () { return LogLevel; }, - Logger: Logger, - setLogLevel: setLogLevel$2, - setUserLogHandler: setUserLogHandler - }); + var tslib = {exports: {}}; + + (function (module) { + var __extends; + var __assign; + var __rest; + var __decorate; + var __param; + var __esDecorate; + var __runInitializers; + var __propKey; + var __setFunctionName; + var __metadata; + var __awaiter; + var __generator; + var __exportStar; + var __values; + var __read; + var __spread; + var __spreadArrays; + var __spreadArray; + var __await; + var __asyncGenerator; + var __asyncDelegator; + var __asyncValues; + var __makeTemplateObject; + var __importStar; + var __importDefault; + var __classPrivateFieldGet; + var __classPrivateFieldSet; + var __classPrivateFieldIn; + var __createBinding; + var __addDisposableResource; + var __disposeResources; + (function (factory) { + var root = typeof commonjsGlobal === "object" ? commonjsGlobal : typeof self === "object" ? self : typeof this === "object" ? this : {}; + { + factory(createExporter(root, createExporter(module.exports))); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { + value: true + }); + } else { + exports.__esModule = true; + } + } + return function (id, v) { + return exports[id] = previous ? previous(id, v) : v; + }; + } + })(function (exporter) { + var extendStatics = Object.setPrototypeOf || ({ + __proto__: [] + }) instanceof Array && (function (d, b) { + d.__proto__ = b; + }) || (function (d, b) { + for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; + }); + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + __assign = Object.assign || (function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }); + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; + } + return t; + }; + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return (c > 3 && r && Object.defineProperty(target, key, r), r); + }; + __param = function (paramIndex, decorator) { + return function (target, key) { + decorator(target, key, paramIndex); + }; + }; + __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { + if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); + return f; + } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { + if (done) throw new TypeError("Cannot add initializers after decoration has completed"); + extraInitializers.push(accept(f || null)); + }; + var result = (0, decorators[i])(kind === "accessor" ? { + get: descriptor.get, + set: descriptor.set + } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + }; + __runInitializers = function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; + }; + __propKey = function (x) { + return typeof x === "symbol" ? x : ("").concat(x); + }; + __setFunctionName = function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? ("[").concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { + configurable: true, + value: prefix ? ("").concat(prefix, " ", name) : name + }); + }; + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { + return value instanceof P ? value : new P(function (resolve) { + resolve(value); + }); + } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { + try { + step(generator.next(value)); + } catch (e) { + reject(e); + } + } + function rejected(value) { + try { + step(generator["throw"](value)); + } catch (e) { + reject(e); + } + } + function step(result) { + result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); + } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + __generator = function (thisArg, body) { + var _ = { + label: 0, + sent: function () { + if (t[0] & 1) throw t[1]; + return t[1]; + }, + trys: [], + ops: [] + }, f, y, t, g; + return (g = { + next: verb(0), + "throw": verb(1), + "return": verb(2) + }, typeof Symbol === "function" && (g[Symbol.iterator] = function () { + return this; + }), g); + function verb(n) { + return function (v) { + return step([n, v]); + }; + } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while ((g && (g = 0, op[0] && (_ = 0)), _)) try { + if ((f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done)) return t; + if ((y = 0, t)) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: + case 1: + t = op; + break; + case 4: + _.label++; + return { + value: op[1], + done: false + }; + case 5: + _.label++; + y = op[1]; + op = [0]; + continue; + case 7: + op = _.ops.pop(); + _.trys.pop(); + continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { + _ = 0; + continue; + } + if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) { + _.label = op[1]; + break; + } + if (op[0] === 6 && _.label < t[1]) { + _.label = t[1]; + t = op; + break; + } + if (t && _.label < t[2]) { + _.label = t[2]; + _.ops.push(op); + break; + } + if (t[2]) _.ops.pop(); + _.trys.pop(); + continue; + } + op = body.call(thisArg, _); + } catch (e) { + op = [6, e]; + y = 0; + } finally { + f = t = 0; + } + if (op[0] & 5) throw op[1]; + return { + value: op[0] ? op[1] : void 0, + done: true + }; + } + }; + __exportStar = function (m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + __createBinding = Object.create ? function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || (("get" in desc) ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { + enumerable: true, + get: function () { + return m[k]; + } + }; + } + Object.defineProperty(o, k2, desc); + } : function (o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }; + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { + value: o && o[i++], + done: !o + }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } catch (error) { + e = { + error: error + }; + } finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } finally { + if (e) throw e.error; + } + } + return ar; + }; + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) ar = ar.concat(__read(arguments[i])); + return ar; + }; + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) for (var a = arguments[i], j = 0, jl = a.length; j < jl; (j++, k++)) r[k] = a[j]; + return r; + }; + __spreadArray = function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !((i in from))) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return (i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i); + function verb(n) { + if (g[n]) i[n] = function (v) { + return new Promise(function (a, b) { + q.push([n, v, a, b]) > 1 || resume(n, v); + }); + }; + } + function resume(n, v) { + try { + step(g[n](v)); + } catch (e) { + settle(q[0][3], e); + } + } + function step(r) { + r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); + } + function fulfill(value) { + resume("next", value); + } + function reject(value) { + resume("throw", value); + } + function settle(f, v) { + if ((f(v), q.shift(), q.length)) resume(q[0][0], q[0][1]); + } + }; + __asyncDelegator = function (o) { + var i, p; + return (i = {}, verb("next"), verb("throw", function (e) { + throw e; + }), verb("return"), i[Symbol.iterator] = function () { + return this; + }, i); + function verb(n, f) { + i[n] = o[n] ? function (v) { + return (p = !p) ? { + value: __await(o[n](v)), + done: false + } : f ? f(v) : v; + } : f; + } + }; + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { + return this; + }, i); + function verb(n) { + i[n] = o[n] && (function (v) { + return new Promise(function (resolve, reject) { + (v = o[n](v), settle(resolve, reject, v.done, v.value)); + }); + }); + } + function settle(resolve, reject, d, v) { + Promise.resolve(v).then(function (v) { + resolve({ + value: v, + done: d + }); + }, reject); + } + }; + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { + Object.defineProperty(cooked, "raw", { + value: raw + }); + } else { + cooked.raw = raw; + } + return cooked; + }; + var __setModuleDefault = Object.create ? function (o, v) { + Object.defineProperty(o, "default", { + enumerable: true, + value: v + }); + } : function (o, v) { + o["default"] = v; + }; + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; + }; + __importDefault = function (mod) { + return mod && mod.__esModule ? mod : { + "default": mod + }; + }; + __classPrivateFieldGet = function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + }; + __classPrivateFieldSet = function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value), value); + }; + __classPrivateFieldIn = function (state, receiver) { + if (receiver === null || typeof receiver !== "object" && typeof receiver !== "function") throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + __addDisposableResource = function (env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + env.stack.push({ + value: value, + dispose: dispose, + async: async + }); + } else if (async) { + env.stack.push({ + async: true + }); + } + return value; + }; + var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return (e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e); + }; + __disposeResources = function (env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + function next() { + while (env.stack.length) { + var rec = env.stack.pop(); + try { + var result = rec.dispose && rec.dispose.call(rec.value); + if (rec.async) return Promise.resolve(result).then(next, function (e) { + fail(e); + return next(); + }); + } catch (e) { + fail(e); + } + } + if (env.hasError) throw env.error; + } + return next(); + }; + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__esDecorate", __esDecorate); + exporter("__runInitializers", __runInitializers); + exporter("__propKey", __propKey); + exporter("__setFunctionName", __setFunctionName); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); + exporter("__classPrivateFieldIn", __classPrivateFieldIn); + exporter("__addDisposableResource", __addDisposableResource); + exporter("__disposeResources", __disposeResources); + }); + })(tslib); + var tslibExports = tslib.exports; + + (function (exports) { + + Object.defineProperty(exports, '__esModule', { value: true }); + + var tslib = tslibExports; + + /** + * @license + * Copyright 2017 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + var _a; + /** + * A container for all of the Logger instances + */ + var instances = []; + /** + * The JS SDK supports 5 log levels and also allows a user the ability to + * silence the logs altogether. + * + * The order is a follows: + * DEBUG < VERBOSE < INFO < WARN < ERROR + * + * All of the log types above the current log level will be captured (i.e. if + * you set the log level to `INFO`, errors will still be logged, but `DEBUG` and + * `VERBOSE` logs will not) + */ + exports.LogLevel = void 0; + (function (LogLevel) { + LogLevel[LogLevel["DEBUG"] = 0] = "DEBUG"; + LogLevel[LogLevel["VERBOSE"] = 1] = "VERBOSE"; + LogLevel[LogLevel["INFO"] = 2] = "INFO"; + LogLevel[LogLevel["WARN"] = 3] = "WARN"; + LogLevel[LogLevel["ERROR"] = 4] = "ERROR"; + LogLevel[LogLevel["SILENT"] = 5] = "SILENT"; + })(exports.LogLevel || (exports.LogLevel = {})); + var levelStringToEnum = { + 'debug': exports.LogLevel.DEBUG, + 'verbose': exports.LogLevel.VERBOSE, + 'info': exports.LogLevel.INFO, + 'warn': exports.LogLevel.WARN, + 'error': exports.LogLevel.ERROR, + 'silent': exports.LogLevel.SILENT + }; + /** + * The default log level + */ + var defaultLogLevel = exports.LogLevel.INFO; + /** + * By default, `console.debug` is not displayed in the developer console (in + * chrome). To avoid forcing users to have to opt-in to these logs twice + * (i.e. once for firebase, and once in the console), we are sending `DEBUG` + * logs to the `console.log` function. + */ + var ConsoleMethod = (_a = {}, + _a[exports.LogLevel.DEBUG] = 'log', + _a[exports.LogLevel.VERBOSE] = 'log', + _a[exports.LogLevel.INFO] = 'info', + _a[exports.LogLevel.WARN] = 'warn', + _a[exports.LogLevel.ERROR] = 'error', + _a); + /** + * The default log handler will forward DEBUG, VERBOSE, INFO, WARN, and ERROR + * messages on to their corresponding console counterparts (if the log method + * is supported by the current log level) + */ + var defaultLogHandler = function (instance, logType) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + if (logType < instance.logLevel) { + return; + } + var now = new Date().toISOString(); + var method = ConsoleMethod[logType]; + if (method) { + console[method].apply(console, tslib.__spreadArray(["[".concat(now, "] ").concat(instance.name, ":")], args, false)); + } + else { + throw new Error("Attempted to log a message with an invalid logType (value: ".concat(logType, ")")); + } + }; + var Logger = /** @class */ (function () { + /** + * Gives you an instance of a Logger to capture messages according to + * Firebase's logging scheme. + * + * @param name The name that the logs will be associated with + */ + function Logger(name) { + this.name = name; + /** + * The log level of the given Logger instance. + */ + this._logLevel = defaultLogLevel; + /** + * The main (internal) log handler for the Logger instance. + * Can be set to a new function in internal package code but not by user. + */ + this._logHandler = defaultLogHandler; + /** + * The optional, additional, user-defined log handler for the Logger instance. + */ + this._userLogHandler = null; + /** + * Capture the current instance for later use + */ + instances.push(this); + } + Object.defineProperty(Logger.prototype, "logLevel", { + get: function () { + return this._logLevel; + }, + set: function (val) { + if (!(val in exports.LogLevel)) { + throw new TypeError("Invalid value \"".concat(val, "\" assigned to `logLevel`")); + } + this._logLevel = val; + }, + enumerable: false, + configurable: true + }); + // Workaround for setter/getter having to be the same type. + Logger.prototype.setLogLevel = function (val) { + this._logLevel = typeof val === 'string' ? levelStringToEnum[val] : val; + }; + Object.defineProperty(Logger.prototype, "logHandler", { + get: function () { + return this._logHandler; + }, + set: function (val) { + if (typeof val !== 'function') { + throw new TypeError('Value assigned to `logHandler` must be a function'); + } + this._logHandler = val; + }, + enumerable: false, + configurable: true + }); + Object.defineProperty(Logger.prototype, "userLogHandler", { + get: function () { + return this._userLogHandler; + }, + set: function (val) { + this._userLogHandler = val; + }, + enumerable: false, + configurable: true + }); + /** + * The functions below are all based on the `console` interface + */ + Logger.prototype.debug = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + this._userLogHandler && this._userLogHandler.apply(this, tslib.__spreadArray([this, exports.LogLevel.DEBUG], args, false)); + this._logHandler.apply(this, tslib.__spreadArray([this, exports.LogLevel.DEBUG], args, false)); + }; + Logger.prototype.log = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + this._userLogHandler && this._userLogHandler.apply(this, tslib.__spreadArray([this, exports.LogLevel.VERBOSE], args, false)); + this._logHandler.apply(this, tslib.__spreadArray([this, exports.LogLevel.VERBOSE], args, false)); + }; + Logger.prototype.info = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + this._userLogHandler && this._userLogHandler.apply(this, tslib.__spreadArray([this, exports.LogLevel.INFO], args, false)); + this._logHandler.apply(this, tslib.__spreadArray([this, exports.LogLevel.INFO], args, false)); + }; + Logger.prototype.warn = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + this._userLogHandler && this._userLogHandler.apply(this, tslib.__spreadArray([this, exports.LogLevel.WARN], args, false)); + this._logHandler.apply(this, tslib.__spreadArray([this, exports.LogLevel.WARN], args, false)); + }; + Logger.prototype.error = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + this._userLogHandler && this._userLogHandler.apply(this, tslib.__spreadArray([this, exports.LogLevel.ERROR], args, false)); + this._logHandler.apply(this, tslib.__spreadArray([this, exports.LogLevel.ERROR], args, false)); + }; + return Logger; + }()); + function setLogLevel(level) { + instances.forEach(function (inst) { + inst.setLogLevel(level); + }); + } + function setUserLogHandler(logCallback, options) { + var _loop_1 = function (instance) { + var customLogLevel = null; + if (options && options.level) { + customLogLevel = levelStringToEnum[options.level]; + } + if (logCallback === null) { + instance.userLogHandler = null; + } + else { + instance.userLogHandler = function (instance, level) { + var args = []; + for (var _i = 2; _i < arguments.length; _i++) { + args[_i - 2] = arguments[_i]; + } + var message = args + .map(function (arg) { + if (arg == null) { + return null; + } + else if (typeof arg === 'string') { + return arg; + } + else if (typeof arg === 'number' || typeof arg === 'boolean') { + return arg.toString(); + } + else if (arg instanceof Error) { + return arg.message; + } + else { + try { + return JSON.stringify(arg); + } + catch (ignored) { + return null; + } + } + }) + .filter(function (arg) { return arg; }) + .join(' '); + if (level >= (customLogLevel !== null && customLogLevel !== void 0 ? customLogLevel : instance.logLevel)) { + logCallback({ + level: exports.LogLevel[level].toLowerCase(), + message: message, + args: args, + type: instance.name + }); + } + }; + } + }; + for (var _i = 0, instances_1 = instances; _i < instances_1.length; _i++) { + var instance = instances_1[_i]; + _loop_1(instance); + } + } + + exports.Logger = Logger; + exports.setLogLevel = setLogLevel; + exports.setUserLogHandler = setUserLogHandler; + + } (index_cjs$1)); + + var build = {}; + + var wrapIdbValue$1 = {}; const instanceOfAny = (object, constructors) => constructors.some((c) => object instanceof c); @@ -1965,6 +2780,16 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } const unwrap = (value) => reverseTransformCache.get(value); + wrapIdbValue$1.instanceOfAny = instanceOfAny; + wrapIdbValue$1.replaceTraps = replaceTraps; + wrapIdbValue$1.reverseTransformCache = reverseTransformCache; + wrapIdbValue$1.unwrap = unwrap; + wrapIdbValue$1.wrap = wrap; + + Object.defineProperty(build, '__esModule', { value: true }); + + var wrapIdbValue = wrapIdbValue$1; + /** * Open a database. * @@ -1974,10 +2799,10 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; */ function openDB(name, version, { blocked, upgrade, blocking, terminated } = {}) { const request = indexedDB.open(name, version); - const openPromise = wrap(request); + const openPromise = wrapIdbValue.wrap(request); if (upgrade) { request.addEventListener('upgradeneeded', (event) => { - upgrade(wrap(request.result), event.oldVersion, event.newVersion, wrap(request.transaction), event); + upgrade(wrapIdbValue.wrap(request.result), event.oldVersion, event.newVersion, wrapIdbValue.wrap(request.transaction), event); }); } if (blocked) { @@ -1996,6 +2821,20 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; .catch(() => { }); return openPromise; } + /** + * Delete a database. + * + * @param name Name of the database. + */ + function deleteDB(name, { blocked } = {}) { + const request = indexedDB.deleteDatabase(name); + if (blocked) { + request.addEventListener('blocked', (event) => blocked( + // Casting due to https://github.com/microsoft/TypeScript-DOM-lib-generator/pull/1405 + event.oldVersion, event)); + } + return wrapIdbValue.wrap(request).then(() => undefined); + } const readMethods = ['get', 'getKey', 'getAll', 'getAllKeys', 'count']; const writeMethods = ['put', 'add', 'delete', 'clear']; @@ -2036,12 +2875,17 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; cachedMethods.set(prop, method); return method; } - replaceTraps((oldTraps) => ({ + wrapIdbValue.replaceTraps((oldTraps) => ({ ...oldTraps, get: (target, prop, receiver) => getMethod(target, prop) || oldTraps.get(target, prop, receiver), has: (target, prop) => !!getMethod(target, prop) || oldTraps.has(target, prop), })); + build.unwrap = wrapIdbValue.unwrap; + build.wrap = wrapIdbValue.wrap; + build.deleteDB = deleteDB; + var openDB_1 = build.openDB = openDB; + /** * @license * Copyright 2019 Google LLC @@ -2096,7 +2940,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } const name$o = "@firebase/app"; - const version$1$1 = "0.9.19"; + const version$1$1 = "0.9.25"; /** * @license @@ -2114,7 +2958,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * See the License for the specific language governing permissions and * limitations under the License. */ - const logger$1 = new Logger('@firebase/app'); + const logger$1 = new index_cjs$1.Logger('@firebase/app'); const name$n = "@firebase/app-compat"; @@ -2163,7 +3007,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; const name$1 = "@firebase/firestore-compat"; const name = "firebase"; - const version$3 = "10.4.0"; + const version$2 = "10.7.1"; /** * @license @@ -2442,7 +3286,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @public */ - const SDK_VERSION$1 = version$3; + const SDK_VERSION$1 = version$2; function initializeApp(_options, rawConfig = {}) { let options = _options; if (typeof rawConfig !== 'object') { @@ -2463,8 +3307,8 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; const existingApp = _apps.get(name); if (existingApp) { // return the existing app if options and config deep equal the ones in the existing app. - if (deepEqual(options, existingApp.options) && - deepEqual(config, existingApp.config)) { + if (deepEqual$1(options, existingApp.options) && + deepEqual$1(config, existingApp.config)) { return existingApp; } else { @@ -2599,7 +3443,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; if (logCallback !== null && typeof logCallback !== 'function') { throw ERROR_FACTORY.create("invalid-log-argument" /* AppError.INVALID_LOG_ARGUMENT */); } - setUserLogHandler(logCallback, options); + index_cjs$1.setUserLogHandler(logCallback, options); } /** * Sets log level for all Firebase SDKs. @@ -2611,7 +3455,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * @public */ function setLogLevel$1(logLevel) { - setLogLevel$2(logLevel); + index_cjs$1.setLogLevel(logLevel); } /** @@ -2636,7 +3480,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; let dbPromise = null; function getDbPromise() { if (!dbPromise) { - dbPromise = openDB(DB_NAME, DB_VERSION, { + dbPromise = openDB_1(DB_NAME, DB_VERSION, { upgrade: (db, oldVersion) => { // We don't use 'break' in this switch statement, the fall-through // behavior is what we want, because if there are multiple versions between @@ -2748,6 +3592,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * already logged, subsequent calls to this function in the same day will be ignored. */ async triggerHeartbeat() { + var _a, _b; const platformLogger = this.container .getProvider('platform-logger') .getImmediate(); @@ -2755,8 +3600,12 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; // service, not the browser user agent. const agent = platformLogger.getPlatformInfoString(); const date = getUTCDateString(); - if (this._heartbeatsCache === null) { + if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null) { this._heartbeatsCache = await this._heartbeatsCachePromise; + // If we failed to construct a heartbeats cache, then return immediately. + if (((_b = this._heartbeatsCache) === null || _b === void 0 ? void 0 : _b.heartbeats) == null) { + return; + } } // Do not store a heartbeat if one is already stored for this day // or if a header has already been sent today. @@ -2784,11 +3633,12 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * returns an empty string. */ async getHeartbeatsHeader() { + var _a; if (this._heartbeatsCache === null) { await this._heartbeatsCachePromise; } // If it's still null or the array is empty, there is no data to send. - if (this._heartbeatsCache === null || + if (((_a = this._heartbeatsCache) === null || _a === void 0 ? void 0 : _a.heartbeats) == null || this._heartbeatsCache.heartbeats.length === 0) { return ''; } @@ -2884,7 +3734,12 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } else { const idbHeartbeatObject = await readHeartbeatsFromIndexedDB(this.app); - return idbHeartbeatObject || { heartbeats: [] }; + if (idbHeartbeatObject === null || idbHeartbeatObject === void 0 ? void 0 : idbHeartbeatObject.heartbeats) { + return idbHeartbeatObject; + } + else { + return { heartbeats: [] }; + } } } // overwrite the storage with the provided heartbeats @@ -2990,16 +3845,16 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; setLogLevel: setLogLevel$1 }); - var require$$0 = /*@__PURE__*/getAugmentedNamespace(index_esm2017); + var require$$0$2 = /*@__PURE__*/getAugmentedNamespace(index_esm2017); (function (exports) { Object.defineProperty(exports, '__esModule', { value: true }); - var app = require$$0; + var app = require$$0$2; var name = "firebase"; - var version = "10.4.0"; + var version = "10.7.1"; /** * @license @@ -3026,220 +3881,212 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; }); }); - } (index_cjs$1)); + } (index_cjs$2)); var index_cjs = {}; - var index_node_cjs = {}; - - var require$$1 = /*@__PURE__*/getAugmentedNamespace(index_esm2017$2); - - var require$$2 = /*@__PURE__*/getAugmentedNamespace(index_esm2017$1); - - var global$1 = (typeof global !== "undefined" ? global : - typeof self !== "undefined" ? self : - typeof window !== "undefined" ? window : {}); - var lookup = []; var revLookup = []; - var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + var Arr = typeof Uint8Array !== "undefined" ? Uint8Array : Array; var inited = false; - function init () { - inited = true; - var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; - for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i]; - revLookup[code.charCodeAt(i)] = i; - } + function init() { + inited = true; + var code = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } - revLookup['-'.charCodeAt(0)] = 62; - revLookup['_'.charCodeAt(0)] = 63; + revLookup["-".charCodeAt(0)] = 62; + revLookup["_".charCodeAt(0)] = 63; } - function toByteArray (b64) { - if (!inited) { - init(); - } - var i, j, l, tmp, placeHolders, arr; - var len = b64.length; + function toByteArray(b64) { + if (!inited) { + init(); + } + var i, j, l, tmp, placeHolders, arr; + var len = b64.length; - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } + if (len % 4 > 0) { + throw new Error("Invalid string. Length must be a multiple of 4"); + } - // the number of equal signs (place holders) - // if there are two placeholders, than the two characters before it - // represent one byte - // if there is only one, then the three characters before it represent 2 bytes - // this is just a cheap hack to not do indexOf twice - placeHolders = b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0; + // the number of equal signs (place holders) + // if there are two placeholders, than the two characters before it + // represent one byte + // if there is only one, then the three characters before it represent 2 bytes + // this is just a cheap hack to not do indexOf twice + placeHolders = b64[len - 2] === "=" ? 2 : b64[len - 1] === "=" ? 1 : 0; - // base64 is 4/3 + up to two characters of the original data - arr = new Arr(len * 3 / 4 - placeHolders); + // base64 is 4/3 + up to two characters of the original data + arr = new Arr((len * 3) / 4 - placeHolders); - // if there are placeholders, only get up to the last complete 4 chars - l = placeHolders > 0 ? len - 4 : len; + // if there are placeholders, only get up to the last complete 4 chars + l = placeHolders > 0 ? len - 4 : len; - var L = 0; + var L = 0; - for (i = 0, j = 0; i < l; i += 4, j += 3) { - tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; - arr[L++] = (tmp >> 16) & 0xFF; - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } + for (i = 0, j = 0; i < l; i += 4, j += 3) { + tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]; + arr[L++] = (tmp >> 16) & 0xff; + arr[L++] = (tmp >> 8) & 0xff; + arr[L++] = tmp & 0xff; + } - if (placeHolders === 2) { - tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); - arr[L++] = tmp & 0xFF; - } else if (placeHolders === 1) { - tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); - arr[L++] = (tmp >> 8) & 0xFF; - arr[L++] = tmp & 0xFF; - } + if (placeHolders === 2) { + tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[L++] = tmp & 0xff; + } else if (placeHolders === 1) { + tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[L++] = (tmp >> 8) & 0xff; + arr[L++] = tmp & 0xff; + } - return arr + return arr; } - function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] + function tripletToBase64(num) { + return lookup[(num >> 18) & 0x3f] + lookup[(num >> 12) & 0x3f] + lookup[(num >> 6) & 0x3f] + lookup[num & 0x3f]; } - function encodeChunk (uint8, start, end) { - var tmp; - var output = []; - for (var i = start; i < end; i += 3) { - tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]); - output.push(tripletToBase64(tmp)); - } - return output.join('') + function encodeChunk(uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + uint8[i + 2]; + output.push(tripletToBase64(tmp)); + } + return output.join(""); } - function fromByteArray (uint8) { - if (!inited) { - init(); - } - var tmp; - var len = uint8.length; - var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes - var output = ''; - var parts = []; - var maxChunkLength = 16383; // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); - } + function fromByteArray(uint8) { + if (!inited) { + init(); + } + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var output = ""; + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, i + maxChunkLength > len2 ? len2 : i + maxChunkLength)); + } - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1]; - output += lookup[tmp >> 2]; - output += lookup[(tmp << 4) & 0x3F]; - output += '=='; - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + (uint8[len - 1]); - output += lookup[tmp >> 10]; - output += lookup[(tmp >> 4) & 0x3F]; - output += lookup[(tmp << 2) & 0x3F]; - output += '='; - } + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + output += lookup[tmp >> 2]; + output += lookup[(tmp << 4) & 0x3f]; + output += "=="; + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + output += lookup[tmp >> 10]; + output += lookup[(tmp >> 4) & 0x3f]; + output += lookup[(tmp << 2) & 0x3f]; + output += "="; + } - parts.push(output); + parts.push(output); - return parts.join('') + return parts.join(""); } - function read (buffer, offset, isLE, mLen, nBytes) { - var e, m; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var nBits = -7; - var i = isLE ? (nBytes - 1) : 0; - var d = isLE ? -1 : 1; - var s = buffer[offset + i]; - - i += d; - - e = s & ((1 << (-nBits)) - 1); - s >>= (-nBits); - nBits += eLen; - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1); - e >>= (-nBits); - nBits += mLen; - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias; - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen); - e = e - eBias; - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + function read(buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << -nBits) - 1); + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << -nBits) - 1); + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); } - function write (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c; - var eLen = nBytes * 8 - mLen - 1; - var eMax = (1 << eLen) - 1; - var eBias = eMax >> 1; - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); - var i = isLE ? 0 : (nBytes - 1); - var d = isLE ? 1 : -1; - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; - - value = Math.abs(value); - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0; - e = eMax; - } else { - e = Math.floor(Math.log(value) / Math.LN2); - if (value * (c = Math.pow(2, -e)) < 1) { - e--; - c *= 2; - } - if (e + eBias >= 1) { - value += rt / c; - } else { - value += rt * Math.pow(2, 1 - eBias); - } - if (value * c >= 2) { - e++; - c /= 2; - } - - if (e + eBias >= eMax) { - m = 0; - e = eMax; - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen); - e = e + eBias; - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); - e = 0; - } - } + function write$1(buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - e = (e << mLen) | m; - eLen += mLen; - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - buffer[offset + i - d] |= s * 128; + buffer[offset + i - d] |= s * 128; } var toString = {}.toString; - var isArray$2 = Array.isArray || function (arr) { - return toString.call(arr) == '[object Array]'; - }; + var isArray$3 = + Array.isArray || + function (arr) { + return toString.call(arr) == "[object Array]"; + }; /*! * The buffer module from node.js, for the browser. @@ -3249,7 +4096,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; */ /* eslint-disable no-proto */ - var INSPECT_MAX_BYTES = 50; /** @@ -3276,38 +4122,34 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ - Buffer$1.TYPED_ARRAY_SUPPORT = global$1.TYPED_ARRAY_SUPPORT !== undefined - ? global$1.TYPED_ARRAY_SUPPORT - : true; + Buffer.TYPED_ARRAY_SUPPORT = global$3.TYPED_ARRAY_SUPPORT !== undefined ? global$3.TYPED_ARRAY_SUPPORT : true; /* * Export kMaxLength after typed array support is determined. */ - kMaxLength(); + var _kMaxLength = kMaxLength(); - function kMaxLength () { - return Buffer$1.TYPED_ARRAY_SUPPORT - ? 0x7fffffff - : 0x3fffffff + function kMaxLength() { + return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff; } - function createBuffer (that, length) { - if (kMaxLength() < length) { - throw new RangeError('Invalid typed array length') - } - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = new Uint8Array(length); - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - if (that === null) { - that = new Buffer$1(length); - } - that.length = length; - } + function createBuffer(that, length) { + if (kMaxLength() < length) { + throw new RangeError("Invalid typed array length"); + } + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = new Uint8Array(length); + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + if (that === null) { + that = new Buffer(length); + } + that.length = length; + } - return that + return that; } /** @@ -3320,45 +4162,43 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * The `Uint8Array` prototype remains unmodified. */ - function Buffer$1 (arg, encodingOrOffset, length) { - if (!Buffer$1.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer$1)) { - return new Buffer$1(arg, encodingOrOffset, length) - } + function Buffer(arg, encodingOrOffset, length) { + if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { + return new Buffer(arg, encodingOrOffset, length); + } - // Common case. - if (typeof arg === 'number') { - if (typeof encodingOrOffset === 'string') { - throw new Error( - 'If encoding is specified then the first argument must be a string' - ) - } - return allocUnsafe(this, arg) - } - return from(this, arg, encodingOrOffset, length) + // Common case. + if (typeof arg === "number") { + if (typeof encodingOrOffset === "string") { + throw new Error("If encoding is specified then the first argument must be a string"); + } + return allocUnsafe(this, arg); + } + return from(this, arg, encodingOrOffset, length); } - Buffer$1.poolSize = 8192; // not used by this implementation + Buffer.poolSize = 8192; // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. - Buffer$1._augment = function (arr) { - arr.__proto__ = Buffer$1.prototype; - return arr + Buffer._augment = function (arr) { + arr.__proto__ = Buffer.prototype; + return arr; }; - function from (that, value, encodingOrOffset, length) { - if (typeof value === 'number') { - throw new TypeError('"value" argument must not be a number') - } + function from(that, value, encodingOrOffset, length) { + if (typeof value === "number") { + throw new TypeError('"value" argument must not be a number'); + } - if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { - return fromArrayBuffer(that, value, encodingOrOffset, length) - } + if (typeof ArrayBuffer !== "undefined" && value instanceof ArrayBuffer) { + return fromArrayBuffer(that, value, encodingOrOffset, length); + } - if (typeof value === 'string') { - return fromString(that, value, encodingOrOffset) - } + if (typeof value === "string") { + return fromString(that, value, encodingOrOffset); + } - return fromObject(that, value) + return fromObject(that, value); } /** @@ -3369,494 +4209,496 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ - Buffer$1.from = function (value, encodingOrOffset, length) { - return from(null, value, encodingOrOffset, length) + Buffer.from = function (value, encodingOrOffset, length) { + return from(null, value, encodingOrOffset, length); }; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - Buffer$1.prototype.__proto__ = Uint8Array.prototype; - Buffer$1.__proto__ = Uint8Array; - if (typeof Symbol !== 'undefined' && Symbol.species && - Buffer$1[Symbol.species] === Buffer$1) ; + if (Buffer.TYPED_ARRAY_SUPPORT) { + Buffer.prototype.__proto__ = Uint8Array.prototype; + Buffer.__proto__ = Uint8Array; + if (typeof Symbol !== "undefined" && Symbol.species && Buffer[Symbol.species] === Buffer); } - function assertSize (size) { - if (typeof size !== 'number') { - throw new TypeError('"size" argument must be a number') - } else if (size < 0) { - throw new RangeError('"size" argument must not be negative') - } + function assertSize(size) { + if (typeof size !== "number") { + throw new TypeError('"size" argument must be a number'); + } else if (size < 0) { + throw new RangeError('"size" argument must not be negative'); + } } - function alloc (that, size, fill, encoding) { - assertSize(size); - if (size <= 0) { - return createBuffer(that, size) - } - if (fill !== undefined) { - // Only pay attention to encoding if it's a string. This - // prevents accidentally sending in a number that would - // be interpretted as a start offset. - return typeof encoding === 'string' - ? createBuffer(that, size).fill(fill, encoding) - : createBuffer(that, size).fill(fill) - } - return createBuffer(that, size) + function alloc(that, size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(that, size); + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpretted as a start offset. + return typeof encoding === "string" ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill); + } + return createBuffer(that, size); } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ - Buffer$1.alloc = function (size, fill, encoding) { - return alloc(null, size, fill, encoding) + Buffer.alloc = function (size, fill, encoding) { + return alloc(null, size, fill, encoding); }; - function allocUnsafe (that, size) { - assertSize(size); - that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) { - for (var i = 0; i < size; ++i) { - that[i] = 0; - } - } - return that + function allocUnsafe(that, size) { + assertSize(size); + that = createBuffer(that, size < 0 ? 0 : checked(size) | 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) { + for (var i = 0; i < size; ++i) { + that[i] = 0; + } + } + return that; } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ - Buffer$1.allocUnsafe = function (size) { - return allocUnsafe(null, size) + Buffer.allocUnsafe = function (size) { + return allocUnsafe(null, size); }; /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ - Buffer$1.allocUnsafeSlow = function (size) { - return allocUnsafe(null, size) + Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(null, size); }; - function fromString (that, string, encoding) { - if (typeof encoding !== 'string' || encoding === '') { - encoding = 'utf8'; - } + function fromString(that, string, encoding) { + if (typeof encoding !== "string" || encoding === "") { + encoding = "utf8"; + } - if (!Buffer$1.isEncoding(encoding)) { - throw new TypeError('"encoding" must be a valid string encoding') - } + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('"encoding" must be a valid string encoding'); + } - var length = byteLength(string, encoding) | 0; - that = createBuffer(that, length); + var length = byteLength(string, encoding) | 0; + that = createBuffer(that, length); - var actual = that.write(string, encoding); + var actual = that.write(string, encoding); - if (actual !== length) { - // Writing a hex string, for example, that contains invalid characters will - // cause everything after the first invalid character to be ignored. (e.g. - // 'abxxcd' will be treated as 'ab') - that = that.slice(0, actual); - } + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + that = that.slice(0, actual); + } - return that + return that; } - function fromArrayLike (that, array) { - var length = array.length < 0 ? 0 : checked(array.length) | 0; - that = createBuffer(that, length); - for (var i = 0; i < length; i += 1) { - that[i] = array[i] & 255; - } - return that + function fromArrayLike(that, array) { + var length = array.length < 0 ? 0 : checked(array.length) | 0; + that = createBuffer(that, length); + for (var i = 0; i < length; i += 1) { + that[i] = array[i] & 255; + } + return that; } - function fromArrayBuffer (that, array, byteOffset, length) { - array.byteLength; // this throws if `array` is not a valid ArrayBuffer + function fromArrayBuffer(that, array, byteOffset, length) { + array.byteLength; // this throws if `array` is not a valid ArrayBuffer - if (byteOffset < 0 || array.byteLength < byteOffset) { - throw new RangeError('\'offset\' is out of bounds') - } + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError("'offset' is out of bounds"); + } - if (array.byteLength < byteOffset + (length || 0)) { - throw new RangeError('\'length\' is out of bounds') - } + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError("'length' is out of bounds"); + } - if (byteOffset === undefined && length === undefined) { - array = new Uint8Array(array); - } else if (length === undefined) { - array = new Uint8Array(array, byteOffset); - } else { - array = new Uint8Array(array, byteOffset, length); - } + if (byteOffset === undefined && length === undefined) { + array = new Uint8Array(array); + } else if (length === undefined) { + array = new Uint8Array(array, byteOffset); + } else { + array = new Uint8Array(array, byteOffset, length); + } - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - // Return an augmented `Uint8Array` instance, for best performance - that = array; - that.__proto__ = Buffer$1.prototype; - } else { - // Fallback: Return an object instance of the Buffer class - that = fromArrayLike(that, array); - } - return that + if (Buffer.TYPED_ARRAY_SUPPORT) { + // Return an augmented `Uint8Array` instance, for best performance + that = array; + that.__proto__ = Buffer.prototype; + } else { + // Fallback: Return an object instance of the Buffer class + that = fromArrayLike(that, array); + } + return that; } - function fromObject (that, obj) { - if (internalIsBuffer(obj)) { - var len = checked(obj.length) | 0; - that = createBuffer(that, len); + function fromObject(that, obj) { + if (internalIsBuffer(obj)) { + var len = checked(obj.length) | 0; + that = createBuffer(that, len); - if (that.length === 0) { - return that - } + if (that.length === 0) { + return that; + } - obj.copy(that, 0, 0, len); - return that - } + obj.copy(that, 0, 0, len); + return that; + } - if (obj) { - if ((typeof ArrayBuffer !== 'undefined' && - obj.buffer instanceof ArrayBuffer) || 'length' in obj) { - if (typeof obj.length !== 'number' || isnan(obj.length)) { - return createBuffer(that, 0) - } - return fromArrayLike(that, obj) - } + if (obj) { + if ((typeof ArrayBuffer !== "undefined" && obj.buffer instanceof ArrayBuffer) || "length" in obj) { + if (typeof obj.length !== "number" || isnan(obj.length)) { + return createBuffer(that, 0); + } + return fromArrayLike(that, obj); + } - if (obj.type === 'Buffer' && isArray$2(obj.data)) { - return fromArrayLike(that, obj.data) - } - } + if (obj.type === "Buffer" && isArray$3(obj.data)) { + return fromArrayLike(that, obj.data); + } + } - throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') + throw new TypeError("First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object."); } - function checked (length) { - // Note: cannot use `length < kMaxLength()` here because that fails when - // length is NaN (which is otherwise coerced to zero.) - if (length >= kMaxLength()) { - throw new RangeError('Attempt to allocate Buffer larger than maximum ' + - 'size: 0x' + kMaxLength().toString(16) + ' bytes') - } - return length | 0 + function checked(length) { + // Note: cannot use `length < kMaxLength()` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= kMaxLength()) { + throw new RangeError("Attempt to allocate Buffer larger than maximum " + "size: 0x" + kMaxLength().toString(16) + " bytes"); + } + return length | 0; + } + + function SlowBuffer(length) { + if (+length != length) { + // eslint-disable-line eqeqeq + length = 0; + } + return Buffer.alloc(+length); } - Buffer$1.isBuffer = isBuffer$1; - function internalIsBuffer (b) { - return !!(b != null && b._isBuffer) + Buffer.isBuffer = isBuffer$2; + function internalIsBuffer(b) { + return !!(b != null && b._isBuffer); } - Buffer$1.compare = function compare (a, b) { - if (!internalIsBuffer(a) || !internalIsBuffer(b)) { - throw new TypeError('Arguments must be Buffers') - } + Buffer.compare = function compare(a, b) { + if (!internalIsBuffer(a) || !internalIsBuffer(b)) { + throw new TypeError("Arguments must be Buffers"); + } - if (a === b) return 0 + if (a === b) return 0; - var x = a.length; - var y = b.length; + var x = a.length; + var y = b.length; - for (var i = 0, len = Math.min(x, y); i < len; ++i) { - if (a[i] !== b[i]) { - x = a[i]; - y = b[i]; - break - } - } + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } - if (x < y) return -1 - if (y < x) return 1 - return 0 + if (x < y) return -1; + if (y < x) return 1; + return 0; }; - Buffer$1.isEncoding = function isEncoding (encoding) { - switch (String(encoding).toLowerCase()) { - case 'hex': - case 'utf8': - case 'utf-8': - case 'ascii': - case 'latin1': - case 'binary': - case 'base64': - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return true - default: - return false - } + Buffer.isEncoding = function isEncoding(encoding) { + switch (String(encoding).toLowerCase()) { + case "hex": + case "utf8": + case "utf-8": + case "ascii": + case "latin1": + case "binary": + case "base64": + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return true; + default: + return false; + } }; - Buffer$1.concat = function concat (list, length) { - if (!isArray$2(list)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } + Buffer.concat = function concat(list, length) { + if (!isArray$3(list)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } - if (list.length === 0) { - return Buffer$1.alloc(0) - } + if (list.length === 0) { + return Buffer.alloc(0); + } - var i; - if (length === undefined) { - length = 0; - for (i = 0; i < list.length; ++i) { - length += list[i].length; - } - } + var i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } - var buffer = Buffer$1.allocUnsafe(length); - var pos = 0; - for (i = 0; i < list.length; ++i) { - var buf = list[i]; - if (!internalIsBuffer(buf)) { - throw new TypeError('"list" argument must be an Array of Buffers') - } - buf.copy(buffer, pos); - pos += buf.length; - } - return buffer + var buffer = Buffer.allocUnsafe(length); + var pos = 0; + for (i = 0; i < list.length; ++i) { + var buf = list[i]; + if (!internalIsBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers'); + } + buf.copy(buffer, pos); + pos += buf.length; + } + return buffer; }; - function byteLength (string, encoding) { - if (internalIsBuffer(string)) { - return string.length - } - if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && - (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { - return string.byteLength - } - if (typeof string !== 'string') { - string = '' + string; - } - - var len = string.length; - if (len === 0) return 0 + function byteLength(string, encoding) { + if (internalIsBuffer(string)) { + return string.length; + } + if (typeof ArrayBuffer !== "undefined" && typeof ArrayBuffer.isView === "function" && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { + return string.byteLength; + } + if (typeof string !== "string") { + string = "" + string; + } - // Use a for loop to avoid recursion - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'ascii': - case 'latin1': - case 'binary': - return len - case 'utf8': - case 'utf-8': - case undefined: - return utf8ToBytes(string).length - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return len * 2 - case 'hex': - return len >>> 1 - case 'base64': - return base64ToBytes(string).length - default: - if (loweredCase) return utf8ToBytes(string).length // assume utf8 - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } + var len = string.length; + if (len === 0) return 0; + + // Use a for loop to avoid recursion + var loweredCase = false; + for (;;) { + switch (encoding) { + case "ascii": + case "latin1": + case "binary": + return len; + case "utf8": + case "utf-8": + case undefined: + return utf8ToBytes(string).length; + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return len * 2; + case "hex": + return len >>> 1; + case "base64": + return base64ToBytes(string).length; + default: + if (loweredCase) return utf8ToBytes(string).length; // assume utf8 + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } } - Buffer$1.byteLength = byteLength; + Buffer.byteLength = byteLength; - function slowToString (encoding, start, end) { - var loweredCase = false; + function slowToString(encoding, start, end) { + var loweredCase = false; - // No need to verify that "this.length <= MAX_UINT32" since it's a read-only - // property of a typed array. + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. - // This behaves neither like String nor Uint8Array in that we set start/end - // to their upper/lower bounds if the value passed is out of range. - // undefined is handled specially as per ECMA-262 6th Edition, - // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. - if (start === undefined || start < 0) { - start = 0; - } - // Return early if start > this.length. Done here to prevent potential uint32 - // coercion fail below. - if (start > this.length) { - return '' - } + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return ""; + } - if (end === undefined || end > this.length) { - end = this.length; - } + if (end === undefined || end > this.length) { + end = this.length; + } - if (end <= 0) { - return '' - } + if (end <= 0) { + return ""; + } - // Force coersion to uint32. This will also coerce falsey/NaN values to 0. - end >>>= 0; - start >>>= 0; + // Force coersion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; - if (end <= start) { - return '' - } + if (end <= start) { + return ""; + } - if (!encoding) encoding = 'utf8'; + if (!encoding) encoding = "utf8"; - while (true) { - switch (encoding) { - case 'hex': - return hexSlice(this, start, end) + while (true) { + switch (encoding) { + case "hex": + return hexSlice(this, start, end); - case 'utf8': - case 'utf-8': - return utf8Slice(this, start, end) + case "utf8": + case "utf-8": + return utf8Slice(this, start, end); - case 'ascii': - return asciiSlice(this, start, end) + case "ascii": + return asciiSlice(this, start, end); - case 'latin1': - case 'binary': - return latin1Slice(this, start, end) + case "latin1": + case "binary": + return latin1Slice(this, start, end); - case 'base64': - return base64Slice(this, start, end) + case "base64": + return base64Slice(this, start, end); - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return utf16leSlice(this, start, end) + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return utf16leSlice(this, start, end); - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = (encoding + '').toLowerCase(); - loweredCase = true; - } - } + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); + encoding = (encoding + "").toLowerCase(); + loweredCase = true; + } + } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. - Buffer$1.prototype._isBuffer = true; + Buffer.prototype._isBuffer = true; - function swap (b, n, m) { - var i = b[n]; - b[n] = b[m]; - b[m] = i; + function swap(b, n, m) { + var i = b[n]; + b[n] = b[m]; + b[m] = i; } - Buffer$1.prototype.swap16 = function swap16 () { - var len = this.length; - if (len % 2 !== 0) { - throw new RangeError('Buffer size must be a multiple of 16-bits') - } - for (var i = 0; i < len; i += 2) { - swap(this, i, i + 1); - } - return this + Buffer.prototype.swap16 = function swap16() { + var len = this.length; + if (len % 2 !== 0) { + throw new RangeError("Buffer size must be a multiple of 16-bits"); + } + for (var i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this; }; - Buffer$1.prototype.swap32 = function swap32 () { - var len = this.length; - if (len % 4 !== 0) { - throw new RangeError('Buffer size must be a multiple of 32-bits') - } - for (var i = 0; i < len; i += 4) { - swap(this, i, i + 3); - swap(this, i + 1, i + 2); - } - return this + Buffer.prototype.swap32 = function swap32() { + var len = this.length; + if (len % 4 !== 0) { + throw new RangeError("Buffer size must be a multiple of 32-bits"); + } + for (var i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this; }; - Buffer$1.prototype.swap64 = function swap64 () { - var len = this.length; - if (len % 8 !== 0) { - throw new RangeError('Buffer size must be a multiple of 64-bits') - } - for (var i = 0; i < len; i += 8) { - swap(this, i, i + 7); - swap(this, i + 1, i + 6); - swap(this, i + 2, i + 5); - swap(this, i + 3, i + 4); - } - return this + Buffer.prototype.swap64 = function swap64() { + var len = this.length; + if (len % 8 !== 0) { + throw new RangeError("Buffer size must be a multiple of 64-bits"); + } + for (var i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this; }; - Buffer$1.prototype.toString = function toString () { - var length = this.length | 0; - if (length === 0) return '' - if (arguments.length === 0) return utf8Slice(this, 0, length) - return slowToString.apply(this, arguments) + Buffer.prototype.toString = function toString() { + var length = this.length | 0; + if (length === 0) return ""; + if (arguments.length === 0) return utf8Slice(this, 0, length); + return slowToString.apply(this, arguments); }; - Buffer$1.prototype.equals = function equals (b) { - if (!internalIsBuffer(b)) throw new TypeError('Argument must be a Buffer') - if (this === b) return true - return Buffer$1.compare(this, b) === 0 + Buffer.prototype.equals = function equals(b) { + if (!internalIsBuffer(b)) throw new TypeError("Argument must be a Buffer"); + if (this === b) return true; + return Buffer.compare(this, b) === 0; }; - Buffer$1.prototype.inspect = function inspect () { - var str = ''; - var max = INSPECT_MAX_BYTES; - if (this.length > 0) { - str = this.toString('hex', 0, max).match(/.{2}/g).join(' '); - if (this.length > max) str += ' ... '; - } - return '' + Buffer.prototype.inspect = function inspect() { + var str = ""; + var max = INSPECT_MAX_BYTES; + if (this.length > 0) { + str = this.toString("hex", 0, max).match(/.{2}/g).join(" "); + if (this.length > max) str += " ... "; + } + return ""; }; - Buffer$1.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { - if (!internalIsBuffer(target)) { - throw new TypeError('Argument must be a Buffer') - } + Buffer.prototype.compare = function compare(target, start, end, thisStart, thisEnd) { + if (!internalIsBuffer(target)) { + throw new TypeError("Argument must be a Buffer"); + } - if (start === undefined) { - start = 0; - } - if (end === undefined) { - end = target ? target.length : 0; - } - if (thisStart === undefined) { - thisStart = 0; - } - if (thisEnd === undefined) { - thisEnd = this.length; - } + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } - if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { - throw new RangeError('out of range index') - } + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError("out of range index"); + } - if (thisStart >= thisEnd && start >= end) { - return 0 - } - if (thisStart >= thisEnd) { - return -1 - } - if (start >= end) { - return 1 - } + if (thisStart >= thisEnd && start >= end) { + return 0; + } + if (thisStart >= thisEnd) { + return -1; + } + if (start >= end) { + return 1; + } - start >>>= 0; - end >>>= 0; - thisStart >>>= 0; - thisEnd >>>= 0; + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; - if (this === target) return 0 + if (this === target) return 0; - var x = thisEnd - thisStart; - var y = end - start; - var len = Math.min(x, y); + var x = thisEnd - thisStart; + var y = end - start; + var len = Math.min(x, y); - var thisCopy = this.slice(thisStart, thisEnd); - var targetCopy = target.slice(start, end); + var thisCopy = this.slice(thisStart, thisEnd); + var targetCopy = target.slice(start, end); - for (var i = 0; i < len; ++i) { - if (thisCopy[i] !== targetCopy[i]) { - x = thisCopy[i]; - y = targetCopy[i]; - break - } - } + for (var i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break; + } + } - if (x < y) return -1 - if (y < x) return 1 - return 0 + if (x < y) return -1; + if (y < x) return 1; + return 0; }; // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, @@ -3868,336 +4710,329 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf - function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { - // Empty buffer means no match - if (buffer.length === 0) return -1 - - // Normalize byteOffset - if (typeof byteOffset === 'string') { - encoding = byteOffset; - byteOffset = 0; - } else if (byteOffset > 0x7fffffff) { - byteOffset = 0x7fffffff; - } else if (byteOffset < -0x80000000) { - byteOffset = -0x80000000; - } - byteOffset = +byteOffset; // Coerce to Number. - if (isNaN(byteOffset)) { - // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer - byteOffset = dir ? 0 : (buffer.length - 1); - } - - // Normalize byteOffset: negative offsets start from the end of the buffer - if (byteOffset < 0) byteOffset = buffer.length + byteOffset; - if (byteOffset >= buffer.length) { - if (dir) return -1 - else byteOffset = buffer.length - 1; - } else if (byteOffset < 0) { - if (dir) byteOffset = 0; - else return -1 - } - - // Normalize val - if (typeof val === 'string') { - val = Buffer$1.from(val, encoding); - } - - // Finally, search either indexOf (if dir is true) or lastIndexOf - if (internalIsBuffer(val)) { - // Special case: looking for empty string/buffer always fails - if (val.length === 0) { - return -1 - } - return arrayIndexOf(buffer, val, byteOffset, encoding, dir) - } else if (typeof val === 'number') { - val = val & 0xFF; // Search for a byte value [0-255] - if (Buffer$1.TYPED_ARRAY_SUPPORT && - typeof Uint8Array.prototype.indexOf === 'function') { - if (dir) { - return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) - } else { - return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) - } - } - return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) - } + function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1; + + // Normalize byteOffset + if (typeof byteOffset === "string") { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -0x80000000) { + byteOffset = -0x80000000; + } + byteOffset = +byteOffset; // Coerce to Number. + if (isNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : buffer.length - 1; + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1; + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1; + } + + // Normalize val + if (typeof val === "string") { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (internalIsBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1; + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir); + } else if (typeof val === "number") { + val = val & 0xff; // Search for a byte value [0-255] + if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === "function") { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset); + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset); + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir); + } - throw new TypeError('val must be string, number or Buffer') + throw new TypeError("val must be string, number or Buffer"); } - function arrayIndexOf (arr, val, byteOffset, encoding, dir) { - var indexSize = 1; - var arrLength = arr.length; - var valLength = val.length; + function arrayIndexOf(arr, val, byteOffset, encoding, dir) { + var indexSize = 1; + var arrLength = arr.length; + var valLength = val.length; - if (encoding !== undefined) { - encoding = String(encoding).toLowerCase(); - if (encoding === 'ucs2' || encoding === 'ucs-2' || - encoding === 'utf16le' || encoding === 'utf-16le') { - if (arr.length < 2 || val.length < 2) { - return -1 - } - indexSize = 2; - arrLength /= 2; - valLength /= 2; - byteOffset /= 2; - } - } + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === "ucs2" || encoding === "ucs-2" || encoding === "utf16le" || encoding === "utf-16le") { + if (arr.length < 2 || val.length < 2) { + return -1; + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } - function read (buf, i) { - if (indexSize === 1) { - return buf[i] - } else { - return buf.readUInt16BE(i * indexSize) - } - } + function read(buf, i) { + if (indexSize === 1) { + return buf[i]; + } else { + return buf.readUInt16BE(i * indexSize); + } + } - var i; - if (dir) { - var foundIndex = -1; - for (i = byteOffset; i < arrLength; i++) { - if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { - if (foundIndex === -1) foundIndex = i; - if (i - foundIndex + 1 === valLength) return foundIndex * indexSize - } else { - if (foundIndex !== -1) i -= i - foundIndex; - foundIndex = -1; - } - } - } else { - if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; - for (i = byteOffset; i >= 0; i--) { - var found = true; - for (var j = 0; j < valLength; j++) { - if (read(arr, i + j) !== read(val, j)) { - found = false; - break - } - } - if (found) return i - } - } + var i; + if (dir) { + var foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize; + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + var found = true; + for (var j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break; + } + } + if (found) return i; + } + } - return -1 + return -1; } - Buffer$1.prototype.includes = function includes (val, byteOffset, encoding) { - return this.indexOf(val, byteOffset, encoding) !== -1 + Buffer.prototype.includes = function includes(val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1; }; - Buffer$1.prototype.indexOf = function indexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, true) + Buffer.prototype.indexOf = function indexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true); }; - Buffer$1.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { - return bidirectionalIndexOf(this, val, byteOffset, encoding, false) + Buffer.prototype.lastIndexOf = function lastIndexOf(val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false); }; - function hexWrite (buf, string, offset, length) { - offset = Number(offset) || 0; - var remaining = buf.length - offset; - if (!length) { - length = remaining; - } else { - length = Number(length); - if (length > remaining) { - length = remaining; - } - } + function hexWrite(buf, string, offset, length) { + offset = Number(offset) || 0; + var remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } - // must be an even number of digits - var strLen = string.length; - if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') + // must be an even number of digits + var strLen = string.length; + if (strLen % 2 !== 0) throw new TypeError("Invalid hex string"); - if (length > strLen / 2) { - length = strLen / 2; - } - for (var i = 0; i < length; ++i) { - var parsed = parseInt(string.substr(i * 2, 2), 16); - if (isNaN(parsed)) return i - buf[offset + i] = parsed; - } - return i + if (length > strLen / 2) { + length = strLen / 2; + } + for (var i = 0; i < length; ++i) { + var parsed = parseInt(string.substr(i * 2, 2), 16); + if (isNaN(parsed)) return i; + buf[offset + i] = parsed; + } + return i; } - function utf8Write (buf, string, offset, length) { - return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) + function utf8Write(buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length); } - function asciiWrite (buf, string, offset, length) { - return blitBuffer(asciiToBytes(string), buf, offset, length) + function asciiWrite(buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length); } - function latin1Write (buf, string, offset, length) { - return asciiWrite(buf, string, offset, length) + function latin1Write(buf, string, offset, length) { + return asciiWrite(buf, string, offset, length); } - function base64Write (buf, string, offset, length) { - return blitBuffer(base64ToBytes(string), buf, offset, length) + function base64Write(buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length); } - function ucs2Write (buf, string, offset, length) { - return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) + function ucs2Write(buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length); } - Buffer$1.prototype.write = function write (string, offset, length, encoding) { - // Buffer#write(string) - if (offset === undefined) { - encoding = 'utf8'; - length = this.length; - offset = 0; - // Buffer#write(string, encoding) - } else if (length === undefined && typeof offset === 'string') { - encoding = offset; - length = this.length; - offset = 0; - // Buffer#write(string, offset[, length][, encoding]) - } else if (isFinite(offset)) { - offset = offset | 0; - if (isFinite(length)) { - length = length | 0; - if (encoding === undefined) encoding = 'utf8'; - } else { - encoding = length; - length = undefined; - } - // legacy write(string, encoding, offset, length) - remove in v0.13 - } else { - throw new Error( - 'Buffer.write(string, encoding, offset[, length]) is no longer supported' - ) - } + Buffer.prototype.write = function write(string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = "utf8"; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === "string") { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset | 0; + if (isFinite(length)) { + length = length | 0; + if (encoding === undefined) encoding = "utf8"; + } else { + encoding = length; + length = undefined; + } + // legacy write(string, encoding, offset, length) - remove in v0.13 + } else { + throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported"); + } - var remaining = this.length - offset; - if (length === undefined || length > remaining) length = remaining; + var remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; - if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { - throw new RangeError('Attempt to write outside buffer bounds') - } + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError("Attempt to write outside buffer bounds"); + } - if (!encoding) encoding = 'utf8'; + if (!encoding) encoding = "utf8"; - var loweredCase = false; - for (;;) { - switch (encoding) { - case 'hex': - return hexWrite(this, string, offset, length) + var loweredCase = false; + for (;;) { + switch (encoding) { + case "hex": + return hexWrite(this, string, offset, length); - case 'utf8': - case 'utf-8': - return utf8Write(this, string, offset, length) + case "utf8": + case "utf-8": + return utf8Write(this, string, offset, length); - case 'ascii': - return asciiWrite(this, string, offset, length) + case "ascii": + return asciiWrite(this, string, offset, length); - case 'latin1': - case 'binary': - return latin1Write(this, string, offset, length) + case "latin1": + case "binary": + return latin1Write(this, string, offset, length); - case 'base64': - // Warning: maxLength not taken into account in base64Write - return base64Write(this, string, offset, length) + case "base64": + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length); - case 'ucs2': - case 'ucs-2': - case 'utf16le': - case 'utf-16le': - return ucs2Write(this, string, offset, length) + case "ucs2": + case "ucs-2": + case "utf16le": + case "utf-16le": + return ucs2Write(this, string, offset, length); - default: - if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) - encoding = ('' + encoding).toLowerCase(); - loweredCase = true; - } - } + default: + if (loweredCase) throw new TypeError("Unknown encoding: " + encoding); + encoding = ("" + encoding).toLowerCase(); + loweredCase = true; + } + } }; - Buffer$1.prototype.toJSON = function toJSON () { - return { - type: 'Buffer', - data: Array.prototype.slice.call(this._arr || this, 0) - } + Buffer.prototype.toJSON = function toJSON() { + return { + type: "Buffer", + data: Array.prototype.slice.call(this._arr || this, 0), + }; }; - function base64Slice (buf, start, end) { - if (start === 0 && end === buf.length) { - return fromByteArray(buf) - } else { - return fromByteArray(buf.slice(start, end)) - } + function base64Slice(buf, start, end) { + if (start === 0 && end === buf.length) { + return fromByteArray(buf); + } else { + return fromByteArray(buf.slice(start, end)); + } } - function utf8Slice (buf, start, end) { - end = Math.min(buf.length, end); - var res = []; - - var i = start; - while (i < end) { - var firstByte = buf[i]; - var codePoint = null; - var bytesPerSequence = (firstByte > 0xEF) ? 4 - : (firstByte > 0xDF) ? 3 - : (firstByte > 0xBF) ? 2 - : 1; - - if (i + bytesPerSequence <= end) { - var secondByte, thirdByte, fourthByte, tempCodePoint; - - switch (bytesPerSequence) { - case 1: - if (firstByte < 0x80) { - codePoint = firstByte; - } - break - case 2: - secondByte = buf[i + 1]; - if ((secondByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); - if (tempCodePoint > 0x7F) { - codePoint = tempCodePoint; - } - } - break - case 3: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); - if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { - codePoint = tempCodePoint; - } - } - break - case 4: - secondByte = buf[i + 1]; - thirdByte = buf[i + 2]; - fourthByte = buf[i + 3]; - if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { - tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); - if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { - codePoint = tempCodePoint; - } - } - } - } - - if (codePoint === null) { - // we did not generate a valid codePoint so insert a - // replacement char (U+FFFD) and advance only 1 byte - codePoint = 0xFFFD; - bytesPerSequence = 1; - } else if (codePoint > 0xFFFF) { - // encode to utf16 (surrogate pair dance) - codePoint -= 0x10000; - res.push(codePoint >>> 10 & 0x3FF | 0xD800); - codePoint = 0xDC00 | codePoint & 0x3FF; - } - - res.push(codePoint); - i += bytesPerSequence; - } + function utf8Slice(buf, start, end) { + end = Math.min(buf.length, end); + var res = []; + + var i = start; + while (i < end) { + var firstByte = buf[i]; + var codePoint = null; + var bytesPerSequence = firstByte > 0xef ? 4 : firstByte > 0xdf ? 3 : firstByte > 0xbf ? 2 : 1; + + if (i + bytesPerSequence <= end) { + var secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break; + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xc0) === 0x80) { + tempCodePoint = ((firstByte & 0x1f) << 0x6) | (secondByte & 0x3f); + if (tempCodePoint > 0x7f) { + codePoint = tempCodePoint; + } + } + break; + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80) { + tempCodePoint = ((firstByte & 0xf) << 0xc) | ((secondByte & 0x3f) << 0x6) | (thirdByte & 0x3f); + if (tempCodePoint > 0x7ff && (tempCodePoint < 0xd800 || tempCodePoint > 0xdfff)) { + codePoint = tempCodePoint; + } + } + break; + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xc0) === 0x80 && (thirdByte & 0xc0) === 0x80 && (fourthByte & 0xc0) === 0x80) { + tempCodePoint = ((firstByte & 0xf) << 0x12) | ((secondByte & 0x3f) << 0xc) | ((thirdByte & 0x3f) << 0x6) | (fourthByte & 0x3f); + if (tempCodePoint > 0xffff && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xfffd; + bytesPerSequence = 1; + } else if (codePoint > 0xffff) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(((codePoint >>> 10) & 0x3ff) | 0xd800); + codePoint = 0xdc00 | (codePoint & 0x3ff); + } + + res.push(codePoint); + i += bytesPerSequence; + } - return decodeCodePointsArray(res) + return decodeCodePointsArray(res); } // Based on http://stackoverflow.com/a/22747272/680742, the browser with @@ -4205,650 +5040,628 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000; - function decodeCodePointsArray (codePoints) { - var len = codePoints.length; - if (len <= MAX_ARGUMENTS_LENGTH) { - return String.fromCharCode.apply(String, codePoints) // avoid extra slice() - } + function decodeCodePointsArray(codePoints) { + var len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints); // avoid extra slice() + } - // Decode in chunks to avoid "call stack size exceeded". - var res = ''; - var i = 0; - while (i < len) { - res += String.fromCharCode.apply( - String, - codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) - ); - } - return res + // Decode in chunks to avoid "call stack size exceeded". + var res = ""; + var i = 0; + while (i < len) { + res += String.fromCharCode.apply(String, codePoints.slice(i, (i += MAX_ARGUMENTS_LENGTH))); + } + return res; } - function asciiSlice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); + function asciiSlice(buf, start, end) { + var ret = ""; + end = Math.min(buf.length, end); - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i] & 0x7F); - } - return ret + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7f); + } + return ret; } - function latin1Slice (buf, start, end) { - var ret = ''; - end = Math.min(buf.length, end); + function latin1Slice(buf, start, end) { + var ret = ""; + end = Math.min(buf.length, end); - for (var i = start; i < end; ++i) { - ret += String.fromCharCode(buf[i]); - } - return ret + for (var i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret; } - function hexSlice (buf, start, end) { - var len = buf.length; + function hexSlice(buf, start, end) { + var len = buf.length; - if (!start || start < 0) start = 0; - if (!end || end < 0 || end > len) end = len; + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; - var out = ''; - for (var i = start; i < end; ++i) { - out += toHex(buf[i]); - } - return out + var out = ""; + for (var i = start; i < end; ++i) { + out += toHex(buf[i]); + } + return out; } - function utf16leSlice (buf, start, end) { - var bytes = buf.slice(start, end); - var res = ''; - for (var i = 0; i < bytes.length; i += 2) { - res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); - } - return res + function utf16leSlice(buf, start, end) { + var bytes = buf.slice(start, end); + var res = ""; + for (var i = 0; i < bytes.length; i += 2) { + res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256); + } + return res; } - Buffer$1.prototype.slice = function slice (start, end) { - var len = this.length; - start = ~~start; - end = end === undefined ? len : ~~end; + Buffer.prototype.slice = function slice(start, end) { + var len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; - if (start < 0) { - start += len; - if (start < 0) start = 0; - } else if (start > len) { - start = len; - } - - if (end < 0) { - end += len; - if (end < 0) end = 0; - } else if (end > len) { - end = len; - } + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } - if (end < start) end = start; + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } - var newBuf; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - newBuf = this.subarray(start, end); - newBuf.__proto__ = Buffer$1.prototype; - } else { - var sliceLen = end - start; - newBuf = new Buffer$1(sliceLen, undefined); - for (var i = 0; i < sliceLen; ++i) { - newBuf[i] = this[i + start]; - } - } + if (end < start) end = start; + + var newBuf; + if (Buffer.TYPED_ARRAY_SUPPORT) { + newBuf = this.subarray(start, end); + newBuf.__proto__ = Buffer.prototype; + } else { + var sliceLen = end - start; + newBuf = new Buffer(sliceLen, undefined); + for (var i = 0; i < sliceLen; ++i) { + newBuf[i] = this[i + start]; + } + } - return newBuf + return newBuf; }; /* * Need to make sure that buffer isn't trying to write out of bounds. */ - function checkOffset (offset, ext, length) { - if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') - if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') + function checkOffset(offset, ext, length) { + if (offset % 1 !== 0 || offset < 0) throw new RangeError("offset is not uint"); + if (offset + ext > length) throw new RangeError("Trying to access beyond buffer length"); } - Buffer$1.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + Buffer.prototype.readUIntLE = function readUIntLE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } - return val + return val; }; - Buffer$1.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - checkOffset(offset, byteLength, this.length); - } + Buffer.prototype.readUIntBE = function readUIntBE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } - var val = this[offset + --byteLength]; - var mul = 1; - while (byteLength > 0 && (mul *= 0x100)) { - val += this[offset + --byteLength] * mul; - } + var val = this[offset + --byteLength]; + var mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } - return val + return val; }; - Buffer$1.prototype.readUInt8 = function readUInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - return this[offset] + Buffer.prototype.readUInt8 = function readUInt8(offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset]; }; - Buffer$1.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return this[offset] | (this[offset + 1] << 8) + Buffer.prototype.readUInt16LE = function readUInt16LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8); }; - Buffer$1.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - return (this[offset] << 8) | this[offset + 1] + Buffer.prototype.readUInt16BE = function readUInt16BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1]; }; - Buffer$1.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + Buffer.prototype.readUInt32LE = function readUInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - return ((this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16)) + - (this[offset + 3] * 0x1000000) + return (this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + this[offset + 3] * 0x1000000; }; - Buffer$1.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + Buffer.prototype.readUInt32BE = function readUInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - return (this[offset] * 0x1000000) + - ((this[offset + 1] << 16) | - (this[offset + 2] << 8) | - this[offset + 3]) + return this[offset] * 0x1000000 + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]); }; - Buffer$1.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + Buffer.prototype.readIntLE = function readIntLE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - var val = this[offset]; - var mul = 1; - var i = 0; - while (++i < byteLength && (mul *= 0x100)) { - val += this[offset + i] * mul; - } - mul *= 0x80; + var val = this[offset]; + var mul = 1; + var i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - return val + return val; }; - Buffer$1.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) checkOffset(offset, byteLength, this.length); + Buffer.prototype.readIntBE = function readIntBE(offset, byteLength, noAssert) { + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); - var i = byteLength; - var mul = 1; - var val = this[offset + --i]; - while (i > 0 && (mul *= 0x100)) { - val += this[offset + --i] * mul; - } - mul *= 0x80; + var i = byteLength; + var mul = 1; + var val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; - if (val >= mul) val -= Math.pow(2, 8 * byteLength); + if (val >= mul) val -= Math.pow(2, 8 * byteLength); - return val + return val; }; - Buffer$1.prototype.readInt8 = function readInt8 (offset, noAssert) { - if (!noAssert) checkOffset(offset, 1, this.length); - if (!(this[offset] & 0x80)) return (this[offset]) - return ((0xff - this[offset] + 1) * -1) + Buffer.prototype.readInt8 = function readInt8(offset, noAssert) { + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return this[offset]; + return (0xff - this[offset] + 1) * -1; }; - Buffer$1.prototype.readInt16LE = function readInt16LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset] | (this[offset + 1] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val + Buffer.prototype.readInt16LE = function readInt16LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset] | (this[offset + 1] << 8); + return val & 0x8000 ? val | 0xffff0000 : val; }; - Buffer$1.prototype.readInt16BE = function readInt16BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 2, this.length); - var val = this[offset + 1] | (this[offset] << 8); - return (val & 0x8000) ? val | 0xFFFF0000 : val + Buffer.prototype.readInt16BE = function readInt16BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 2, this.length); + var val = this[offset + 1] | (this[offset] << 8); + return val & 0x8000 ? val | 0xffff0000 : val; }; - Buffer$1.prototype.readInt32LE = function readInt32LE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + Buffer.prototype.readInt32LE = function readInt32LE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - return (this[offset]) | - (this[offset + 1] << 8) | - (this[offset + 2] << 16) | - (this[offset + 3] << 24) + return this[offset] | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24); }; - Buffer$1.prototype.readInt32BE = function readInt32BE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); + Buffer.prototype.readInt32BE = function readInt32BE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); - return (this[offset] << 24) | - (this[offset + 1] << 16) | - (this[offset + 2] << 8) | - (this[offset + 3]) + return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]; }; - Buffer$1.prototype.readFloatLE = function readFloatLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, true, 23, 4) + Buffer.prototype.readFloatLE = function readFloatLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, true, 23, 4); }; - Buffer$1.prototype.readFloatBE = function readFloatBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 4, this.length); - return read(this, offset, false, 23, 4) + Buffer.prototype.readFloatBE = function readFloatBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 4, this.length); + return read(this, offset, false, 23, 4); }; - Buffer$1.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, true, 52, 8) + Buffer.prototype.readDoubleLE = function readDoubleLE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, true, 52, 8); }; - Buffer$1.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { - if (!noAssert) checkOffset(offset, 8, this.length); - return read(this, offset, false, 52, 8) + Buffer.prototype.readDoubleBE = function readDoubleBE(offset, noAssert) { + if (!noAssert) checkOffset(offset, 8, this.length); + return read(this, offset, false, 52, 8); }; - function checkInt (buf, value, offset, ext, max, min) { - if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') - if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') - if (offset + ext > buf.length) throw new RangeError('Index out of range') + function checkInt(buf, value, offset, ext, max, min) { + if (!internalIsBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance'); + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds'); + if (offset + ext > buf.length) throw new RangeError("Index out of range"); } - Buffer$1.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } + Buffer.prototype.writeUIntLE = function writeUIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } - var mul = 1; - var i = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } + var mul = 1; + var i = 0; + this[offset] = value & 0xff; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xff; + } - return offset + byteLength + return offset + byteLength; }; - Buffer$1.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - byteLength = byteLength | 0; - if (!noAssert) { - var maxBytes = Math.pow(2, 8 * byteLength) - 1; - checkInt(this, value, offset, byteLength, maxBytes, 0); - } + Buffer.prototype.writeUIntBE = function writeUIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + byteLength = byteLength | 0; + if (!noAssert) { + var maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } - var i = byteLength - 1; - var mul = 1; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - this[offset + i] = (value / mul) & 0xFF; - } + var i = byteLength - 1; + var mul = 1; + this[offset + i] = value & 0xff; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xff; + } - return offset + byteLength + return offset + byteLength; }; - Buffer$1.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - this[offset] = (value & 0xff); - return offset + 1 + Buffer.prototype.writeUInt8 = function writeUInt8(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + this[offset] = value & 0xff; + return offset + 1; }; - function objectWriteUInt16 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { - buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> - (littleEndian ? i : 1 - i) * 8; - } + function objectWriteUInt16(buf, value, offset, littleEndian) { + if (value < 0) value = 0xffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { + buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> ((littleEndian ? i : 1 - i) * 8); + } } - Buffer$1.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 + Buffer.prototype.writeUInt16LE = function writeUInt16LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2; }; - Buffer$1.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 + Buffer.prototype.writeUInt16BE = function writeUInt16BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2; }; - function objectWriteUInt32 (buf, value, offset, littleEndian) { - if (value < 0) value = 0xffffffff + value + 1; - for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { - buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff; - } + function objectWriteUInt32(buf, value, offset, littleEndian) { + if (value < 0) value = 0xffffffff + value + 1; + for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { + buf[offset + i] = (value >>> ((littleEndian ? i : 3 - i) * 8)) & 0xff; + } } - Buffer$1.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset + 3] = (value >>> 24); - this[offset + 2] = (value >>> 16); - this[offset + 1] = (value >>> 8); - this[offset] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 + Buffer.prototype.writeUInt32LE = function writeUInt32LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset + 3] = value >>> 24; + this[offset + 2] = value >>> 16; + this[offset + 1] = value >>> 8; + this[offset] = value & 0xff; + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4; }; - Buffer$1.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 + Buffer.prototype.writeUInt32BE = function writeUInt32BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4; }; - Buffer$1.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); + Buffer.prototype.writeIntLE = function writeIntLE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - var i = 0; - var mul = 1; - var sub = 0; - this[offset] = value & 0xFF; - while (++i < byteLength && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } + var i = 0; + var mul = 1; + var sub = 0; + this[offset] = value & 0xff; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = (((value / mul) >> 0) - sub) & 0xff; + } - return offset + byteLength + return offset + byteLength; }; - Buffer$1.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) { - var limit = Math.pow(2, 8 * byteLength - 1); + Buffer.prototype.writeIntBE = function writeIntBE(value, offset, byteLength, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) { + var limit = Math.pow(2, 8 * byteLength - 1); - checkInt(this, value, offset, byteLength, limit - 1, -limit); - } + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } - var i = byteLength - 1; - var mul = 1; - var sub = 0; - this[offset + i] = value & 0xFF; - while (--i >= 0 && (mul *= 0x100)) { - if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { - sub = 1; - } - this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; - } + var i = byteLength - 1; + var mul = 1; + var sub = 0; + this[offset + i] = value & 0xff; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = (((value / mul) >> 0) - sub) & 0xff; + } - return offset + byteLength + return offset + byteLength; }; - Buffer$1.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); - if (!Buffer$1.TYPED_ARRAY_SUPPORT) value = Math.floor(value); - if (value < 0) value = 0xff + value + 1; - this[offset] = (value & 0xff); - return offset + 1 + Buffer.prototype.writeInt8 = function writeInt8(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80); + if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value); + if (value < 0) value = 0xff + value + 1; + this[offset] = value & 0xff; + return offset + 1; }; - Buffer$1.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - } else { - objectWriteUInt16(this, value, offset, true); - } - return offset + 2 + Buffer.prototype.writeInt16LE = function writeInt16LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + } else { + objectWriteUInt16(this, value, offset, true); + } + return offset + 2; }; - Buffer$1.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 8); - this[offset + 1] = (value & 0xff); - } else { - objectWriteUInt16(this, value, offset, false); - } - return offset + 2 + Buffer.prototype.writeInt16BE = function writeInt16BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 8; + this[offset + 1] = value & 0xff; + } else { + objectWriteUInt16(this, value, offset, false); + } + return offset + 2; }; - Buffer$1.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value & 0xff); - this[offset + 1] = (value >>> 8); - this[offset + 2] = (value >>> 16); - this[offset + 3] = (value >>> 24); - } else { - objectWriteUInt32(this, value, offset, true); - } - return offset + 4 + Buffer.prototype.writeInt32LE = function writeInt32LE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value & 0xff; + this[offset + 1] = value >>> 8; + this[offset + 2] = value >>> 16; + this[offset + 3] = value >>> 24; + } else { + objectWriteUInt32(this, value, offset, true); + } + return offset + 4; }; - Buffer$1.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { - value = +value; - offset = offset | 0; - if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); - if (value < 0) value = 0xffffffff + value + 1; - if (Buffer$1.TYPED_ARRAY_SUPPORT) { - this[offset] = (value >>> 24); - this[offset + 1] = (value >>> 16); - this[offset + 2] = (value >>> 8); - this[offset + 3] = (value & 0xff); - } else { - objectWriteUInt32(this, value, offset, false); - } - return offset + 4 + Buffer.prototype.writeInt32BE = function writeInt32BE(value, offset, noAssert) { + value = +value; + offset = offset | 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000); + if (value < 0) value = 0xffffffff + value + 1; + if (Buffer.TYPED_ARRAY_SUPPORT) { + this[offset] = value >>> 24; + this[offset + 1] = value >>> 16; + this[offset + 2] = value >>> 8; + this[offset + 3] = value & 0xff; + } else { + objectWriteUInt32(this, value, offset, false); + } + return offset + 4; }; - function checkIEEE754 (buf, value, offset, ext, max, min) { - if (offset + ext > buf.length) throw new RangeError('Index out of range') - if (offset < 0) throw new RangeError('Index out of range') + function checkIEEE754(buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError("Index out of range"); + if (offset < 0) throw new RangeError("Index out of range"); } - function writeFloat (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 4); - } - write(buf, value, offset, littleEndian, 23, 4); - return offset + 4 + function writeFloat(buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + write$1(buf, value, offset, littleEndian, 23, 4); + return offset + 4; } - Buffer$1.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { - return writeFloat(this, value, offset, true, noAssert) + Buffer.prototype.writeFloatLE = function writeFloatLE(value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert); }; - Buffer$1.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { - return writeFloat(this, value, offset, false, noAssert) + Buffer.prototype.writeFloatBE = function writeFloatBE(value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert); }; - function writeDouble (buf, value, offset, littleEndian, noAssert) { - if (!noAssert) { - checkIEEE754(buf, value, offset, 8); - } - write(buf, value, offset, littleEndian, 52, 8); - return offset + 8 + function writeDouble(buf, value, offset, littleEndian, noAssert) { + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + write$1(buf, value, offset, littleEndian, 52, 8); + return offset + 8; } - Buffer$1.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { - return writeDouble(this, value, offset, true, noAssert) + Buffer.prototype.writeDoubleLE = function writeDoubleLE(value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert); }; - Buffer$1.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { - return writeDouble(this, value, offset, false, noAssert) + Buffer.prototype.writeDoubleBE = function writeDoubleBE(value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert); }; // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) - Buffer$1.prototype.copy = function copy (target, targetStart, start, end) { - if (!start) start = 0; - if (!end && end !== 0) end = this.length; - if (targetStart >= target.length) targetStart = target.length; - if (!targetStart) targetStart = 0; - if (end > 0 && end < start) end = start; - - // Copy 0 bytes; we're done - if (end === start) return 0 - if (target.length === 0 || this.length === 0) return 0 - - // Fatal error conditions - if (targetStart < 0) { - throw new RangeError('targetStart out of bounds') - } - if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') - if (end < 0) throw new RangeError('sourceEnd out of bounds') - - // Are we oob? - if (end > this.length) end = this.length; - if (target.length - targetStart < end - start) { - end = target.length - targetStart + start; - } + Buffer.prototype.copy = function copy(target, targetStart, start, end) { + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0; + if (target.length === 0 || this.length === 0) return 0; + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError("targetStart out of bounds"); + } + if (start < 0 || start >= this.length) throw new RangeError("sourceStart out of bounds"); + if (end < 0) throw new RangeError("sourceEnd out of bounds"); - var len = end - start; - var i; + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } - if (this === target && start < targetStart && targetStart < end) { - // descending copy from end - for (i = len - 1; i >= 0; --i) { - target[i + targetStart] = this[i + start]; - } - } else if (len < 1000 || !Buffer$1.TYPED_ARRAY_SUPPORT) { - // ascending copy from start - for (i = 0; i < len; ++i) { - target[i + targetStart] = this[i + start]; - } - } else { - Uint8Array.prototype.set.call( - target, - this.subarray(start, start + len), - targetStart - ); - } + var len = end - start; + var i; + + if (this === target && start < targetStart && targetStart < end) { + // descending copy from end + for (i = len - 1; i >= 0; --i) { + target[i + targetStart] = this[i + start]; + } + } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { + // ascending copy from start + for (i = 0; i < len; ++i) { + target[i + targetStart] = this[i + start]; + } + } else { + Uint8Array.prototype.set.call(target, this.subarray(start, start + len), targetStart); + } - return len + return len; }; // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) - Buffer$1.prototype.fill = function fill (val, start, end, encoding) { - // Handle string cases: - if (typeof val === 'string') { - if (typeof start === 'string') { - encoding = start; - start = 0; - end = this.length; - } else if (typeof end === 'string') { - encoding = end; - end = this.length; - } - if (val.length === 1) { - var code = val.charCodeAt(0); - if (code < 256) { - val = code; - } - } - if (encoding !== undefined && typeof encoding !== 'string') { - throw new TypeError('encoding must be a string') - } - if (typeof encoding === 'string' && !Buffer$1.isEncoding(encoding)) { - throw new TypeError('Unknown encoding: ' + encoding) - } - } else if (typeof val === 'number') { - val = val & 255; - } - - // Invalid ranges are not set to a default, so can range check early. - if (start < 0 || this.length < start || this.length < end) { - throw new RangeError('Out of range index') - } - - if (end <= start) { - return this - } + Buffer.prototype.fill = function fill(val, start, end, encoding) { + // Handle string cases: + if (typeof val === "string") { + if (typeof start === "string") { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === "string") { + encoding = end; + end = this.length; + } + if (val.length === 1) { + var code = val.charCodeAt(0); + if (code < 256) { + val = code; + } + } + if (encoding !== undefined && typeof encoding !== "string") { + throw new TypeError("encoding must be a string"); + } + if (typeof encoding === "string" && !Buffer.isEncoding(encoding)) { + throw new TypeError("Unknown encoding: " + encoding); + } + } else if (typeof val === "number") { + val = val & 255; + } - start = start >>> 0; - end = end === undefined ? this.length : end >>> 0; + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError("Out of range index"); + } - if (!val) val = 0; + if (end <= start) { + return this; + } - var i; - if (typeof val === 'number') { - for (i = start; i < end; ++i) { - this[i] = val; - } - } else { - var bytes = internalIsBuffer(val) - ? val - : utf8ToBytes(new Buffer$1(val, encoding).toString()); - var len = bytes.length; - for (i = 0; i < end - start; ++i) { - this[i + start] = bytes[i % len]; - } - } + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + var i; + if (typeof val === "number") { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + var bytes = internalIsBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()); + var len = bytes.length; + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } - return this + return this; }; // HELPER FUNCTIONS @@ -4856,1174 +5669,34661 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g; - function base64clean (str) { - // Node strips out invalid characters like \n and \t from the string, base64-js does not - str = stringtrim(str).replace(INVALID_BASE64_RE, ''); - // Node converts strings with length < 2 to '' - if (str.length < 2) return '' - // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not - while (str.length % 4 !== 0) { - str = str + '='; - } - return str + function base64clean(str) { + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = stringtrim(str).replace(INVALID_BASE64_RE, ""); + // Node converts strings with length < 2 to '' + if (str.length < 2) return ""; + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + "="; + } + return str; } - function stringtrim (str) { - if (str.trim) return str.trim() - return str.replace(/^\s+|\s+$/g, '') + function stringtrim(str) { + if (str.trim) return str.trim(); + return str.replace(/^\s+|\s+$/g, ""); } - function toHex (n) { - if (n < 16) return '0' + n.toString(16) - return n.toString(16) + function toHex(n) { + if (n < 16) return "0" + n.toString(16); + return n.toString(16); } - function utf8ToBytes (string, units) { - units = units || Infinity; - var codePoint; - var length = string.length; - var leadSurrogate = null; - var bytes = []; - - for (var i = 0; i < length; ++i) { - codePoint = string.charCodeAt(i); - - // is surrogate component - if (codePoint > 0xD7FF && codePoint < 0xE000) { - // last char was a lead - if (!leadSurrogate) { - // no lead yet - if (codePoint > 0xDBFF) { - // unexpected trail - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } else if (i + 1 === length) { - // unpaired lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - continue - } - - // valid lead - leadSurrogate = codePoint; - - continue - } - - // 2 leads in a row - if (codePoint < 0xDC00) { - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - leadSurrogate = codePoint; - continue - } - - // valid surrogate pair - codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; - } else if (leadSurrogate) { - // valid bmp char, but last char was a lead - if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); - } + function utf8ToBytes(string, units) { + units = units || Infinity; + var codePoint; + var length = string.length; + var leadSurrogate = null; + var bytes = []; + + for (var i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xd7ff && codePoint < 0xe000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xdbff) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + continue; + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + continue; + } + + // valid lead + leadSurrogate = codePoint; + + continue; + } - leadSurrogate = null; + // 2 leads in a row + if (codePoint < 0xdc00) { + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + leadSurrogate = codePoint; + continue; + } - // encode utf8 - if (codePoint < 0x80) { - if ((units -= 1) < 0) break - bytes.push(codePoint); - } else if (codePoint < 0x800) { - if ((units -= 2) < 0) break - bytes.push( - codePoint >> 0x6 | 0xC0, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x10000) { - if ((units -= 3) < 0) break - bytes.push( - codePoint >> 0xC | 0xE0, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else if (codePoint < 0x110000) { - if ((units -= 4) < 0) break - bytes.push( - codePoint >> 0x12 | 0xF0, - codePoint >> 0xC & 0x3F | 0x80, - codePoint >> 0x6 & 0x3F | 0x80, - codePoint & 0x3F | 0x80 - ); - } else { - throw new Error('Invalid code point') - } - } + // valid surrogate pair + codePoint = (((leadSurrogate - 0xd800) << 10) | (codePoint - 0xdc00)) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xef, 0xbf, 0xbd); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break; + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break; + bytes.push((codePoint >> 0x6) | 0xc0, (codePoint & 0x3f) | 0x80); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break; + bytes.push((codePoint >> 0xc) | 0xe0, ((codePoint >> 0x6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break; + bytes.push((codePoint >> 0x12) | 0xf0, ((codePoint >> 0xc) & 0x3f) | 0x80, ((codePoint >> 0x6) & 0x3f) | 0x80, (codePoint & 0x3f) | 0x80); + } else { + throw new Error("Invalid code point"); + } + } - return bytes + return bytes; } - function asciiToBytes (str) { - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - // Node's code seems to be doing this and not & 0x7F.. - byteArray.push(str.charCodeAt(i) & 0xFF); - } - return byteArray + function asciiToBytes(str) { + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xff); + } + return byteArray; } - function utf16leToBytes (str, units) { - var c, hi, lo; - var byteArray = []; - for (var i = 0; i < str.length; ++i) { - if ((units -= 2) < 0) break - - c = str.charCodeAt(i); - hi = c >> 8; - lo = c % 256; - byteArray.push(lo); - byteArray.push(hi); - } + function utf16leToBytes(str, units) { + var c, hi, lo; + var byteArray = []; + for (var i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break; + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } - return byteArray + return byteArray; } - - function base64ToBytes (str) { - return toByteArray(base64clean(str)) + function base64ToBytes(str) { + return toByteArray(base64clean(str)); } - function blitBuffer (src, dst, offset, length) { - for (var i = 0; i < length; ++i) { - if ((i + offset >= dst.length) || (i >= src.length)) break - dst[i + offset] = src[i]; - } - return i + function blitBuffer(src, dst, offset, length) { + for (var i = 0; i < length; ++i) { + if (i + offset >= dst.length || i >= src.length) break; + dst[i + offset] = src[i]; + } + return i; } - function isnan (val) { - return val !== val // eslint-disable-line no-self-compare + function isnan(val) { + return val !== val; // eslint-disable-line no-self-compare } - // the following is from is-buffer, also by Feross Aboukhadijeh and with same lisence // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually - function isBuffer$1(obj) { - return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)) + function isBuffer$2(obj) { + return obj != null && (!!obj._isBuffer || isFastBuffer(obj) || isSlowBuffer(obj)); } - function isFastBuffer (obj) { - return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) + function isFastBuffer(obj) { + return !!obj.constructor && typeof obj.constructor.isBuffer === "function" && obj.constructor.isBuffer(obj); } // For Node v0.10 support. Remove this eventually. - function isSlowBuffer (obj) { - return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isFastBuffer(obj.slice(0, 0)) + function isSlowBuffer(obj) { + return typeof obj.readFloatLE === "function" && typeof obj.slice === "function" && isFastBuffer(obj.slice(0, 0)); } - // shim for using process in browser - // based off https://github.com/defunctzombie/node-process/blob/master/browser.js + let Blob$3 = class Blob {}; - function defaultSetTimout() { - throw new Error('setTimeout has not been defined'); - } - function defaultClearTimeout () { - throw new Error('clearTimeout has not been defined'); - } - var cachedSetTimeout = defaultSetTimout; - var cachedClearTimeout = defaultClearTimeout; - if (typeof global$1.setTimeout === 'function') { - cachedSetTimeout = setTimeout; - } - if (typeof global$1.clearTimeout === 'function') { - cachedClearTimeout = clearTimeout; - } + var _polyfillNode_buffer = /*#__PURE__*/Object.freeze({ + __proto__: null, + Blob: Blob$3, + Buffer: Buffer, + INSPECT_MAX_BYTES: INSPECT_MAX_BYTES, + SlowBuffer: SlowBuffer, + isBuffer: isBuffer$2, + kMaxLength: _kMaxLength + }); - function runTimeout(fun) { - if (cachedSetTimeout === setTimeout) { - //normal enviroments in sane situations - return setTimeout(fun, 0); - } - // if setTimeout wasn't available but was latter defined - if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { - cachedSetTimeout = setTimeout; - return setTimeout(fun, 0); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedSetTimeout(fun, 0); - } catch(e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedSetTimeout.call(null, fun, 0); - } catch(e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error - return cachedSetTimeout.call(this, fun, 0); - } - } + var index_node_cjs = {}; + var require$$1$4 = /*@__PURE__*/getAugmentedNamespace(index_esm2017$1); + var inherits; + if (typeof Object.create === 'function'){ + inherits = function inherits(ctor, superCtor) { + // implementation from standard node.js 'util' module + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; + } else { + inherits = function inherits(ctor, superCtor) { + ctor.super_ = superCtor; + var TempCtor = function () {}; + TempCtor.prototype = superCtor.prototype; + ctor.prototype = new TempCtor(); + ctor.prototype.constructor = ctor; + }; } - function runClearTimeout(marker) { - if (cachedClearTimeout === clearTimeout) { - //normal enviroments in sane situations - return clearTimeout(marker); - } - // if clearTimeout wasn't available but was latter defined - if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { - cachedClearTimeout = clearTimeout; - return clearTimeout(marker); - } - try { - // when when somebody has screwed with setTimeout but no I.E. maddness - return cachedClearTimeout(marker); - } catch (e){ - try { - // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally - return cachedClearTimeout.call(null, marker); - } catch (e){ - // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. - // Some versions of I.E. have different rules for clearTimeout vs setTimeout - return cachedClearTimeout.call(this, marker); - } - } + var inherits$1 = inherits; + var getOwnPropertyDescriptors = + Object.getOwnPropertyDescriptors || + function getOwnPropertyDescriptors(obj) { + var keys = Object.keys(obj); + var descriptors = {}; + for (var i = 0; i < keys.length; i++) { + descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); + } + return descriptors; + }; + var formatRegExp = /%[sdj%]/g; + function format$1(f) { + if (!isString(f)) { + var objects = []; + for (var i = 0; i < arguments.length; i++) { + objects.push(inspect$1(arguments[i])); + } + return objects.join(" "); + } + var i = 1; + var args = arguments; + var len = args.length; + var str = String(f).replace(formatRegExp, function (x) { + if (x === "%%") return "%"; + if (i >= len) return x; + switch (x) { + case "%s": + return String(args[i++]); + case "%d": + return Number(args[i++]); + case "%j": + try { + return JSON.stringify(args[i++]); + } catch (_) { + return "[Circular]"; + } + default: + return x; + } + }); + for (var x = args[i]; i < len; x = args[++i]) { + if (isNull(x) || !isObject(x)) { + str += " " + x; + } else { + str += " " + inspect$1(x); + } + } + return str; } - var queue = []; - var draining = false; - var currentQueue; - var queueIndex = -1; - function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - drainQueue(); - } + // Mark that a method should not be used. + // Returns a modified function which warns once by default. + // If --no-deprecation is set, then it is a no-op. + function deprecate(fn, msg) { + // Allow for deprecating things in the process of starting up. + if (isUndefined(global$3.process)) { + return function () { + return deprecate(fn, msg).apply(this, arguments); + }; + } + + if (browser$1$1.noDeprecation === true) { + return fn; + } + + var warned = false; + function deprecated() { + if (!warned) { + if (browser$1$1.throwDeprecation) { + throw new Error(msg); + } else if (browser$1$1.traceDeprecation) { + console.trace(msg); + } else { + console.error(msg); + } + warned = true; + } + return fn.apply(this, arguments); + } + + return deprecated; } - function drainQueue() { - if (draining) { - return; - } - var timeout = runTimeout(cleanUpNextTick); - draining = true; + var debugs = {}; + var debugEnviron; + function debuglog(set) { + if (isUndefined(debugEnviron)) debugEnviron = browser$1$1.env.NODE_DEBUG || ""; + set = set.toUpperCase(); + if (!debugs[set]) { + if (new RegExp("\\b" + set + "\\b", "i").test(debugEnviron)) { + var pid = 0; + debugs[set] = function () { + var msg = format$1.apply(null, arguments); + console.error("%s %d: %s", set, pid, msg); + }; + } else { + debugs[set] = function () {}; + } + } + return debugs[set]; + } - var len = queue.length; - while(len) { - currentQueue = queue; - queue = []; - while (++queueIndex < len) { - if (currentQueue) { - currentQueue[queueIndex].run(); - } - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - draining = false; - runClearTimeout(timeout); + /** + * Echos the value of a value. Trys to print the value out + * in the best way possible given the different types. + * + * @param {Object} obj The object to print out. + * @param {Object} opts Optional options object that alters the output. + */ + /* legacy: obj, showHidden, depth, colors*/ + function inspect$1(obj, opts) { + // default options + var ctx = { + seen: [], + stylize: stylizeNoColor, + }; + // legacy... + if (arguments.length >= 3) ctx.depth = arguments[2]; + if (arguments.length >= 4) ctx.colors = arguments[3]; + if (isBoolean(opts)) { + // legacy... + ctx.showHidden = opts; + } else if (opts) { + // got an "options" object + _extend(ctx, opts); + } + // set default options + if (isUndefined(ctx.showHidden)) ctx.showHidden = false; + if (isUndefined(ctx.depth)) ctx.depth = 2; + if (isUndefined(ctx.colors)) ctx.colors = false; + if (isUndefined(ctx.customInspect)) ctx.customInspect = true; + if (ctx.colors) ctx.stylize = stylizeWithColor; + return formatValue(ctx, obj, ctx.depth); } - function nextTick(fun) { - var args = new Array(arguments.length - 1); - if (arguments.length > 1) { - for (var i = 1; i < arguments.length; i++) { - args[i - 1] = arguments[i]; - } - } - queue.push(new Item(fun, args)); - if (queue.length === 1 && !draining) { - runTimeout(drainQueue); - } + + // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics + inspect$1.colors = { + bold: [1, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + white: [37, 39], + grey: [90, 39], + black: [30, 39], + blue: [34, 39], + cyan: [36, 39], + green: [32, 39], + magenta: [35, 39], + red: [31, 39], + yellow: [33, 39], + }; + + // Don't use 'blue' not visible on cmd.exe + inspect$1.styles = { + special: "cyan", + number: "yellow", + boolean: "yellow", + undefined: "grey", + null: "bold", + string: "green", + date: "magenta", + // "name": intentionally not styling + regexp: "red", + }; + + function stylizeWithColor(str, styleType) { + var style = inspect$1.styles[styleType]; + + if (style) { + return "\u001b[" + inspect$1.colors[style][0] + "m" + str + "\u001b[" + inspect$1.colors[style][1] + "m"; + } else { + return str; + } } - // v8 likes predictible objects - function Item(fun, array) { - this.fun = fun; - this.array = array; + + function stylizeNoColor(str, styleType) { + return str; } - Item.prototype.run = function () { - this.fun.apply(null, this.array); - }; - var title = 'browser'; - var platform = 'browser'; - var browser$2 = true; - var env = {}; - var argv = []; - var version$2 = ''; // empty string to avoid regexp issues - var versions = {}; - var release = {}; - var config = {}; - function noop() {} + function arrayToHash(array) { + var hash = {}; - var on = noop; - var addListener = noop; - var once = noop; - var off = noop; - var removeListener = noop; - var removeAllListeners = noop; - var emit = noop; + array.forEach(function (val, idx) { + hash[val] = true; + }); - function binding(name) { - throw new Error('process.binding is not supported'); + return hash; } - function cwd () { return '/' } - function chdir (dir) { - throw new Error('process.chdir is not supported'); - }function umask() { return 0; } + function formatValue(ctx, value, recurseTimes) { + // Provide a hook for user-specified inspect functions. + // Check that value is an object with an inspect function on it + if ( + ctx.customInspect && + value && + isFunction$1(value.inspect) && + // Filter out the util module, it's inspect function is special + value.inspect !== inspect$1 && + // Also filter out any prototype objects using the circular check. + !(value.constructor && value.constructor.prototype === value) + ) { + var ret = value.inspect(recurseTimes, ctx); + if (!isString(ret)) { + ret = formatValue(ctx, ret, recurseTimes); + } + return ret; + } - // from https://github.com/kumavis/browser-process-hrtime/blob/master/index.js - var performance = global$1.performance || {}; - var performanceNow = - performance.now || - performance.mozNow || - performance.msNow || - performance.oNow || - performance.webkitNow || - function(){ return (new Date()).getTime() }; + // Primitive types cannot have properties + var primitive = formatPrimitive(ctx, value); + if (primitive) { + return primitive; + } - // generate timestamp or delta - // see http://nodejs.org/api/process.html#process_process_hrtime - function hrtime(previousTimestamp){ - var clocktime = performanceNow.call(performance)*1e-3; - var seconds = Math.floor(clocktime); - var nanoseconds = Math.floor((clocktime%1)*1e9); - if (previousTimestamp) { - seconds = seconds - previousTimestamp[0]; - nanoseconds = nanoseconds - previousTimestamp[1]; - if (nanoseconds<0) { - seconds--; - nanoseconds += 1e9; - } - } - return [seconds,nanoseconds] + // Look up the keys of the object. + var keys = Object.keys(value); + var visibleKeys = arrayToHash(keys); + + if (ctx.showHidden) { + keys = Object.getOwnPropertyNames(value); + } + + // IE doesn't make error fields non-enumerable + // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx + if (isError(value) && (keys.indexOf("message") >= 0 || keys.indexOf("description") >= 0)) { + return formatError(value); + } + + // Some type of object without properties can be shortcutted. + if (keys.length === 0) { + if (isFunction$1(value)) { + var name = value.name ? ": " + value.name : ""; + return ctx.stylize("[Function" + name + "]", "special"); + } + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); + } + if (isDate(value)) { + return ctx.stylize(Date.prototype.toString.call(value), "date"); + } + if (isError(value)) { + return formatError(value); + } + } + + var base = "", + array = false, + braces = ["{", "}"]; + + // Make Array say that they are Array + if (isArray$2(value)) { + array = true; + braces = ["[", "]"]; + } + + // Make functions say that they are functions + if (isFunction$1(value)) { + var n = value.name ? ": " + value.name : ""; + base = " [Function" + n + "]"; + } + + // Make RegExps say that they are RegExps + if (isRegExp(value)) { + base = " " + RegExp.prototype.toString.call(value); + } + + // Make dates with properties first say the date + if (isDate(value)) { + base = " " + Date.prototype.toUTCString.call(value); + } + + // Make error with message first say the error + if (isError(value)) { + base = " " + formatError(value); + } + + if (keys.length === 0 && (!array || value.length == 0)) { + return braces[0] + base + braces[1]; + } + + if (recurseTimes < 0) { + if (isRegExp(value)) { + return ctx.stylize(RegExp.prototype.toString.call(value), "regexp"); + } else { + return ctx.stylize("[Object]", "special"); + } + } + + ctx.seen.push(value); + + var output; + if (array) { + output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); + } else { + output = keys.map(function (key) { + return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); + }); + } + + ctx.seen.pop(); + + return reduceToSingleString(output, base, braces); } - var startTime = new Date(); - function uptime() { - var currentTime = new Date(); - var dif = currentTime - startTime; - return dif / 1000; + function formatPrimitive(ctx, value) { + if (isUndefined(value)) return ctx.stylize("undefined", "undefined"); + if (isString(value)) { + var simple = "'" + JSON.stringify(value).replace(/^"|"$/g, "").replace(/'/g, "\\'").replace(/\\"/g, '"') + "'"; + return ctx.stylize(simple, "string"); + } + if (isNumber(value)) return ctx.stylize("" + value, "number"); + if (isBoolean(value)) return ctx.stylize("" + value, "boolean"); + // For some reason typeof null is "object", so special case here. + if (isNull(value)) return ctx.stylize("null", "null"); } - var browser$1$1 = { - nextTick: nextTick, - title: title, - browser: browser$2, - env: env, - argv: argv, - version: version$2, - versions: versions, - on: on, - addListener: addListener, - once: once, - off: off, - removeListener: removeListener, - removeAllListeners: removeAllListeners, - emit: emit, - binding: binding, - cwd: cwd, - chdir: chdir, - umask: umask, - hrtime: hrtime, - platform: platform, - release: release, - config: config, - uptime: uptime - }; + function formatError(value) { + return "[" + Error.prototype.toString.call(value) + "]"; + } - var inherits; - if (typeof Object.create === 'function'){ - inherits = function inherits(ctor, superCtor) { - // implementation from standard node.js 'util' module - ctor.super_ = superCtor; - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; - } else { - inherits = function inherits(ctor, superCtor) { - ctor.super_ = superCtor; - var TempCtor = function () {}; - TempCtor.prototype = superCtor.prototype; - ctor.prototype = new TempCtor(); - ctor.prototype.constructor = ctor; - }; + function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { + var output = []; + for (var i = 0, l = value.length; i < l; ++i) { + if (hasOwnProperty$1(value, String(i))) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); + } else { + output.push(""); + } + } + keys.forEach(function (key) { + if (!key.match(/^\d+$/)) { + output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); + } + }); + return output; } - var inherits$1 = inherits; - var getOwnPropertyDescriptors = Object.getOwnPropertyDescriptors || - function getOwnPropertyDescriptors(obj) { - var keys = Object.keys(obj); - var descriptors = {}; - for (var i = 0; i < keys.length; i++) { - descriptors[keys[i]] = Object.getOwnPropertyDescriptor(obj, keys[i]); - } - return descriptors; - }; + function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { + var name, str, desc; + desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; + if (desc.get) { + if (desc.set) { + str = ctx.stylize("[Getter/Setter]", "special"); + } else { + str = ctx.stylize("[Getter]", "special"); + } + } else { + if (desc.set) { + str = ctx.stylize("[Setter]", "special"); + } + } + if (!hasOwnProperty$1(visibleKeys, key)) { + name = "[" + key + "]"; + } + if (!str) { + if (ctx.seen.indexOf(desc.value) < 0) { + if (isNull(recurseTimes)) { + str = formatValue(ctx, desc.value, null); + } else { + str = formatValue(ctx, desc.value, recurseTimes - 1); + } + if (str.indexOf("\n") > -1) { + if (array) { + str = str + .split("\n") + .map(function (line) { + return " " + line; + }) + .join("\n") + .substr(2); + } else { + str = + "\n" + + str + .split("\n") + .map(function (line) { + return " " + line; + }) + .join("\n"); + } + } + } else { + str = ctx.stylize("[Circular]", "special"); + } + } + if (isUndefined(name)) { + if (array && key.match(/^\d+$/)) { + return str; + } + name = JSON.stringify("" + key); + if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { + name = name.substr(1, name.length - 2); + name = ctx.stylize(name, "name"); + } else { + name = name + .replace(/'/g, "\\'") + .replace(/\\"/g, '"') + .replace(/(^"|"$)/g, "'"); + name = ctx.stylize(name, "string"); + } + } - var formatRegExp = /%[sdj%]/g; - function format(f) { - if (!isString(f)) { - var objects = []; - for (var i = 0; i < arguments.length; i++) { - objects.push(inspect(arguments[i])); - } - return objects.join(' '); - } - - var i = 1; - var args = arguments; - var len = args.length; - var str = String(f).replace(formatRegExp, function(x) { - if (x === '%%') return '%'; - if (i >= len) return x; - switch (x) { - case '%s': return String(args[i++]); - case '%d': return Number(args[i++]); - case '%j': - try { - return JSON.stringify(args[i++]); - } catch (_) { - return '[Circular]'; - } - default: - return x; - } - }); - for (var x = args[i]; i < len; x = args[++i]) { - if (isNull(x) || !isObject(x)) { - str += ' ' + x; - } else { - str += ' ' + inspect(x); - } - } - return str; + return name + ": " + str; } - // Mark that a method should not be used. - // Returns a modified function which warns once by default. - // If --no-deprecation is set, then it is a no-op. - function deprecate(fn, msg) { - // Allow for deprecating things in the process of starting up. - if (isUndefined(global$1.process)) { - return function() { - return deprecate(fn, msg).apply(this, arguments); - }; - } + function reduceToSingleString(output, base, braces) { + var length = output.reduce(function (prev, cur) { + if (cur.indexOf("\n") >= 0) ; + return prev + cur.replace(/\u001b\[\d\d?m/g, "").length + 1; + }, 0); - if (browser$1$1.noDeprecation === true) { - return fn; - } + if (length > 60) { + return braces[0] + (base === "" ? "" : base + "\n ") + " " + output.join(",\n ") + " " + braces[1]; + } - var warned = false; - function deprecated() { - if (!warned) { - if (browser$1$1.throwDeprecation) { - throw new Error(msg); - } else if (browser$1$1.traceDeprecation) { - console.trace(msg); - } else { - console.error(msg); - } - warned = true; - } - return fn.apply(this, arguments); - } + return braces[0] + base + " " + output.join(", ") + " " + braces[1]; + } - return deprecated; + // NOTE: These type checking functions intentionally don't use `instanceof` + // because it is fragile and can be easily faked with `Object.create()`. + function isArray$2(ar) { + return Array.isArray(ar); } - var debugs = {}; - var debugEnviron; - function debuglog(set) { - if (isUndefined(debugEnviron)) - debugEnviron = browser$1$1.env.NODE_DEBUG || ''; - set = set.toUpperCase(); - if (!debugs[set]) { - if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { - var pid = 0; - debugs[set] = function() { - var msg = format.apply(null, arguments); - console.error('%s %d: %s', set, pid, msg); - }; - } else { - debugs[set] = function() {}; - } - } - return debugs[set]; + function isBoolean(arg) { + return typeof arg === "boolean"; } - /** - * Echos the value of a value. Trys to print the value out - * in the best way possible given the different types. - * - * @param {Object} obj The object to print out. - * @param {Object} opts Optional options object that alters the output. - */ - /* legacy: obj, showHidden, depth, colors*/ - function inspect(obj, opts) { - // default options - var ctx = { - seen: [], - stylize: stylizeNoColor - }; - // legacy... - if (arguments.length >= 3) ctx.depth = arguments[2]; - if (arguments.length >= 4) ctx.colors = arguments[3]; - if (isBoolean(opts)) { - // legacy... - ctx.showHidden = opts; - } else if (opts) { - // got an "options" object - _extend(ctx, opts); - } - // set default options - if (isUndefined(ctx.showHidden)) ctx.showHidden = false; - if (isUndefined(ctx.depth)) ctx.depth = 2; - if (isUndefined(ctx.colors)) ctx.colors = false; - if (isUndefined(ctx.customInspect)) ctx.customInspect = true; - if (ctx.colors) ctx.stylize = stylizeWithColor; - return formatValue(ctx, obj, ctx.depth); + function isNull(arg) { + return arg === null; + } + + function isNullOrUndefined$1(arg) { + return arg == null; + } + + function isNumber(arg) { + return typeof arg === "number"; + } + + function isString(arg) { + return typeof arg === "string"; + } + + function isSymbol(arg) { + return typeof arg === "symbol"; + } + + function isUndefined(arg) { + return arg === void 0; + } + + function isRegExp(re) { + return isObject(re) && objectToString(re) === "[object RegExp]"; + } + + function isObject(arg) { + return typeof arg === "object" && arg !== null; } - // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics - inspect.colors = { - 'bold' : [1, 22], - 'italic' : [3, 23], - 'underline' : [4, 24], - 'inverse' : [7, 27], - 'white' : [37, 39], - 'grey' : [90, 39], - 'black' : [30, 39], - 'blue' : [34, 39], - 'cyan' : [36, 39], - 'green' : [32, 39], - 'magenta' : [35, 39], - 'red' : [31, 39], - 'yellow' : [33, 39] - }; + function isDate(d) { + return isObject(d) && objectToString(d) === "[object Date]"; + } + + function isError(e) { + return isObject(e) && (objectToString(e) === "[object Error]" || e instanceof Error); + } + + function isFunction$1(arg) { + return typeof arg === "function"; + } + + function isPrimitive(arg) { + return ( + arg === null || + typeof arg === "boolean" || + typeof arg === "number" || + typeof arg === "string" || + typeof arg === "symbol" || // ES6 symbol + typeof arg === "undefined" + ); + } + + function isBuffer$1(maybeBuf) { + return Buffer.isBuffer(maybeBuf); + } + + function objectToString(o) { + return Object.prototype.toString.call(o); + } + + function pad(n) { + return n < 10 ? "0" + n.toString(10) : n.toString(10); + } + + var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + + // 26 Feb 16:19:34 + function timestamp() { + var d = new Date(); + var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(":"); + return [d.getDate(), months[d.getMonth()], time].join(" "); + } + + // log is just a thin wrapper to console.log that prepends a timestamp + function log() { + console.log("%s - %s", timestamp(), format$1.apply(null, arguments)); + } + + function _extend(origin, add) { + // Don't do anything if add isn't an object + if (!add || !isObject(add)) return origin; + + var keys = Object.keys(add); + var i = keys.length; + while (i--) { + origin[keys[i]] = add[keys[i]]; + } + return origin; + } + + function hasOwnProperty$1(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + + var kCustomPromisifiedSymbol = typeof Symbol !== "undefined" ? Symbol("util.promisify.custom") : undefined; + + function promisify$2(original) { + if (typeof original !== "function") throw new TypeError('The "original" argument must be of type Function'); + + if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { + var fn = original[kCustomPromisifiedSymbol]; + if (typeof fn !== "function") { + throw new TypeError('The "util.promisify.custom" argument must be of type Function'); + } + Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, + enumerable: false, + writable: false, + configurable: true, + }); + return fn; + } + + function fn() { + var promiseResolve, promiseReject; + var promise = new Promise(function (resolve, reject) { + promiseResolve = resolve; + promiseReject = reject; + }); + + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + args.push(function (err, value) { + if (err) { + promiseReject(err); + } else { + promiseResolve(value); + } + }); + + try { + original.apply(this, args); + } catch (err) { + promiseReject(err); + } + + return promise; + } + + Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); + + if (kCustomPromisifiedSymbol) + Object.defineProperty(fn, kCustomPromisifiedSymbol, { + value: fn, + enumerable: false, + writable: false, + configurable: true, + }); + return Object.defineProperties(fn, getOwnPropertyDescriptors(original)); + } + + promisify$2.custom = kCustomPromisifiedSymbol; + + function callbackifyOnRejected(reason, cb) { + // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). + // Because `null` is a special error value in callbacks which means "no error + // occurred", we error-wrap so the callback consumer can distinguish between + // "the promise rejected with null" or "the promise fulfilled with undefined". + if (!reason) { + var newReason = new Error("Promise was rejected with a falsy value"); + newReason.reason = reason; + reason = newReason; + } + return cb(reason); + } + + function callbackify(original) { + if (typeof original !== "function") { + throw new TypeError('The "original" argument must be of type Function'); + } + + // We DO NOT return the promise as it gives the user a false sense that + // the promise is actually somehow related to the callback's execution + // and that the callback throwing will reject the promise. + function callbackified() { + var args = []; + for (var i = 0; i < arguments.length; i++) { + args.push(arguments[i]); + } + + var maybeCb = args.pop(); + if (typeof maybeCb !== "function") { + throw new TypeError("The last argument must be of type Function"); + } + var self = this; + var cb = function () { + return maybeCb.apply(self, arguments); + }; + // In true node style we process the callback on `nextTick` with all the + // implications (stack, `uncaughtException`, `async_hooks`) + original.apply(this, args).then( + function (ret) { + browser$1$1.nextTick(cb.bind(null, null, ret)); + }, + function (rej) { + browser$1$1.nextTick(callbackifyOnRejected.bind(null, rej, cb)); + } + ); + } + + Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); + Object.defineProperties(callbackified, getOwnPropertyDescriptors(original)); + return callbackified; + } + + function isPromise$1(obj) { + return obj && typeof obj.then === "function"; + } + + const types = { + inherits: inherits$1, + _extend: _extend, + log: log, + isBuffer: isBuffer$1, + isPrimitive: isPrimitive, + isFunction: isFunction$1, + isError: isError, + isDate: isDate, + isObject: isObject, + isRegExp: isRegExp, + isUndefined: isUndefined, + isSymbol: isSymbol, + isString: isString, + isNumber: isNumber, + isNullOrUndefined: isNullOrUndefined$1, + isNull: isNull, + isBoolean: isBoolean, + isArray: isArray$2, + inspect: inspect$1, + deprecate: deprecate, + format: format$1, + debuglog: debuglog, + promisify: promisify$2, + callbackify: callbackify, + isPromise: isPromise$1, + }; + + var _polyfillNode_util = /*#__PURE__*/Object.freeze({ + __proto__: null, + _extend: _extend, + callbackify: callbackify, + debuglog: debuglog, + default: types, + deprecate: deprecate, + format: format$1, + inherits: inherits$1, + inspect: inspect$1, + isArray: isArray$2, + isBoolean: isBoolean, + isBuffer: isBuffer$1, + isDate: isDate, + isError: isError, + isFunction: isFunction$1, + isNull: isNull, + isNullOrUndefined: isNullOrUndefined$1, + isNumber: isNumber, + isObject: isObject, + isPrimitive: isPrimitive, + isPromise: isPromise$1, + isRegExp: isRegExp, + isString: isString, + isSymbol: isSymbol, + isUndefined: isUndefined, + log: log, + promisify: promisify$2, + types: types + }); + + var require$$3$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util); + + var require$$4$1 = /*@__PURE__*/getAugmentedNamespace(index_esm2017$2); + + var undici$1 = {}; + + function compare(a, b) { + if (a === b) { + return 0; + } + + var x = a.length; + var y = b.length; + + for (var i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break; + } + } + + if (x < y) { + return -1; + } + if (y < x) { + return 1; + } + return 0; + } + var hasOwn = Object.prototype.hasOwnProperty; + + var objectKeys$1 = Object.keys || function (obj) { + var keys = []; + for (var key in obj) { + if (hasOwn.call(obj, key)) keys.push(key); + } + return keys; + }; + var pSlice = Array.prototype.slice; + var _functionsHaveNames; + function functionsHaveNames() { + if (typeof _functionsHaveNames !== 'undefined') { + return _functionsHaveNames; + } + return _functionsHaveNames = (function () { + return function foo() {}.name === 'foo'; + }()); + } + function pToString (obj) { + return Object.prototype.toString.call(obj); + } + function isView(arrbuf) { + if (isBuffer$2(arrbuf)) { + return false; + } + if (typeof global$3.ArrayBuffer !== 'function') { + return false; + } + if (typeof ArrayBuffer.isView === 'function') { + return ArrayBuffer.isView(arrbuf); + } + if (!arrbuf) { + return false; + } + if (arrbuf instanceof DataView) { + return true; + } + if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { + return true; + } + return false; + } + // 1. The assert module provides functions that throw + // AssertionError's when particular conditions are not met. The + // assert module must conform to the following interface. + + function assert$a(value, message) { + if (!value) fail$1(value, true, message, '==', ok); + } + + // 2. The AssertionError is defined in assert. + // new assert.AssertionError({ message: message, + // actual: actual, + // expected: expected }) + + var regex = /\s*function\s+([^\(\s]*)\s*/; + // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js + function getName(func) { + if (!isFunction$1(func)) { + return; + } + if (functionsHaveNames()) { + return func.name; + } + var str = func.toString(); + var match = str.match(regex); + return match && match[1]; + } + assert$a.AssertionError = AssertionError; + function AssertionError(options) { + this.name = 'AssertionError'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + if (options.message) { + this.message = options.message; + this.generatedMessage = false; + } else { + this.message = getMessage(this); + this.generatedMessage = true; + } + var stackStartFunction = options.stackStartFunction || fail$1; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, stackStartFunction); + } else { + // non v8 browsers so we can have a stacktrace + var err = new Error(); + if (err.stack) { + var out = err.stack; + + // try to strip useless frames + var fn_name = getName(stackStartFunction); + var idx = out.indexOf('\n' + fn_name); + if (idx >= 0) { + // once we have located the function frame + // we need to strip out everything before it (and its line) + var next_line = out.indexOf('\n', idx + 1); + out = out.substring(next_line + 1); + } + + this.stack = out; + } + } + } + + // assert.AssertionError instanceof Error + inherits$1(AssertionError, Error); + + function truncate(s, n) { + if (typeof s === 'string') { + return s.length < n ? s : s.slice(0, n); + } else { + return s; + } + } + function inspect(something) { + if (functionsHaveNames() || !isFunction$1(something)) { + return inspect$1(something); + } + var rawname = getName(something); + var name = rawname ? ': ' + rawname : ''; + return '[Function' + name + ']'; + } + function getMessage(self) { + return truncate(inspect(self.actual), 128) + ' ' + + self.operator + ' ' + + truncate(inspect(self.expected), 128); + } + + // At present only the three keys mentioned above are used and + // understood by the spec. Implementations or sub modules can pass + // other keys to the AssertionError's constructor - they will be + // ignored. + + // 3. All of the following functions must throw an AssertionError + // when a corresponding condition is not met, with a message that + // may be undefined if not provided. All assertion methods provide + // both the actual and expected values to the assertion error for + // display purposes. + + function fail$1(actual, expected, message, operator, stackStartFunction) { + throw new AssertionError({ + message: message, + actual: actual, + expected: expected, + operator: operator, + stackStartFunction: stackStartFunction + }); + } + + // EXTENSION! allows for well behaved errors defined elsewhere. + assert$a.fail = fail$1; + + // 4. Pure assertion tests whether a value is truthy, as determined + // by !!guard. + // assert.ok(guard, message_opt); + // This statement is equivalent to assert.equal(true, !!guard, + // message_opt);. To test strictly for the value true, use + // assert.strictEqual(true, guard, message_opt);. + + function ok(value, message) { + if (!value) fail$1(value, true, message, '==', ok); + } + assert$a.ok = ok; + + // 5. The equality assertion tests shallow, coercive equality with + // ==. + // assert.equal(actual, expected, message_opt); + assert$a.equal = equal; + function equal(actual, expected, message) { + if (actual != expected) fail$1(actual, expected, message, '==', equal); + } + + // 6. The non-equality assertion tests for whether two objects are not equal + // with != assert.notEqual(actual, expected, message_opt); + assert$a.notEqual = notEqual; + function notEqual(actual, expected, message) { + if (actual == expected) { + fail$1(actual, expected, message, '!=', notEqual); + } + } + + // 7. The equivalence assertion tests a deep equality relation. + // assert.deepEqual(actual, expected, message_opt); + assert$a.deepEqual = deepEqual; + function deepEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, false)) { + fail$1(actual, expected, message, 'deepEqual', deepEqual); + } + } + assert$a.deepStrictEqual = deepStrictEqual; + function deepStrictEqual(actual, expected, message) { + if (!_deepEqual(actual, expected, true)) { + fail$1(actual, expected, message, 'deepStrictEqual', deepStrictEqual); + } + } + + function _deepEqual(actual, expected, strict, memos) { + // 7.1. All identical values are equivalent, as determined by ===. + if (actual === expected) { + return true; + } else if (isBuffer$2(actual) && isBuffer$2(expected)) { + return compare(actual, expected) === 0; + + // 7.2. If the expected value is a Date object, the actual value is + // equivalent if it is also a Date object that refers to the same time. + } else if (isDate(actual) && isDate(expected)) { + return actual.getTime() === expected.getTime(); + + // 7.3 If the expected value is a RegExp object, the actual value is + // equivalent if it is also a RegExp object with the same source and + // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). + } else if (isRegExp(actual) && isRegExp(expected)) { + return actual.source === expected.source && + actual.global === expected.global && + actual.multiline === expected.multiline && + actual.lastIndex === expected.lastIndex && + actual.ignoreCase === expected.ignoreCase; + + // 7.4. Other pairs that do not both pass typeof value == 'object', + // equivalence is determined by ==. + } else if ((actual === null || typeof actual !== 'object') && + (expected === null || typeof expected !== 'object')) { + return strict ? actual === expected : actual == expected; + + // If both values are instances of typed arrays, wrap their underlying + // ArrayBuffers in a Buffer each to increase performance + // This optimization requires the arrays to have the same type as checked by + // Object.prototype.toString (aka pToString). Never perform binary + // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their + // bit patterns are not identical. + } else if (isView(actual) && isView(expected) && + pToString(actual) === pToString(expected) && + !(actual instanceof Float32Array || + actual instanceof Float64Array)) { + return compare(new Uint8Array(actual.buffer), + new Uint8Array(expected.buffer)) === 0; + + // 7.5 For all other Object pairs, including Array objects, equivalence is + // determined by having the same number of owned properties (as verified + // with Object.prototype.hasOwnProperty.call), the same set of keys + // (although not necessarily the same order), equivalent values for every + // corresponding key, and an identical 'prototype' property. Note: this + // accounts for both named and indexed properties on Arrays. + } else if (isBuffer$2(actual) !== isBuffer$2(expected)) { + return false; + } else { + memos = memos || {actual: [], expected: []}; + + var actualIndex = memos.actual.indexOf(actual); + if (actualIndex !== -1) { + if (actualIndex === memos.expected.indexOf(expected)) { + return true; + } + } + + memos.actual.push(actual); + memos.expected.push(expected); + + return objEquiv(actual, expected, strict, memos); + } + } + + function isArguments(object) { + return Object.prototype.toString.call(object) == '[object Arguments]'; + } + + function objEquiv(a, b, strict, actualVisitedObjects) { + if (a === null || a === undefined || b === null || b === undefined) + return false; + // if one is a primitive, the other must be same + if (isPrimitive(a) || isPrimitive(b)) + return a === b; + if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) + return false; + var aIsArgs = isArguments(a); + var bIsArgs = isArguments(b); + if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) + return false; + if (aIsArgs) { + a = pSlice.call(a); + b = pSlice.call(b); + return _deepEqual(a, b, strict); + } + var ka = objectKeys$1(a); + var kb = objectKeys$1(b); + var key, i; + // having the same number of owned properties (keys incorporates + // hasOwnProperty) + if (ka.length !== kb.length) + return false; + //the same set of keys (although not necessarily the same order), + ka.sort(); + kb.sort(); + //~~~cheap key test + for (i = ka.length - 1; i >= 0; i--) { + if (ka[i] !== kb[i]) + return false; + } + //equivalent values for every corresponding key, and + //~~~possibly expensive deep test + for (i = ka.length - 1; i >= 0; i--) { + key = ka[i]; + if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) + return false; + } + return true; + } + + // 8. The non-equivalence assertion tests for any deep inequality. + // assert.notDeepEqual(actual, expected, message_opt); + assert$a.notDeepEqual = notDeepEqual; + function notDeepEqual(actual, expected, message) { + if (_deepEqual(actual, expected, false)) { + fail$1(actual, expected, message, 'notDeepEqual', notDeepEqual); + } + } + + assert$a.notDeepStrictEqual = notDeepStrictEqual; + function notDeepStrictEqual(actual, expected, message) { + if (_deepEqual(actual, expected, true)) { + fail$1(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); + } + } + + + // 9. The strict equality assertion tests strict equality, as determined by ===. + // assert.strictEqual(actual, expected, message_opt); + assert$a.strictEqual = strictEqual; + function strictEqual(actual, expected, message) { + if (actual !== expected) { + fail$1(actual, expected, message, '===', strictEqual); + } + } + + // 10. The strict non-equality assertion tests for strict inequality, as + // determined by !==. assert.notStrictEqual(actual, expected, message_opt); + assert$a.notStrictEqual = notStrictEqual; + function notStrictEqual(actual, expected, message) { + if (actual === expected) { + fail$1(actual, expected, message, '!==', notStrictEqual); + } + } + + function expectedException(actual, expected) { + if (!actual || !expected) { + return false; + } + + if (Object.prototype.toString.call(expected) == '[object RegExp]') { + return expected.test(actual); + } + + try { + if (actual instanceof expected) { + return true; + } + } catch (e) { + // Ignore. The instanceof check doesn't work for arrow functions. + } + + if (Error.isPrototypeOf(expected)) { + return false; + } + + return expected.call({}, actual) === true; + } + + function _tryBlock(block) { + var error; + try { + block(); + } catch (e) { + error = e; + } + return error; + } + + function _throws(shouldThrow, block, expected, message) { + var actual; + + if (typeof block !== 'function') { + throw new TypeError('"block" argument must be a function'); + } + + if (typeof expected === 'string') { + message = expected; + expected = null; + } + + actual = _tryBlock(block); + + message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + + (message ? ' ' + message : '.'); + + if (shouldThrow && !actual) { + fail$1(actual, expected, 'Missing expected exception' + message); + } + + var userProvidedMessage = typeof message === 'string'; + var isUnwantedException = !shouldThrow && isError(actual); + var isUnexpectedException = !shouldThrow && actual && !expected; + + if ((isUnwantedException && + userProvidedMessage && + expectedException(actual, expected)) || + isUnexpectedException) { + fail$1(actual, expected, 'Got unwanted exception' + message); + } + + if ((shouldThrow && actual && expected && + !expectedException(actual, expected)) || (!shouldThrow && actual)) { + throw actual; + } + } + + // 11. Expected to throw an error: + // assert.throws(block, Error_opt, message_opt); + assert$a.throws = throws; + function throws(block, /*optional*/error, /*optional*/message) { + _throws(true, block, error, message); + } + + // EXTENSION! This is annoying to write outside this module. + assert$a.doesNotThrow = doesNotThrow; + function doesNotThrow(block, /*optional*/error, /*optional*/message) { + _throws(false, block, error, message); + } + + assert$a.ifError = ifError; + function ifError(err) { + if (err) throw err; + } + + var _polyfillNode_assert = /*#__PURE__*/Object.freeze({ + __proto__: null, + AssertionError: AssertionError, + assert: ok, + deepEqual: deepEqual, + deepStrictEqual: deepStrictEqual, + default: assert$a, + doesNotThrow: doesNotThrow, + equal: equal, + fail: fail$1, + ifError: ifError, + notDeepEqual: notDeepEqual, + notDeepStrictEqual: notDeepStrictEqual, + notEqual: notEqual, + notStrictEqual: notStrictEqual, + ok: ok, + strictEqual: strictEqual, + throws: throws + }); + + var require$$3$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_assert); + + var _polyfillNode_net = {}; + + var _polyfillNode_net$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + default: _polyfillNode_net + }); + + var require$$1$3 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_net$1); + + var hasFetch = isFunction(global$3.fetch) && isFunction(global$3.ReadableStream); + + var _blobConstructor; + function blobConstructor() { + if (typeof _blobConstructor !== 'undefined') { + return _blobConstructor; + } + try { + new global$3.Blob([new ArrayBuffer(1)]); + _blobConstructor = true; + } catch (e) { + _blobConstructor = false; + } + return _blobConstructor + } + var xhr; + + function checkTypeSupport(type) { + if (!xhr) { + xhr = new global$3.XMLHttpRequest(); + // If location.host is empty, e.g. if this page/worker was loaded + // from a Blob, then use example.com to avoid an error + xhr.open('GET', global$3.location.host ? '/' : 'https://example.com'); + } + try { + xhr.responseType = type; + return xhr.responseType === type + } catch (e) { + return false + } + + } + + // For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'. + // Safari 7.1 appears to have fixed this bug. + var haveArrayBuffer = typeof global$3.ArrayBuffer !== 'undefined'; + var haveSlice = haveArrayBuffer && isFunction(global$3.ArrayBuffer.prototype.slice); + + var arraybuffer = haveArrayBuffer && checkTypeSupport('arraybuffer'); + // These next two tests unavoidably show warnings in Chrome. Since fetch will always + // be used if it's available, just return false for these to avoid the warnings. + var msstream = !hasFetch && haveSlice && checkTypeSupport('ms-stream'); + var mozchunkedarraybuffer = !hasFetch && haveArrayBuffer && + checkTypeSupport('moz-chunked-arraybuffer'); + var overrideMimeType = isFunction(xhr.overrideMimeType); + var vbArray = isFunction(global$3.VBArray); + + function isFunction(value) { + return typeof value === 'function' + } + + xhr = null; // Help gc + + var domain; + + // This constructor is used to store event handlers. Instantiating this is + // faster than explicitly calling `Object.create(null)` to get a "clean" empty + // object (tested with v8 v4.9). + function EventHandlers() {} + EventHandlers.prototype = Object.create(null); + + function EventEmitter$1() { + EventEmitter$1.init.call(this); + } + + // nodejs oddity + // require('events') === require('events').EventEmitter + EventEmitter$1.EventEmitter = EventEmitter$1; + + EventEmitter$1.usingDomains = false; + + EventEmitter$1.prototype.domain = undefined; + EventEmitter$1.prototype._events = undefined; + EventEmitter$1.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + EventEmitter$1.defaultMaxListeners = 10; + + EventEmitter$1.init = function() { + this.domain = null; + if (EventEmitter$1.usingDomains) { + // if there is an active domain, then attach to it. + if (domain.active ) ; + } + + if (!this._events || this._events === Object.getPrototypeOf(this)._events) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter$1.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || isNaN(n)) + throw new TypeError('"n" argument must be a positive number'); + this._maxListeners = n; + return this; + }; + + function $getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter$1.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter$1.prototype.getMaxListeners = function getMaxListeners() { + return $getMaxListeners(this); + }; + + // These standalone emit* functions are used to optimize calling of event + // handlers for fast cases because emit() itself often has a variable number of + // arguments and can be deoptimized because of that. These functions always have + // the same number of arguments and thus do not get deoptimized, so the code + // inside them can execute faster. + function emitNone(handler, isFn, self) { + if (isFn) + handler.call(self); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self); + } + } + function emitOne(handler, isFn, self, arg1) { + if (isFn) + handler.call(self, arg1); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1); + } + } + function emitTwo(handler, isFn, self, arg1, arg2) { + if (isFn) + handler.call(self, arg1, arg2); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2); + } + } + function emitThree(handler, isFn, self, arg1, arg2, arg3) { + if (isFn) + handler.call(self, arg1, arg2, arg3); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].call(self, arg1, arg2, arg3); + } + } + + function emitMany(handler, isFn, self, args) { + if (isFn) + handler.apply(self, args); + else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + listeners[i].apply(self, args); + } + } + + EventEmitter$1.prototype.emit = function emit(type) { + var er, handler, len, args, i, events, domain; + var doError = (type === 'error'); + + events = this._events; + if (events) + doError = (doError && events.error == null); + else if (!doError) + return false; + + domain = this.domain; + + // If there is no 'error' event listener then throw. + if (doError) { + er = arguments[1]; + if (domain) { + if (!er) + er = new Error('Uncaught, unspecified "error" event'); + er.domainEmitter = this; + er.domain = domain; + er.domainThrown = false; + domain.emit('error', er); + } else if (er instanceof Error) { + throw er; // Unhandled 'error' event + } else { + // At least give some kind of context to the user + var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); + err.context = er; + throw err; + } + return false; + } + + handler = events[type]; + + if (!handler) + return false; + + var isFn = typeof handler === 'function'; + len = arguments.length; + switch (len) { + // fast cases + case 1: + emitNone(handler, isFn, this); + break; + case 2: + emitOne(handler, isFn, this, arguments[1]); + break; + case 3: + emitTwo(handler, isFn, this, arguments[1], arguments[2]); + break; + case 4: + emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]); + break; + // slower + default: + args = new Array(len - 1); + for (i = 1; i < len; i++) + args[i - 1] = arguments[i]; + emitMany(handler, isFn, this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = target._events; + if (!events) { + events = target._events = new EventHandlers(); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (!existing) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = prepend ? [listener, existing] : + [existing, listener]; + } else { + // If we've already got an array, just append. + if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + } + + // Check for listener leak + if (!existing.warned) { + m = $getMaxListeners(target); + if (m && m > 0 && existing.length > m) { + existing.warned = true; + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + type + ' listeners added. ' + + 'Use emitter.setMaxListeners() to increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + emitWarning(w); + } + } + } + + return target; + } + function emitWarning(e) { + typeof console.warn === 'function' ? console.warn(e) : console.log(e); + } + EventEmitter$1.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter$1.prototype.on = EventEmitter$1.prototype.addListener; + + EventEmitter$1.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function _onceWrap(target, type, listener) { + var fired = false; + function g() { + target.removeListener(type, g); + if (!fired) { + fired = true; + listener.apply(target, arguments); + } + } + g.listener = listener; + return g; + } + + EventEmitter$1.prototype.once = function once(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter$1.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // emits a 'removeListener' event iff the listener was removed + EventEmitter$1.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + if (typeof listener !== 'function') + throw new TypeError('"listener" argument must be a function'); + + events = this._events; + if (!events) + return this; + + list = events[type]; + if (!list) + return this; + + if (list === listener || (list.listener && list.listener === listener)) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length; i-- > 0;) { + if (list[i] === listener || + (list[i].listener && list[i].listener === listener)) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (list.length === 1) { + list[0] = undefined; + if (--this._eventsCount === 0) { + this._events = new EventHandlers(); + return this; + } else { + delete events[type]; + } + } else { + spliceOne(list, position); + } + + if (events.removeListener) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + // Alias for removeListener added in NodeJS 10.0 + // https://nodejs.org/api/events.html#events_emitter_off_eventname_listener + EventEmitter$1.prototype.off = function(type, listener){ + return this.removeListener(type, listener); + }; + + EventEmitter$1.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events; + + events = this._events; + if (!events) + return this; + + // not listening for removeListener, no need to emit + if (!events.removeListener) { + if (arguments.length === 0) { + this._events = new EventHandlers(); + this._eventsCount = 0; + } else if (events[type]) { + if (--this._eventsCount === 0) + this._events = new EventHandlers(); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + for (var i = 0, key; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = new EventHandlers(); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners) { + // LIFO order + do { + this.removeListener(type, listeners[listeners.length - 1]); + } while (listeners[0]); + } + + return this; + }; + + EventEmitter$1.prototype.listeners = function listeners(type) { + var evlistener; + var ret; + var events = this._events; + + if (!events) + ret = []; + else { + evlistener = events[type]; + if (!evlistener) + ret = []; + else if (typeof evlistener === 'function') + ret = [evlistener.listener || evlistener]; + else + ret = unwrapListeners(evlistener); + } + + return ret; + }; + + EventEmitter$1.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount$1.call(emitter, type); + } + }; + + EventEmitter$1.prototype.listenerCount = listenerCount$1; + function listenerCount$1(type) { + var events = this._events; + + if (events) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter$1.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : []; + }; + + // About 1.5x faster than the two-arg version of Array#splice(). + function spliceOne(list, index) { + for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1) + list[i] = list[k]; + list.pop(); + } + + function arrayClone(arr, i) { + var copy = new Array(i); + while (i--) + copy[i] = arr[i]; + return copy; + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + var _polyfillNode_events = /*#__PURE__*/Object.freeze({ + __proto__: null, + EventEmitter: EventEmitter$1, + default: EventEmitter$1 + }); + + function BufferList() { + this.head = null; + this.tail = null; + this.length = 0; + } + + BufferList.prototype.push = function (v) { + var entry = { data: v, next: null }; + if (this.length > 0) this.tail.next = entry;else this.head = entry; + this.tail = entry; + ++this.length; + }; + + BufferList.prototype.unshift = function (v) { + var entry = { data: v, next: this.head }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + }; + + BufferList.prototype.shift = function () { + 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; + }; + + BufferList.prototype.clear = function () { + this.head = this.tail = null; + this.length = 0; + }; + + BufferList.prototype.join = function (s) { + if (this.length === 0) return ''; + var p = this.head; + var ret = '' + p.data; + while (p = p.next) { + ret += s + p.data; + }return ret; + }; + + BufferList.prototype.concat = function (n) { + if (this.length === 0) return Buffer.alloc(0); + if (this.length === 1) return this.head.data; + var ret = Buffer.allocUnsafe(n >>> 0); + var p = this.head; + var i = 0; + while (p) { + p.data.copy(ret, i); + i += p.data.length; + p = p.next; + } + return ret; + }; + + // 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 isBufferEncoding = Buffer.isEncoding + || function(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; + } + }; + + + function assertEncoding(encoding) { + if (encoding && !isBufferEncoding(encoding)) { + throw new Error('Unknown encoding: ' + encoding); + } + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. CESU-8 is handled as part of the UTF-8 encoding. + // + // @TODO Handling all encodings inside a single object makes it very difficult + // to reason about this code, so it should be split up in the future. + // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code + // points as used by CESU-8. + function StringDecoder(encoding) { + this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); + assertEncoding(encoding); + switch (this.encoding) { + case 'utf8': + // CESU-8 represents each of Surrogate Pair by 3-bytes + this.surrogateSize = 3; + break; + case 'ucs2': + case 'utf16le': + // UTF-16 represents each of Surrogate Pair by 2-bytes + this.surrogateSize = 2; + this.detectIncompleteChar = utf16DetectIncompleteChar; + break; + case 'base64': + // Base-64 stores 3 bytes in 4 chars, and pads the remainder. + this.surrogateSize = 3; + this.detectIncompleteChar = base64DetectIncompleteChar; + break; + default: + this.write = passThroughWrite; + return; + } + + // Enough space to store all bytes of a single character. UTF-8 needs 4 + // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). + this.charBuffer = new Buffer(6); + // Number of bytes received for the current incomplete multi-byte character. + this.charReceived = 0; + // Number of bytes expected for the current incomplete multi-byte character. + this.charLength = 0; + } + + // write decodes the given buffer and returns it as JS string that is + // guaranteed to not contain any partial multi-byte characters. Any partial + // character found at the end of the buffer is buffered up, and will be + // returned when calling write again with the remaining bytes. + // + // Note: Converting a Buffer containing an orphan surrogate to a String + // currently works, but converting a String to a Buffer (via `new Buffer`, or + // Buffer#write) will replace incomplete surrogates with the unicode + // replacement character. See https://codereview.chromium.org/121173009/ . + StringDecoder.prototype.write = function(buffer) { + var charStr = ''; + // if our last write ended with an incomplete multibyte character + while (this.charLength) { + // determine how many remaining bytes this buffer has to offer for this char + var available = (buffer.length >= this.charLength - this.charReceived) ? + this.charLength - this.charReceived : + buffer.length; + + // add the new bytes to the char buffer + buffer.copy(this.charBuffer, this.charReceived, 0, available); + this.charReceived += available; + + if (this.charReceived < this.charLength) { + // still not enough chars in this buffer? wait for more ... + return ''; + } + + // remove bytes belonging to the current character from the buffer + buffer = buffer.slice(available, buffer.length); + + // get the character that was split + charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); + + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + var charCode = charStr.charCodeAt(charStr.length - 1); + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + this.charLength += this.surrogateSize; + charStr = ''; + continue; + } + this.charReceived = this.charLength = 0; + + // if there are no more bytes in this buffer, just emit our char + if (buffer.length === 0) { + return charStr; + } + break; + } + + // determine and set charLength / charReceived + this.detectIncompleteChar(buffer); + + var end = buffer.length; + if (this.charLength) { + // buffer the incomplete character bytes we got + buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); + end -= this.charReceived; + } + + charStr += buffer.toString(this.encoding, 0, end); + + var end = charStr.length - 1; + var charCode = charStr.charCodeAt(end); + // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character + if (charCode >= 0xD800 && charCode <= 0xDBFF) { + var size = this.surrogateSize; + this.charLength += size; + this.charReceived += size; + this.charBuffer.copy(this.charBuffer, size, 0, size); + buffer.copy(this.charBuffer, 0, 0, size); + return charStr.substring(0, end); + } + + // or just emit the charStr + return charStr; + }; + + // detectIncompleteChar determines if there is an incomplete UTF-8 character at + // the end of the given buffer. If so, it sets this.charLength to the byte + // length that character, and sets this.charReceived to the number of bytes + // that are available for this character. + StringDecoder.prototype.detectIncompleteChar = function(buffer) { + // determine how many bytes we have to check at the end of this buffer + var i = (buffer.length >= 3) ? 3 : buffer.length; + + // Figure out if one of the last i bytes of our buffer announces an + // incomplete char. + for (; i > 0; i--) { + var c = buffer[buffer.length - i]; + + // See http://en.wikipedia.org/wiki/UTF-8#Description + + // 110XXXXX + if (i == 1 && c >> 5 == 0x06) { + this.charLength = 2; + break; + } + + // 1110XXXX + if (i <= 2 && c >> 4 == 0x0E) { + this.charLength = 3; + break; + } + + // 11110XXX + if (i <= 3 && c >> 3 == 0x1E) { + this.charLength = 4; + break; + } + } + this.charReceived = i; + }; + + StringDecoder.prototype.end = function(buffer) { + var res = ''; + if (buffer && buffer.length) + res = this.write(buffer); + + if (this.charReceived) { + var cr = this.charReceived; + var buf = this.charBuffer; + var enc = this.encoding; + res += buf.slice(0, cr).toString(enc); + } + + return res; + }; + + function passThroughWrite(buffer) { + return buffer.toString(this.encoding); + } + + function utf16DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 2; + this.charLength = this.charReceived ? 2 : 0; + } + + function base64DetectIncompleteChar(buffer) { + this.charReceived = buffer.length % 3; + this.charLength = this.charReceived ? 3 : 0; + } + + var _polyfillNode_string_decoder = /*#__PURE__*/Object.freeze({ + __proto__: null, + StringDecoder: StringDecoder + }); + + Readable$3.ReadableState = ReadableState; + + var debug = debuglog('stream'); + inherits$1(Readable$3, EventEmitter$1); + + 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); + } else { + // 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 listenerCount (emitter, type) { + return emitter.listeners(type).length; + } + function ReadableState(options, stream) { + + options = options || {}; + + // 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 (stream instanceof Duplex$1) this.objectMode = this.objectMode || !!options.readableObjectMode; + + // 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 defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + // 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; + + // 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; + + // 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; + + // 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'; + + // when piping, we only care about 'readable' events that happen + // after read()ing all the bytes and not getting any pushback. + this.ranOut = false; + + // the number of writers that are awaiting a drain event in .pipe()s + this.awaitDrain = 0; + + // if true, a maybeReadMore has been scheduled + this.readingMore = false; + + this.decoder = null; + this.encoding = null; + if (options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable$3(options) { + + if (!(this instanceof Readable$3)) return new Readable$3(options); + + this._readableState = new ReadableState(options, this); + + // legacy + this.readable = true; + + if (options && typeof options.read === 'function') this._read = options.read; + + EventEmitter$1.call(this); + } + + // 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$3.prototype.push = function (chunk, encoding) { + var state = this._readableState; + + if (!state.objectMode && typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (encoding !== state.encoding) { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + + return readableAddChunk(this, state, chunk, encoding, false); + }; + + // Unshift should *always* be something directly out of read() + Readable$3.prototype.unshift = function (chunk) { + var state = this._readableState; + return readableAddChunk(this, state, chunk, '', true); + }; + + Readable$3.prototype.isPaused = function () { + return this._readableState.flowing === false; + }; + + function readableAddChunk(stream, state, chunk, encoding, addToFront) { + var er = chunkInvalid(state, chunk); + if (er) { + stream.emit('error', er); + } else if (chunk === null) { + state.reading = false; + onEofChunk(stream, state); + } else if (state.objectMode || chunk && chunk.length > 0) { + if (state.ended && !addToFront) { + var e = new Error('stream.push() after EOF'); + stream.emit('error', e); + } else if (state.endEmitted && addToFront) { + var _e = new Error('stream.unshift() after end event'); + stream.emit('error', _e); + } else { + var skipAdd; + if (state.decoder && !addToFront && !encoding) { + chunk = state.decoder.write(chunk); + skipAdd = !state.objectMode && chunk.length === 0; + } + + if (!addToFront) state.reading = false; + + // Don't add to the buffer if we've decoded to an empty string chunk and + // we're not in object mode + if (!skipAdd) { + // if we want the data now, just emit it. + 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); + } + } else if (!addToFront) { + state.reading = false; + } + + return needMoreData(state); + } + + // 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); + } + + // backwards compatibility. + Readable$3.prototype.setEncoding = function (enc) { + 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; + } + + // 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$3.prototype.read = function (n) { + debug('read', n); + n = parseInt(n, 10); + var state = this._readableState; + var nOrig = n; + + if (n !== 0) state.emittedReadable = false; + + // 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; + } + + // 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. + var doRead = state.needReadable; + 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); + } + + // 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; + + if (ret === null) { + state.needReadable = true; + n = 0; + } else { + state.length -= n; + } + + 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; + + // 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) this.emit('data', ret); + + return ret; + }; + + function chunkInvalid(state, chunk) { + var er = null; + if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== null && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + return er; + } + + 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; + + // emit 'readable' now to make sure it gets picked up. + emitReadable(stream); + } + + // 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) nextTick(emitReadable_, stream);else emitReadable_(stream); + } + } + + 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; + 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$3.prototype._read = function (n) { + this.emit('error', new Error('not implemented')); + }; + + Readable$3.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); + + var endFn = doEnd ? onend : cleanup; + if (state.endEmitted) nextTick(endFn);else src.once('end', endFn); + + dest.on('unpipe', onunpipe); + function onunpipe(readable) { + debug('onunpipe'); + if (readable === src) { + cleanup(); + } + } + + 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', cleanup); + 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', src._readableState.awaitDrain); + src._readableState.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 (listenerCount(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 && src.listeners('data').length) { + state.flowing = true; + flow(src); + } + }; + } + + Readable$3.prototype.unpipe = function (dest) { + var state = this._readableState; + + // if we're not piping anywhere, then do nothing. + if (state.pipesCount === 0) return this; + + // 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 (!dest) dest = state.pipes; + + // got a match. + state.pipes = null; + state.pipesCount = 0; + state.flowing = false; + if (dest) dest.emit('unpipe', this); + 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); + }return this; + } + + // try to find the right one. + var i = indexOf(state.pipes, dest); + if (i === -1) return this; + + state.pipes.splice(i, 1); + state.pipesCount -= 1; + if (state.pipesCount === 1) state.pipes = state.pipes[0]; + + dest.emit('unpipe', this); + + return this; + }; + + // set up data events if they are asked for + // Ensure readable listeners eventually get something + Readable$3.prototype.on = function (ev, fn) { + var res = EventEmitter$1.prototype.on.call(this, ev, fn); + + 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) { + nextTick(nReadingNextTick, this); + } else if (state.length) { + emitReadable(this); + } + } + } + + return res; + }; + Readable$3.prototype.addListener = Readable$3.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$3.prototype.resume = function () { + var state = this._readableState; + if (!state.flowing) { + debug('resume'); + state.flowing = true; + resume$1(this, state); + } + return this; + }; + + function resume$1(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + 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); + } + + Readable$3.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) {} + } + + // 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$3.prototype.wrap = function (stream) { + var state = this._readableState; + var paused = false; + + var self = this; + stream.on('end', function () { + debug('wrapped end'); + if (state.decoder && !state.ended) { + var chunk = state.decoder.end(); + if (chunk && chunk.length) self.push(chunk); + } + + self.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 = self.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. + var events = ['error', 'close', 'destroy', 'pause', 'resume']; + forEach$1(events, function (ev) { + stream.on(ev, self.emit.bind(self, ev)); + }); + + // when we try to consume some more bytes, simply unpause the + // underlying stream. + self._read = function (n) { + debug('wrapped _read', n); + if (paused) { + paused = false; + stream.resume(); + } + }; + + return self; + }; + + // exposed for testing purposes only. + Readable$3._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; + } + + // 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; + } + + // 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; + } + + // 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; + } + + function endReadable(stream) { + var state = stream._readableState; + + // 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; + 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'); + } + } + + function forEach$1(xs, f) { + for (var i = 0, l = xs.length; i < l; i++) { + f(xs[i], i); + } + } + + function indexOf(xs, x) { + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) return i; + } + return -1; + } + + // A bit simpler than readable streams. + // Implement an async ._write(chunk, encoding, cb), and it'll handle all + // the drain event emission and buffering. + + Writable.WritableState = WritableState; + inherits$1(Writable, EventEmitter$1); + + function nop$2() {} + + function WriteReq(chunk, encoding, cb) { + this.chunk = chunk; + this.encoding = encoding; + this.callback = cb; + this.next = null; + } + + function WritableState(options, stream) { + Object.defineProperty(this, 'buffer', { + get: deprecate(function () { + return this.getBuffer(); + }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.') + }); + options = options || {}; + + // object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!options.objectMode; + + if (stream instanceof Duplex$1) this.objectMode = this.objectMode || !!options.writableObjectMode; + + // 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 defaultHwm = this.objectMode ? 16 : 16 * 1024; + this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; + + // cast to ints. + this.highWaterMark = ~ ~this.highWaterMark; + + 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; + + // 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'; + + // 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; + + // a flag to see when we're in the middle of a write. + this.writing = false; + + // when true all writes will be buffered until .uncork() call + this.corked = 0; + + // 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); + }; + + // the callback that the user supplies to write(chunk,encoding,cb) + this.writecb = null; + + // the amount that is being written when _write is called. + this.writelen = 0; + + this.bufferedRequest = null; + this.lastBufferedRequest = null; + + // 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; + + // count buffered requests + this.bufferedRequestCount = 0; + + // 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 writableStateGetBuffer() { + var current = this.bufferedRequest; + var out = []; + while (current) { + out.push(current); + current = current.next; + } + return out; + }; + function Writable(options) { + + // Writable ctor is applied to Duplexes, though they're not + // instanceof Writable, they're instanceof Readable. + if (!(this instanceof Writable) && !(this instanceof Duplex$1)) return new Writable(options); + + this._writableState = new WritableState(options, this); + + // legacy. + this.writable = true; + + if (options) { + if (typeof options.write === 'function') this._write = options.write; + + if (typeof options.writev === 'function') this._writev = options.writev; + } + + EventEmitter$1.call(this); + } + + // 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); + nextTick(cb, er); + } + + // If we get something that is not a buffer, string, null, or undefined, + // and we're not in objectMode, then that's an error. + // Otherwise stream chunks are all considered to be of length=1, and the + // watermarks determine how many objects to keep in the buffer, rather than + // how many bytes or characters. + function validChunk(stream, state, chunk, cb) { + var valid = true; + var er = false; + // Always throw error if a null is written + // if we are not in object mode then throw + // if it is not a buffer, string, or undefined. + if (chunk === null) { + er = new TypeError('May not write null values to stream'); + } else if (!Buffer.isBuffer(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { + er = new TypeError('Invalid non-string/buffer chunk'); + } + if (er) { + stream.emit('error', er); + nextTick(cb, er); + valid = false; + } + return valid; + } + + Writable.prototype.write = function (chunk, encoding, cb) { + var state = this._writableState; + var ret = false; + + if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + + if (Buffer.isBuffer(chunk)) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; + + if (typeof cb !== 'function') cb = nop$2; + + if (state.ended) writeAfterEnd(this, cb);else if (validChunk(this, state, chunk, cb)) { + state.pendingcb++; + ret = writeOrBuffer(this, state, chunk, encoding, cb); + } + + return ret; + }; + + Writable.prototype.cork = function () { + var state = this._writableState; + + state.corked++; + }; + + Writable.prototype.uncork = function () { + var state = this._writableState; + + if (state.corked) { + state.corked--; + + if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); + } + }; + + 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 decodeChunk(state, chunk, encoding) { + if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { + chunk = Buffer.from(chunk, encoding); + } + return chunk; + } + + // 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, cb) { + chunk = decodeChunk(state, chunk, encoding); + + if (Buffer.isBuffer(chunk)) encoding = 'buffer'; + var len = state.objectMode ? 1 : chunk.length; + + state.length += len; + + 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 = new WriteReq(chunk, encoding, cb); + 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; + if (sync) nextTick(cb, er);else cb(er); + + stream._writableState.errorEmitted = true; + stream.emit('error', er); + } + + function onwriteStateUpdate(state) { + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + } + + 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); + + if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { + clearBuffer(stream, state); + } + + if (sync) { + /**/ + nextTick(afterWrite, stream, state, finished, cb); + /**/ + } else { + afterWrite(stream, state, finished, cb); + } + } + } + + function afterWrite(stream, state, finished, cb) { + if (!finished) onwriteDrain(stream, state); + state.pendingcb--; + cb(); + finishMaybe(stream, state); + } + + // 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 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; + while (entry) { + buffer[count] = entry; + entry = entry.next; + count += 1; + } + + doWrite(stream, state, true, state.length, buffer, '', holder.finish); + + // 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); + } + } 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; + // 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; + } + + state.bufferedRequestCount = 0; + state.bufferedRequest = entry; + state.bufferProcessing = false; + } + + Writable.prototype._write = function (chunk, encoding, cb) { + cb(new Error('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); + + // .end() fully uncorks + if (state.corked) { + state.corked = 1; + this.uncork(); + } + + // ignore unnecessary end() calls. + if (!state.ending && !state.finished) endWritable(this, state, cb); + }; + + function needFinish(state) { + return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; + } + + function prefinish(stream, state) { + if (!state.prefinished) { + state.prefinished = true; + stream.emit('prefinish'); + } + } + + function finishMaybe(stream, state) { + var need = needFinish(state); + if (need) { + if (state.pendingcb === 0) { + prefinish(stream, state); + state.finished = true; + stream.emit('finish'); + } else { + prefinish(stream, state); + } + } + return need; + } + + function endWritable(stream, state, cb) { + state.ending = true; + finishMaybe(stream, state); + if (cb) { + if (state.finished) nextTick(cb);else stream.once('finish', cb); + } + state.ended = true; + stream.writable = 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; + + this.next = null; + this.entry = null; + + this.finish = function (err) { + var entry = _this.entry; + _this.entry = null; + while (entry) { + var cb = entry.callback; + state.pendingcb--; + cb(err); + entry = entry.next; + } + if (state.corkedRequestsFree) { + state.corkedRequestsFree.next = _this; + } else { + state.corkedRequestsFree = _this; + } + }; + } + + inherits$1(Duplex$1, Readable$3); + + var keys = Object.keys(Writable.prototype); + for (var v = 0; v < keys.length; v++) { + var method = keys[v]; + if (!Duplex$1.prototype[method]) Duplex$1.prototype[method] = Writable.prototype[method]; + } + function Duplex$1(options) { + if (!(this instanceof Duplex$1)) return new Duplex$1(options); + + Readable$3.call(this, options); + Writable.call(this, options); + + if (options && options.readable === false) this.readable = false; + + if (options && options.writable === false) this.writable = false; + + this.allowHalfOpen = true; + if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; + + this.once('end', onend); + } + + // 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; + + // no more data can be written. + // But allow more writes to happen in this tick. + nextTick(onEndNT, this); + } + + function onEndNT(self) { + self.end(); + } + + // 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. + + inherits$1(Transform$1, Duplex$1); + + function TransformState(stream) { + this.afterTransform = function (er, data) { + return afterTransform(stream, er, data); + }; + + this.needTransform = false; + this.transforming = false; + this.writecb = null; + this.writechunk = null; + this.writeencoding = null; + } + + function afterTransform(stream, er, data) { + var ts = stream._transformState; + ts.transforming = false; + + var cb = ts.writecb; + + if (!cb) return stream.emit('error', new Error('no writecb in Transform class')); + + ts.writechunk = null; + ts.writecb = null; + + if (data !== null && data !== undefined) stream.push(data); + + cb(er); + + var rs = stream._readableState; + rs.reading = false; + if (rs.needReadable || rs.length < rs.highWaterMark) { + stream._read(rs.highWaterMark); + } + } + function Transform$1(options) { + if (!(this instanceof Transform$1)) return new Transform$1(options); + + Duplex$1.call(this, options); + + this._transformState = new TransformState(this); + + // when the writable side finishes, then flush out anything remaining. + var stream = this; + + // 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; + + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + + if (typeof options.flush === 'function') this._flush = options.flush; + } + + this.once('prefinish', function () { + if (typeof this._flush === 'function') this._flush(function (er) { + done(stream, er); + });else done(stream); + }); + } + + Transform$1.prototype.push = function (chunk, encoding) { + this._transformState.needTransform = false; + return Duplex$1.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$1.prototype._transform = function (chunk, encoding, cb) { + throw new Error('Not implemented'); + }; + + Transform$1.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); + } + }; + + // 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$1.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; + } + }; + + function done(stream, er) { + if (er) return stream.emit('error', er); + + // if there's nothing in the write buffer, then that means + // that nothing more will ever be provided + var ws = stream._writableState; + var ts = stream._transformState; + + if (ws.length) throw new Error('Calling transform done when ws.length != 0'); + + if (ts.transforming) throw new Error('Calling transform done when still transforming'); + + return stream.push(null); + } + + inherits$1(PassThrough$2, Transform$1); + function PassThrough$2(options) { + if (!(this instanceof PassThrough$2)) return new PassThrough$2(options); + + Transform$1.call(this, options); + } + + PassThrough$2.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + + inherits$1(Stream, EventEmitter$1); + Stream.Readable = Readable$3; + Stream.Writable = Writable; + Stream.Duplex = Duplex$1; + Stream.Transform = Transform$1; + Stream.PassThrough = PassThrough$2; + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + + // old-style streams. Note that the pipe method (the only relevant + // part of this class) is overridden in the Readable class. + + function Stream() { + EventEmitter$1.call(this); + } + + Stream.prototype.pipe = function(dest, options) { + var source = this; + + function ondata(chunk) { + if (dest.writable) { + if (false === dest.write(chunk) && source.pause) { + source.pause(); + } + } + } + + source.on('data', ondata); + + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + + dest.on('drain', ondrain); + + // 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); + } + + var 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 (EventEmitter$1.listenerCount(this, 'error') === 0) { + throw er; // Unhandled stream error in pipe. + } + } + + source.on('error', onerror); + dest.on('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; + }; + + var _polyfillNode_stream = /*#__PURE__*/Object.freeze({ + __proto__: null, + Duplex: Duplex$1, + PassThrough: PassThrough$2, + Readable: Readable$3, + Stream: Stream, + Transform: Transform$1, + Writable: Writable, + default: Stream + }); + + var rStates = { + UNSENT: 0, + OPENED: 1, + HEADERS_RECEIVED: 2, + LOADING: 3, + DONE: 4 + }; + function IncomingMessage$1(xhr, response, mode) { + var self = this; + Readable$3.call(self); + + self._mode = mode; + self.headers = {}; + self.rawHeaders = []; + self.trailers = {}; + self.rawTrailers = []; + + // Fake the 'close' event, but only once 'end' fires + self.on('end', function() { + // The nextTick is necessary to prevent the 'request' module from causing an infinite loop + browser$1$1.nextTick(function() { + self.emit('close'); + }); + }); + var read; + if (mode === 'fetch') { + self._fetchResponse = response; + + self.url = response.url; + self.statusCode = response.status; + self.statusMessage = response.statusText; + // backwards compatible version of for ( of ): + // for (var ,_i,_it = [Symbol.iterator](); = (_i = _it.next()).value,!_i.done;) + for (var header, _i, _it = response.headers[Symbol.iterator](); header = (_i = _it.next()).value, !_i.done;) { + self.headers[header[0].toLowerCase()] = header[1]; + self.rawHeaders.push(header[0], header[1]); + } + + // TODO: this doesn't respect backpressure. Once WritableStream is available, this can be fixed + var reader = response.body.getReader(); + + read = function () { + reader.read().then(function(result) { + if (self._destroyed) + return + if (result.done) { + self.push(null); + return + } + self.push(new Buffer(result.value)); + read(); + }); + }; + read(); + + } else { + self._xhr = xhr; + self._pos = 0; + + self.url = xhr.responseURL; + self.statusCode = xhr.status; + self.statusMessage = xhr.statusText; + var headers = xhr.getAllResponseHeaders().split(/\r?\n/); + headers.forEach(function(header) { + var matches = header.match(/^([^:]+):\s*(.*)/); + if (matches) { + var key = matches[1].toLowerCase(); + if (key === 'set-cookie') { + if (self.headers[key] === undefined) { + self.headers[key] = []; + } + self.headers[key].push(matches[2]); + } else if (self.headers[key] !== undefined) { + self.headers[key] += ', ' + matches[2]; + } else { + self.headers[key] = matches[2]; + } + self.rawHeaders.push(matches[1], matches[2]); + } + }); + + self._charset = 'x-user-defined'; + if (!overrideMimeType) { + var mimeType = self.rawHeaders['mime-type']; + if (mimeType) { + var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/); + if (charsetMatch) { + self._charset = charsetMatch[1].toLowerCase(); + } + } + if (!self._charset) + self._charset = 'utf-8'; // best guess + } + } + } + + inherits$1(IncomingMessage$1, Readable$3); + + IncomingMessage$1.prototype._read = function() {}; + + IncomingMessage$1.prototype._onXHRProgress = function() { + var self = this; + + var xhr = self._xhr; + + var response = null; + switch (self._mode) { + case 'text:vbarray': // For IE9 + if (xhr.readyState !== rStates.DONE) + break + try { + // This fails in IE8 + response = new global$3.VBArray(xhr.responseBody).toArray(); + } catch (e) { + // pass + } + if (response !== null) { + self.push(new Buffer(response)); + break + } + // Falls through in IE8 + case 'text': + try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4 + response = xhr.responseText; + } catch (e) { + self._mode = 'text:vbarray'; + break + } + if (response.length > self._pos) { + var newData = response.substr(self._pos); + if (self._charset === 'x-user-defined') { + var buffer = new Buffer(newData.length); + for (var i = 0; i < newData.length; i++) + buffer[i] = newData.charCodeAt(i) & 0xff; + + self.push(buffer); + } else { + self.push(newData, self._charset); + } + self._pos = response.length; + } + break + case 'arraybuffer': + if (xhr.readyState !== rStates.DONE || !xhr.response) + break + response = xhr.response; + self.push(new Buffer(new Uint8Array(response))); + break + case 'moz-chunked-arraybuffer': // take whole + response = xhr.response; + if (xhr.readyState !== rStates.LOADING || !response) + break + self.push(new Buffer(new Uint8Array(response))); + break + case 'ms-stream': + response = xhr.response; + if (xhr.readyState !== rStates.LOADING) + break + var reader = new global$3.MSStreamReader(); + reader.onprogress = function() { + if (reader.result.byteLength > self._pos) { + self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos)))); + self._pos = reader.result.byteLength; + } + }; + reader.onload = function() { + self.push(null); + }; + // reader.onerror = ??? // TODO: this + reader.readAsArrayBuffer(response); + break + } + + // The ms-stream case handles end separately in reader.onload() + if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') { + self.push(null); + } + }; + + // from https://github.com/jhiesey/to-arraybuffer/blob/6502d9850e70ba7935a7df4ad86b358fc216f9f0/index.js + + function toArrayBuffer (buf) { + // If the buffer is backed by a Uint8Array, a faster version will work + if (buf instanceof Uint8Array) { + // If the buffer isn't a subarray, return the underlying ArrayBuffer + if (buf.byteOffset === 0 && buf.byteLength === buf.buffer.byteLength) { + return buf.buffer + } else if (typeof buf.buffer.slice === 'function') { + // Otherwise we need to get a proper copy + return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength) + } + } + + if (isBuffer$2(buf)) { + // This is the slow version that will work with any Buffer + // implementation (even in old browsers) + var arrayCopy = new Uint8Array(buf.length); + var len = buf.length; + for (var i = 0; i < len; i++) { + arrayCopy[i] = buf[i]; + } + return arrayCopy.buffer + } else { + throw new Error('Argument must be a Buffer') + } + } + + function decideMode(preferBinary, useFetch) { + if (hasFetch && useFetch) { + return 'fetch' + } else if (mozchunkedarraybuffer) { + return 'moz-chunked-arraybuffer' + } else if (msstream) { + return 'ms-stream' + } else if (arraybuffer && preferBinary) { + return 'arraybuffer' + } else if (vbArray && preferBinary) { + return 'text:vbarray' + } else { + return 'text' + } + } + + function ClientRequest(opts) { + var self = this; + Writable.call(self); + + self._opts = opts; + self._body = []; + self._headers = {}; + if (opts.auth) + self.setHeader('Authorization', 'Basic ' + new Buffer(opts.auth).toString('base64')); + Object.keys(opts.headers).forEach(function(name) { + self.setHeader(name, opts.headers[name]); + }); + + var preferBinary; + var useFetch = true; + if (opts.mode === 'disable-fetch') { + // If the use of XHR should be preferred and includes preserving the 'content-type' header + useFetch = false; + preferBinary = true; + } else if (opts.mode === 'prefer-streaming') { + // If streaming is a high priority but binary compatibility and + // the accuracy of the 'content-type' header aren't + preferBinary = false; + } else if (opts.mode === 'allow-wrong-content-type') { + // If streaming is more important than preserving the 'content-type' header + preferBinary = !overrideMimeType; + } else if (!opts.mode || opts.mode === 'default' || opts.mode === 'prefer-fast') { + // Use binary if text streaming may corrupt data or the content-type header, or for speed + preferBinary = true; + } else { + throw new Error('Invalid value for opts.mode') + } + self._mode = decideMode(preferBinary, useFetch); + + self.on('finish', function() { + self._onFinish(); + }); + } + + inherits$1(ClientRequest, Writable); + // Taken from http://www.w3.org/TR/XMLHttpRequest/#the-setrequestheader%28%29-method + var unsafeHeaders = [ + 'accept-charset', + 'accept-encoding', + 'access-control-request-headers', + 'access-control-request-method', + 'connection', + 'content-length', + 'cookie', + 'cookie2', + 'date', + 'dnt', + 'expect', + 'host', + 'keep-alive', + 'origin', + 'referer', + 'te', + 'trailer', + 'transfer-encoding', + 'upgrade', + 'user-agent', + 'via' + ]; + ClientRequest.prototype.setHeader = function(name, value) { + var self = this; + var lowerName = name.toLowerCase(); + // This check is not necessary, but it prevents warnings from browsers about setting unsafe + // headers. To be honest I'm not entirely sure hiding these warnings is a good thing, but + // http-browserify did it, so I will too. + if (unsafeHeaders.indexOf(lowerName) !== -1) + return + + self._headers[lowerName] = { + name: name, + value: value + }; + }; + + ClientRequest.prototype.getHeader = function(name) { + var self = this; + return self._headers[name.toLowerCase()].value + }; + + ClientRequest.prototype.removeHeader = function(name) { + var self = this; + delete self._headers[name.toLowerCase()]; + }; + + ClientRequest.prototype._onFinish = function() { + var self = this; + + if (self._destroyed) + return + var opts = self._opts; + + var headersObj = self._headers; + var body; + if (opts.method === 'POST' || opts.method === 'PUT' || opts.method === 'PATCH') { + if (blobConstructor()) { + body = new global$3.Blob(self._body.map(function(buffer) { + return toArrayBuffer(buffer) + }), { + type: (headersObj['content-type'] || {}).value || '' + }); + } else { + // get utf8 string + body = Buffer.concat(self._body).toString(); + } + } + + if (self._mode === 'fetch') { + var headers = Object.keys(headersObj).map(function(name) { + return [headersObj[name].name, headersObj[name].value] + }); + + global$3.fetch(self._opts.url, { + method: self._opts.method, + headers: headers, + body: body, + mode: 'cors', + credentials: opts.withCredentials ? 'include' : 'same-origin' + }).then(function(response) { + self._fetchResponse = response; + self._connect(); + }, function(reason) { + self.emit('error', reason); + }); + } else { + var xhr = self._xhr = new global$3.XMLHttpRequest(); + try { + xhr.open(self._opts.method, self._opts.url, true); + } catch (err) { + browser$1$1.nextTick(function() { + self.emit('error', err); + }); + return + } + + // Can't set responseType on really old browsers + if ('responseType' in xhr) + xhr.responseType = self._mode.split(':')[0]; + + if ('withCredentials' in xhr) + xhr.withCredentials = !!opts.withCredentials; + + if (self._mode === 'text' && 'overrideMimeType' in xhr) + xhr.overrideMimeType('text/plain; charset=x-user-defined'); + + Object.keys(headersObj).forEach(function(name) { + xhr.setRequestHeader(headersObj[name].name, headersObj[name].value); + }); + + self._response = null; + xhr.onreadystatechange = function() { + switch (xhr.readyState) { + case rStates.LOADING: + case rStates.DONE: + self._onXHRProgress(); + break + } + }; + // Necessary for streaming in Firefox, since xhr.response is ONLY defined + // in onprogress, not in onreadystatechange with xhr.readyState = 3 + if (self._mode === 'moz-chunked-arraybuffer') { + xhr.onprogress = function() { + self._onXHRProgress(); + }; + } + + xhr.onerror = function() { + if (self._destroyed) + return + self.emit('error', new Error('XHR error')); + }; + + try { + xhr.send(body); + } catch (err) { + browser$1$1.nextTick(function() { + self.emit('error', err); + }); + return + } + } + }; + + /** + * Checks if xhr.status is readable and non-zero, indicating no error. + * Even though the spec says it should be available in readyState 3, + * accessing it throws an exception in IE8 + */ + function statusValid(xhr) { + try { + var status = xhr.status; + return (status !== null && status !== 0) + } catch (e) { + return false + } + } + + ClientRequest.prototype._onXHRProgress = function() { + var self = this; + + if (!statusValid(self._xhr) || self._destroyed) + return + + if (!self._response) + self._connect(); + + self._response._onXHRProgress(); + }; + + ClientRequest.prototype._connect = function() { + var self = this; + + if (self._destroyed) + return + + self._response = new IncomingMessage$1(self._xhr, self._fetchResponse, self._mode); + self.emit('response', self._response); + }; + + ClientRequest.prototype._write = function(chunk, encoding, cb) { + var self = this; + + self._body.push(chunk); + cb(); + }; + + ClientRequest.prototype.abort = ClientRequest.prototype.destroy = function() { + var self = this; + self._destroyed = true; + if (self._response) + self._response._destroyed = true; + if (self._xhr) + self._xhr.abort(); + // Currently, there isn't a way to truly abort a fetch. + // If you like bikeshedding, see https://github.com/whatwg/fetch/issues/27 + }; + + ClientRequest.prototype.end = function(data, encoding, cb) { + var self = this; + if (typeof data === 'function') { + cb = data; + data = undefined; + } + + Writable.prototype.end.call(self, data, encoding, cb); + }; + + ClientRequest.prototype.flushHeaders = function() {}; + ClientRequest.prototype.setTimeout = function() {}; + ClientRequest.prototype.setNoDelay = function() {}; + ClientRequest.prototype.setSocketKeepAlive = function() {}; + + /*! https://mths.be/punycode v1.4.1 by @mathias */ + + + /** Highest positive signed 32-bit float value */ + var maxInt = 2147483647; // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + var base = 36; + var tMin = 1; + var tMax = 26; + var skew = 38; + var damp = 700; + var initialBias = 72; + var initialN = 128; // 0x80 + var delimiter = '-'; // '\x2D' + var regexNonASCII = /[^\x20-\x7E]/; // unprintable ASCII chars + non-ASCII chars + var regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g; // RFC 3490 separators + + /** Error messages */ + var errors$2 = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }; + + /** Convenience shortcuts */ + var baseMinusTMin = base - tMin; + var floor = Math.floor; + var stringFromCharCode = String.fromCharCode; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors$2[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map$1(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map$1(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for ( /* no initialization */ ; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */ ; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) ? + 'xn--' + encode(string) : + string; + }); + } + + // 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 obj.hasOwnProperty has been overridden, then calling + // obj.hasOwnProperty(prop) will break. + // See: https://github.com/joyent/node/issues/1707 + function hasOwnProperty(obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop); + } + var isArray$1 = Array.isArray || function (xs) { + return Object.prototype.toString.call(xs) === '[object Array]'; + }; + function stringifyPrimitive(v) { + switch (typeof v) { + case 'string': + return v; + + case 'boolean': + return v ? 'true' : 'false'; + + case 'number': + return isFinite(v) ? v : ''; + + default: + return ''; + } + } + + function stringify$1 (obj, sep, eq, name) { + sep = sep || '&'; + eq = eq || '='; + if (obj === null) { + obj = undefined; + } + + if (typeof obj === 'object') { + return map(objectKeys(obj), function(k) { + var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; + if (isArray$1(obj[k])) { + return map(obj[k], function(v) { + return ks + encodeURIComponent(stringifyPrimitive(v)); + }).join(sep); + } else { + return ks + encodeURIComponent(stringifyPrimitive(obj[k])); + } + }).join(sep); + + } + + if (!name) return ''; + return encodeURIComponent(stringifyPrimitive(name)) + eq + + encodeURIComponent(stringifyPrimitive(obj)); + } + function map (xs, f) { + if (xs.map) return xs.map(f); + var res = []; + for (var i = 0; i < xs.length; i++) { + res.push(f(xs[i], i)); + } + return res; + } + + var objectKeys = Object.keys || function (obj) { + var res = []; + for (var key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); + } + return res; + }; + + function parse$2(qs, sep, eq, options) { + sep = sep || '&'; + eq = eq || '='; + var obj = {}; + + if (typeof qs !== 'string' || qs.length === 0) { + return obj; + } + + var regexp = /\+/g; + qs = qs.split(sep); + + var maxKeys = 1000; + if (options && typeof options.maxKeys === 'number') { + maxKeys = options.maxKeys; + } + + var len = qs.length; + // maxKeys <= 0 means that we should not limit keys count + if (maxKeys > 0 && len > maxKeys) { + len = maxKeys; + } + + for (var i = 0; i < len; ++i) { + var x = qs[i].replace(regexp, '%20'), + idx = x.indexOf(eq), + kstr, vstr, k, v; + + if (idx >= 0) { + kstr = x.substr(0, idx); + vstr = x.substr(idx + 1); + } else { + kstr = x; + vstr = ''; + } + + k = decodeURIComponent(kstr); + v = decodeURIComponent(vstr); + + if (!hasOwnProperty(obj, k)) { + obj[k] = v; + } else if (isArray$1(obj[k])) { + obj[k].push(v); + } else { + obj[k] = [obj[k], v]; + } + } + + return obj; + }var _polyfillNode_querystring = { + encode: stringify$1, + stringify: stringify$1, + decode: parse$2, + parse: parse$2 + }; + + var _polyfillNode_querystring$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + decode: parse$2, + default: _polyfillNode_querystring, + encode: stringify$1, + parse: parse$2, + stringify: stringify$1 + }); + + // WHATWG API + const URL$2 = global$3.URL; + const URLSearchParams$1 = global$3.URLSearchParams; + var _polyfillNode_url = { + parse: urlParse, + resolve: urlResolve, + resolveObject: urlResolveObject, + fileURLToPath: urlFileURLToPath, + format: urlFormat, + Url: Url, + + // WHATWG API + URL: URL$2, + URLSearchParams: URLSearchParams$1, + }; + function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; + } + + // Reference: RFC 3986, RFC 1808, RFC 2396 + + // define these here so at least they only have to be + // compiled once on the first module load. + var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, + + // RFC 2396: characters reserved for delimiting URLs. + // We actually just auto-escape these. + delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], + + // RFC 2396: characters not allowed for various reasons. + unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + // Characters that are never ever allowed in a hostname. + // Note that any invalid chars are also handled, but these + // are the ones that are *expected* to be seen, so we fast-path + // them. + nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), + hostEndingChars = ['/', '?', '#'], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + 'javascript': true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + 'http': true, + 'https': true, + 'ftp': true, + 'gopher': true, + 'file': true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }; + + function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && isObject(url) && url instanceof Url) return url; + + var u = new Url; + u.parse(url, parseQueryString, slashesDenoteHost); + return u; + } + Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { + return parse$1(this, url, parseQueryString, slashesDenoteHost); + }; + + function parse$1(self, url, parseQueryString, slashesDenoteHost) { + if (!isString(url)) { + throw new TypeError('Parameter \'url\' must be a string, not ' + typeof url); + } + + // Copy chrome, IE, opera backslash-handling behavior. + // Back slashes before the query string get converted to forward slashes + // See: https://code.google.com/p/chromium/issues/detail?id=25916 + var queryIndex = url.indexOf('?'), + splitter = + (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + // trim before proceeding. + // This is to support parse stuff like " http://foo.com \n" + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + self.path = rest; + self.href = rest; + self.pathname = simplePath[1]; + if (simplePath[2]) { + self.search = simplePath[2]; + if (parseQueryString) { + self.query = parse$2(self.search.substr(1)); + } else { + self.query = self.search.substr(1); + } + } else if (parseQueryString) { + self.search = ''; + self.query = {}; + } + return self; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + self.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + // figure out if it's got a host + // user@server is *always* interpreted as a hostname, and url + // resolution will treat //foo/bar as host=foo,path=bar because that's + // how the browser resolves relative URLs. + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + self.slashes = true; + } + } + var i, hec, l, p; + if (!hostlessProtocol[proto] && + (slashes || (proto && !slashedProtocol[proto]))) { + + // there's a hostname. + // the first instance of /, ?, ;, or # ends the host. + // + // If there is an @ in the hostname, then non-host chars *are* allowed + // to the left of the last @ sign, unless some host-ending character + // comes *before* the @-sign. + // URLs are obnoxious. + // + // ex: + // http://a@b@c/ => user:a@b host:c + // http://a@b?@c => user:a host:c path:/?@c + + // v0.12 TODO(isaacs): This is not quite how Chrome does things. + // Review our test case against browsers more comprehensively. + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (i = 0; i < hostEndingChars.length; i++) { + hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + + // at this point, either we have an explicit point where the + // auth portion cannot go past, or the last @ char is the decider. + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + // atSign must be in auth portion. + // http://a@b/c@d => host:b auth:a path:/c@d + atSign = rest.lastIndexOf('@', hostEnd); + } + + // Now we have a portion which is definitely the auth. + // Pull that off. + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + self.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (i = 0; i < nonHostChars.length; i++) { + hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) + hostEnd = hec; + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) + hostEnd = rest.length; + + self.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + parseHost(self); + + // we've indicated that there is a hostname, + // so even if it's empty, it has to be present. + self.hostname = self.hostname || ''; + + // if hostname begins with [ and ends with ] + // assume that it's an IPv6 address. + var ipv6Hostname = self.hostname[0] === '[' && + self.hostname[self.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = self.hostname.split(/\./); + for (i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) continue; + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + // we replace non-ASCII char with a temporary placeholder + // we need this to make sure size of hostname is not + // broken by replacing non-ASCII by nothing + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + self.hostname = validParts.join('.'); + break; + } + } + } + } + + if (self.hostname.length > hostnameMaxLen) { + self.hostname = ''; + } else { + // hostnames are always lower case. + self.hostname = self.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + // IDNA Support: Returns a punycoded representation of "domain". + // It only converts parts of the domain name that + // have non-ASCII characters, i.e. it doesn't matter if + // you call it with a domain that already is ASCII-only. + self.hostname = toASCII(self.hostname); + } + + p = self.port ? ':' + self.port : ''; + var h = self.hostname || ''; + self.host = h + p; + self.href += self.host; + + // strip [ and ] from the hostname + // the host field still retains them, though + if (ipv6Hostname) { + self.hostname = self.hostname.substr(1, self.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + // now rest is set to the post-host stuff. + // chop off any delim chars. + if (!unsafeProtocol[lowerProto]) { + + // First, make 100% sure that any "autoEscape" chars get + // escaped, even if encodeURIComponent doesn't think they + // need to be. + for (i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) + continue; + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + self.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + self.search = rest.substr(qm); + self.query = rest.substr(qm + 1); + if (parseQueryString) { + self.query = parse$2(self.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + self.search = ''; + self.query = {}; + } + if (rest) self.pathname = rest; + if (slashedProtocol[lowerProto] && + self.hostname && !self.pathname) { + self.pathname = '/'; + } + + //to support http.request + if (self.pathname || self.search) { + p = self.pathname || ''; + var s = self.search || ''; + self.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + self.href = format(self); + return self; + } + + function urlFileURLToPath(path) { + if (typeof path === 'string') + path = new Url().parse(path); + else if (!(path instanceof Url)) + throw new TypeError('The "path" argument must be of type string or an instance of URL. Received type ' + (typeof path) + String(path)); + if (path.protocol !== 'file:') + throw new TypeError('The URL must be of scheme file'); + return getPathFromURLPosix(path); + } + + function getPathFromURLPosix(url) { + const pathname = url.pathname; + for (let n = 0; n < pathname.length; n++) { + if (pathname[n] === '%') { + const third = pathname.codePointAt(n + 2) | 0x20; + if (pathname[n + 1] === '2' && third === 102) { + throw new TypeError( + 'must not include encoded / characters' + ); + } + } + } + return decodeURIComponent(pathname); + } + + // format a parsed object into a url string + function urlFormat(obj) { + // ensure it's an object, and not a string url. + // If it's an obj, this is a no-op. + // this way, you can call url_format() on strings + // to clean up potentially wonky urls. + if (isString(obj)) obj = parse$1({}, obj); + return format(obj); + } + + function format(self) { + var auth = self.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = self.protocol || '', + pathname = self.pathname || '', + hash = self.hash || '', + host = false, + query = ''; + + if (self.host) { + host = auth + self.host; + } else if (self.hostname) { + host = auth + (self.hostname.indexOf(':') === -1 ? + self.hostname : + '[' + this.hostname + ']'); + if (self.port) { + host += ':' + self.port; + } + } + + if (self.query && + isObject(self.query) && + Object.keys(self.query).length) { + query = stringify$1(self.query); + } + + var search = self.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') protocol += ':'; + + // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + // unless they had them to begin with. + if (self.slashes || + (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') hash = '#' + hash; + if (search && search.charAt(0) !== '?') search = '?' + search; + + pathname = pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; + } + + Url.prototype.format = function() { + return format(this); + }; + + function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); + } + + Url.prototype.resolve = function(relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); + }; + + function urlResolveObject(source, relative) { + if (!source) return relative; + return urlParse(source, false, true).resolveObject(relative); + } + + Url.prototype.resolveObject = function(relative) { + if (isString(relative)) { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + // hash is always overridden, no matter what. + // even href="" will remove it. + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') + result[rkey] = relative[rkey]; + } + + //urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && + result.hostname && !result.pathname) { + result.path = result.pathname = '/'; + } + + result.href = result.format(); + return result; + } + var relPath; + if (relative.protocol && relative.protocol !== result.protocol) { + // if it's a known url protocol, then changing + // the protocol does weird things + // first, if it's not file:, then we MUST have a host, + // and if there was a path + // to begin with, then we MUST have a path. + // if it is file:, then the host is dropped, + // because that's known to be hostless. + // anything else is assumed to be absolute. + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())); + if (!relative.host) relative.host = ''; + if (!relative.hostname) relative.hostname = ''; + if (relPath[0] !== '') relPath.unshift(''); + if (relPath.length < 2) relPath.unshift(''); + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), + isRelAbs = ( + relative.host || + relative.pathname && relative.pathname.charAt(0) === '/' + ), + mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + relPath = relative.pathname && relative.pathname.split('/') || []; + // if the url is a non-slashed url, then relative + // links like ../.. should be able + // to crawl up to the hostname, as well. This is strange. + // result.protocol has already been set by now. + // Later on, put the first path part into the host field. + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') srcPath[0] = result.host; + else srcPath.unshift(result.host); + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + var authInHost; + if (isRelAbs) { + // it's absolute. + result.host = (relative.host || relative.host === '') ? + relative.host : result.host; + result.hostname = (relative.hostname || relative.hostname === '') ? + relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + // it's relative + // throw away the existing file, and take the new path instead. + if (!srcPath) srcPath = []; + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (!isNullOrUndefined$1(relative.search)) { + // just pull out the search. + // like href='?foo'. + // Put this after the other two cases because it simplifies the booleans + if (psychotic) { + result.hostname = result.host = srcPath.shift(); + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + result.search = relative.search; + result.query = relative.query; + //to support http.request + if (!isNull(result.pathname) || !isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we've already handled the other stuff above. + result.pathname = null; + //to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + // if a url ENDs in . or .., then it must get a trailing slash. + // however, if it ends in anything else non-slashy, + // then it must NOT get a trailing slash. + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = ( + (result.host || relative.host || srcPath.length > 1) && + (last === '.' || last === '..') || last === ''); + + // strip single dots, resolve double dots to parent dir + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && + (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || + (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = result.host = isAbsolute ? '' : + srcPath.length ? srcPath.shift() : ''; + //occationaly the auth can get stuck only in host + //this especially happens in cases like + //url.resolveObject('mailto:local1@domain1', 'local2@domain2') + authInHost = result.host && result.host.indexOf('@') > 0 ? + result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (!srcPath.length) { + result.pathname = null; + result.path = null; + } else { + result.pathname = srcPath.join('/'); + } + + //to support request.http + if (!isNull(result.pathname) || !isNull(result.search)) { + result.path = (result.pathname ? result.pathname : '') + + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + }; + + Url.prototype.parseHost = function() { + return parseHost(this); + }; + + function parseHost(self) { + var host = self.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + self.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) self.hostname = host; + } + + var _polyfillNode_url$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + URL: URL$2, + URLSearchParams: URLSearchParams$1, + Url: Url, + default: _polyfillNode_url, + fileURLToPath: urlFileURLToPath, + format: urlFormat, + parse: urlParse, + resolve: urlResolve, + resolveObject: urlResolveObject + }); + + function request$3(opts, cb) { + if (typeof opts === 'string') + opts = urlParse(opts); + + + // Normally, the page is loaded from http or https, so not specifying a protocol + // will result in a (valid) protocol-relative url. However, this won't work if + // the protocol is something else, like 'file:' + var defaultProtocol = global$3.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''; + + var protocol = opts.protocol || defaultProtocol; + var host = opts.hostname || opts.host; + var port = opts.port; + var path = opts.path || '/'; + + // Necessary for IPv6 addresses + if (host && host.indexOf(':') !== -1) + host = '[' + host + ']'; + + // This may be a relative url. The browser should always be able to interpret it correctly. + opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path; + opts.method = (opts.method || 'GET').toUpperCase(); + opts.headers = opts.headers || {}; + + // Also valid opts.auth, opts.mode + + var req = new ClientRequest(opts); + if (cb) + req.on('response', cb); + return req + } + + function get(opts, cb) { + var req = request$3(opts, cb); + req.end(); + return req + } + + function Agent$5() {} + Agent$5.defaultMaxSockets = 4; + + var METHODS = [ + 'CHECKOUT', + 'CONNECT', + 'COPY', + 'DELETE', + 'GET', + 'HEAD', + 'LOCK', + 'M-SEARCH', + 'MERGE', + 'MKACTIVITY', + 'MKCOL', + 'MOVE', + 'NOTIFY', + 'OPTIONS', + 'PATCH', + 'POST', + 'PROPFIND', + 'PROPPATCH', + 'PURGE', + 'PUT', + 'REPORT', + 'SEARCH', + 'SUBSCRIBE', + 'TRACE', + 'UNLOCK', + 'UNSUBSCRIBE' + ]; + var STATUS_CODES$1 = { + 100: 'Continue', + 101: 'Switching Protocols', + 102: 'Processing', // RFC 2518, obsoleted by RFC 4918 + 200: 'OK', + 201: 'Created', + 202: 'Accepted', + 203: 'Non-Authoritative Information', + 204: 'No Content', + 205: 'Reset Content', + 206: 'Partial Content', + 207: 'Multi-Status', // RFC 4918 + 300: 'Multiple Choices', + 301: 'Moved Permanently', + 302: 'Moved Temporarily', + 303: 'See Other', + 304: 'Not Modified', + 305: 'Use Proxy', + 307: 'Temporary Redirect', + 400: 'Bad Request', + 401: 'Unauthorized', + 402: 'Payment Required', + 403: 'Forbidden', + 404: 'Not Found', + 405: 'Method Not Allowed', + 406: 'Not Acceptable', + 407: 'Proxy Authentication Required', + 408: 'Request Time-out', + 409: 'Conflict', + 410: 'Gone', + 411: 'Length Required', + 412: 'Precondition Failed', + 413: 'Request Entity Too Large', + 414: 'Request-URI Too Large', + 415: 'Unsupported Media Type', + 416: 'Requested Range Not Satisfiable', + 417: 'Expectation Failed', + 418: 'I\'m a teapot', // RFC 2324 + 422: 'Unprocessable Entity', // RFC 4918 + 423: 'Locked', // RFC 4918 + 424: 'Failed Dependency', // RFC 4918 + 425: 'Unordered Collection', // RFC 4918 + 426: 'Upgrade Required', // RFC 2817 + 428: 'Precondition Required', // RFC 6585 + 429: 'Too Many Requests', // RFC 6585 + 431: 'Request Header Fields Too Large', // RFC 6585 + 500: 'Internal Server Error', + 501: 'Not Implemented', + 502: 'Bad Gateway', + 503: 'Service Unavailable', + 504: 'Gateway Time-out', + 505: 'HTTP Version Not Supported', + 506: 'Variant Also Negotiates', // RFC 2295 + 507: 'Insufficient Storage', // RFC 4918 + 509: 'Bandwidth Limit Exceeded', + 510: 'Not Extended', // RFC 2774 + 511: 'Network Authentication Required' // RFC 6585 + }; + + var _polyfillNode_http = { + request: request$3, + get, + Agent: Agent$5, + METHODS, + STATUS_CODES: STATUS_CODES$1 + }; + + var _polyfillNode_http$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + Agent: Agent$5, + METHODS: METHODS, + STATUS_CODES: STATUS_CODES$1, + default: _polyfillNode_http, + get: get, + request: request$3 + }); + + var require$$17 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_http$1); + + var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_stream); + + var symbols$4 = { + kClose: Symbol('close'), + kDestroy: Symbol('destroy'), + kDispatch: Symbol('dispatch'), + kUrl: Symbol('url'), + kWriting: Symbol('writing'), + kResuming: Symbol('resuming'), + kQueue: Symbol('queue'), + kConnect: Symbol('connect'), + kConnecting: Symbol('connecting'), + kHeadersList: Symbol('headers list'), + kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), + kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), + kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), + kKeepAliveTimeoutValue: Symbol('keep alive timeout'), + kKeepAlive: Symbol('keep alive'), + kHeadersTimeout: Symbol('headers timeout'), + kBodyTimeout: Symbol('body timeout'), + kServerName: Symbol('server name'), + kLocalAddress: Symbol('local address'), + kHost: Symbol('host'), + kNoRef: Symbol('no ref'), + kBodyUsed: Symbol('used'), + kRunning: Symbol('running'), + kBlocking: Symbol('blocking'), + kPending: Symbol('pending'), + kSize: Symbol('size'), + kBusy: Symbol('busy'), + kQueued: Symbol('queued'), + kFree: Symbol('free'), + kConnected: Symbol('connected'), + kClosed: Symbol('closed'), + kNeedDrain: Symbol('need drain'), + kReset: Symbol('reset'), + kDestroyed: Symbol.for('nodejs.stream.destroyed'), + kMaxHeadersSize: Symbol('max headers size'), + kRunningIdx: Symbol('running index'), + kPendingIdx: Symbol('pending index'), + kError: Symbol('error'), + kClients: Symbol('clients'), + kClient: Symbol('client'), + kParser: Symbol('parser'), + kOnDestroyed: Symbol('destroy callbacks'), + kPipelining: Symbol('pipelining'), + kSocket: Symbol('socket'), + kHostHeader: Symbol('host header'), + kConnector: Symbol('connector'), + kStrictContentLength: Symbol('strict content length'), + kMaxRedirections: Symbol('maxRedirections'), + kMaxRequests: Symbol('maxRequestsPerClient'), + kProxy: Symbol('proxy agent options'), + kCounter: Symbol('socket request counter'), + kInterceptors: Symbol('dispatch interceptors'), + kMaxResponseSize: Symbol('max response size'), + kHTTP2Session: Symbol('http2Session'), + kHTTP2SessionState: Symbol('http2Session state'), + kHTTP2BuildRequest: Symbol('http2 build request'), + kHTTP1BuildRequest: Symbol('http1 build request'), + kHTTP2CopyHeaders: Symbol('http2 copy headers'), + kHTTPConnVersion: Symbol('http connection version') + }; + + let UndiciError$2 = class UndiciError extends Error { + constructor (message) { + super(message); + this.name = 'UndiciError'; + this.code = 'UND_ERR'; + } + }; + + let ConnectTimeoutError$1 = class ConnectTimeoutError extends UndiciError$2 { + constructor (message) { + super(message); + Error.captureStackTrace(this, ConnectTimeoutError); + this.name = 'ConnectTimeoutError'; + this.message = message || 'Connect Timeout Error'; + this.code = 'UND_ERR_CONNECT_TIMEOUT'; + } + }; + + let HeadersTimeoutError$1 = class HeadersTimeoutError extends UndiciError$2 { + constructor (message) { + super(message); + Error.captureStackTrace(this, HeadersTimeoutError); + this.name = 'HeadersTimeoutError'; + this.message = message || 'Headers Timeout Error'; + this.code = 'UND_ERR_HEADERS_TIMEOUT'; + } + }; + + let HeadersOverflowError$1 = class HeadersOverflowError extends UndiciError$2 { + constructor (message) { + super(message); + Error.captureStackTrace(this, HeadersOverflowError); + this.name = 'HeadersOverflowError'; + this.message = message || 'Headers Overflow Error'; + this.code = 'UND_ERR_HEADERS_OVERFLOW'; + } + }; + + let BodyTimeoutError$1 = class BodyTimeoutError extends UndiciError$2 { + constructor (message) { + super(message); + Error.captureStackTrace(this, BodyTimeoutError); + this.name = 'BodyTimeoutError'; + this.message = message || 'Body Timeout Error'; + this.code = 'UND_ERR_BODY_TIMEOUT'; + } + }; + + let ResponseStatusCodeError$1 = class ResponseStatusCodeError extends UndiciError$2 { + constructor (message, statusCode, headers, body) { + super(message); + Error.captureStackTrace(this, ResponseStatusCodeError); + this.name = 'ResponseStatusCodeError'; + this.message = message || 'Response Status Code Error'; + this.code = 'UND_ERR_RESPONSE_STATUS_CODE'; + this.body = body; + this.status = statusCode; + this.statusCode = statusCode; + this.headers = headers; + } + }; + + let InvalidArgumentError$m = class InvalidArgumentError extends UndiciError$2 { + constructor (message) { + super(message); + Error.captureStackTrace(this, InvalidArgumentError); + this.name = 'InvalidArgumentError'; + this.message = message || 'Invalid Argument Error'; + this.code = 'UND_ERR_INVALID_ARG'; + } + }; + + let InvalidReturnValueError$2 = class InvalidReturnValueError extends UndiciError$2 { + constructor (message) { + super(message); + Error.captureStackTrace(this, InvalidReturnValueError); + this.name = 'InvalidReturnValueError'; + this.message = message || 'Invalid Return Value Error'; + this.code = 'UND_ERR_INVALID_RETURN_VALUE'; + } + }; + + let RequestAbortedError$9 = class RequestAbortedError extends UndiciError$2 { + constructor (message) { + super(message); + Error.captureStackTrace(this, RequestAbortedError); + this.name = 'AbortError'; + this.message = message || 'Request aborted'; + this.code = 'UND_ERR_ABORTED'; + } + }; + + let InformationalError$1 = class InformationalError extends UndiciError$2 { + constructor (message) { + super(message); + Error.captureStackTrace(this, InformationalError); + this.name = 'InformationalError'; + this.message = message || 'Request information'; + this.code = 'UND_ERR_INFO'; + } + }; + + let RequestContentLengthMismatchError$1 = class RequestContentLengthMismatchError extends UndiciError$2 { + constructor (message) { + super(message); + Error.captureStackTrace(this, RequestContentLengthMismatchError); + this.name = 'RequestContentLengthMismatchError'; + this.message = message || 'Request body length does not match content-length header'; + this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'; + } + }; + + let ResponseContentLengthMismatchError$1 = class ResponseContentLengthMismatchError extends UndiciError$2 { + constructor (message) { + super(message); + Error.captureStackTrace(this, ResponseContentLengthMismatchError); + this.name = 'ResponseContentLengthMismatchError'; + this.message = message || 'Response body length does not match content-length header'; + this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'; + } + }; + + let ClientDestroyedError$2 = class ClientDestroyedError extends UndiciError$2 { + constructor (message) { + super(message); + Error.captureStackTrace(this, ClientDestroyedError); + this.name = 'ClientDestroyedError'; + this.message = message || 'The client is destroyed'; + this.code = 'UND_ERR_DESTROYED'; + } + }; + + let ClientClosedError$1 = class ClientClosedError extends UndiciError$2 { + constructor (message) { + super(message); + Error.captureStackTrace(this, ClientClosedError); + this.name = 'ClientClosedError'; + this.message = message || 'The client is closed'; + this.code = 'UND_ERR_CLOSED'; + } + }; + + let SocketError$3 = class SocketError extends UndiciError$2 { + constructor (message, socket) { + super(message); + Error.captureStackTrace(this, SocketError); + this.name = 'SocketError'; + this.message = message || 'Socket error'; + this.code = 'UND_ERR_SOCKET'; + this.socket = socket; + } + }; + + let NotSupportedError$2 = class NotSupportedError extends UndiciError$2 { + constructor (message) { + super(message); + Error.captureStackTrace(this, NotSupportedError); + this.name = 'NotSupportedError'; + this.message = message || 'Not supported error'; + this.code = 'UND_ERR_NOT_SUPPORTED'; + } + }; + + let BalancedPoolMissingUpstreamError$1 = class BalancedPoolMissingUpstreamError extends UndiciError$2 { + constructor (message) { + super(message); + Error.captureStackTrace(this, NotSupportedError$2); + this.name = 'MissingUpstreamError'; + this.message = message || 'No upstream has been added to the BalancedPool'; + this.code = 'UND_ERR_BPL_MISSING_UPSTREAM'; + } + }; + + let HTTPParserError$1 = class HTTPParserError extends Error { + constructor (message, code, data) { + super(message); + Error.captureStackTrace(this, HTTPParserError); + this.name = 'HTTPParserError'; + this.code = code ? `HPE_${code}` : undefined; + this.data = data ? data.toString() : undefined; + } + }; + + let ResponseExceededMaxSizeError$1 = class ResponseExceededMaxSizeError extends UndiciError$2 { + constructor (message) { + super(message); + Error.captureStackTrace(this, ResponseExceededMaxSizeError); + this.name = 'ResponseExceededMaxSizeError'; + this.message = message || 'Response content exceeded max size'; + this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE'; + } + }; + + var errors$1 = { + HTTPParserError: HTTPParserError$1, + UndiciError: UndiciError$2, + HeadersTimeoutError: HeadersTimeoutError$1, + HeadersOverflowError: HeadersOverflowError$1, + BodyTimeoutError: BodyTimeoutError$1, + RequestContentLengthMismatchError: RequestContentLengthMismatchError$1, + ConnectTimeoutError: ConnectTimeoutError$1, + ResponseStatusCodeError: ResponseStatusCodeError$1, + InvalidArgumentError: InvalidArgumentError$m, + InvalidReturnValueError: InvalidReturnValueError$2, + RequestAbortedError: RequestAbortedError$9, + ClientDestroyedError: ClientDestroyedError$2, + ClientClosedError: ClientClosedError$1, + InformationalError: InformationalError$1, + SocketError: SocketError$3, + NotSupportedError: NotSupportedError$2, + ResponseContentLengthMismatchError: ResponseContentLengthMismatchError$1, + BalancedPoolMissingUpstreamError: BalancedPoolMissingUpstreamError$1, + ResponseExceededMaxSizeError: ResponseExceededMaxSizeError$1 + }; + + var require$$7 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_buffer); + + var require$$8 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_querystring$1); + + var web_polyfillNodeIgnore = /*#__PURE__*/Object.freeze({ + __proto__: null + }); + + var require$$14 = /*@__PURE__*/getAugmentedNamespace(web_polyfillNodeIgnore); + + var require$$10$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_events); + + const assert$9 = require$$3$1; + const { kDestroyed: kDestroyed$1, kBodyUsed: kBodyUsed$1 } = symbols$4; + const { IncomingMessage } = require$$17; + const stream$1 = require$$0$1; + const net$2 = require$$1$3; + const { InvalidArgumentError: InvalidArgumentError$l } = errors$1; + const { Blob: Blob$2 } = require$$7; + const nodeUtil = require$$3$2; + const { stringify } = require$$8; + + const [nodeMajor, nodeMinor] = "18.15.0".split('.').map(v => Number(v)); + + function nop$1 () {} + + function isStream (obj) { + return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' + } + + // based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) + function isBlobLike (object) { + return (Blob$2 && object instanceof Blob$2) || ( + object && + typeof object === 'object' && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + /^(Blob|File)$/.test(object[Symbol.toStringTag]) + ) + } + + function buildURL$2 (url, queryParams) { + if (url.includes('?') || url.includes('#')) { + throw new Error('Query params cannot be passed when url already contains "?" or "#".') + } + + const stringified = stringify(queryParams); + + if (stringified) { + url += '?' + stringified; + } + + return url + } + + function parseURL (url) { + if (typeof url === 'string') { + url = new URL(url); + + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError$l('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + return url + } + + if (!url || typeof url !== 'object') { + throw new InvalidArgumentError$l('Invalid URL: The URL argument must be a non-null object.') + } + + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError$l('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + if (!(url instanceof URL)) { + if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) { + throw new InvalidArgumentError$l('Invalid URL: port must be a valid integer or a string representation of an integer.') + } + + if (url.path != null && typeof url.path !== 'string') { + throw new InvalidArgumentError$l('Invalid URL path: the path must be a string or null/undefined.') + } + + if (url.pathname != null && typeof url.pathname !== 'string') { + throw new InvalidArgumentError$l('Invalid URL pathname: the pathname must be a string or null/undefined.') + } + + if (url.hostname != null && typeof url.hostname !== 'string') { + throw new InvalidArgumentError$l('Invalid URL hostname: the hostname must be a string or null/undefined.') + } + + if (url.origin != null && typeof url.origin !== 'string') { + throw new InvalidArgumentError$l('Invalid URL origin: the origin must be a string or null/undefined.') + } + + const port = url.port != null + ? url.port + : (url.protocol === 'https:' ? 443 : 80); + let origin = url.origin != null + ? url.origin + : `${url.protocol}//${url.hostname}:${port}`; + let path = url.path != null + ? url.path + : `${url.pathname || ''}${url.search || ''}`; + + if (origin.endsWith('/')) { + origin = origin.substring(0, origin.length - 1); + } + + if (path && !path.startsWith('/')) { + path = `/${path}`; + } + // new URL(path, origin) is unsafe when `path` contains an absolute URL + // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: + // If first parameter is a relative URL, second param is required, and will be used as the base URL. + // If first parameter is an absolute URL, a given second param will be ignored. + url = new URL(origin + path); + } + + return url + } + + function parseOrigin$1 (url) { + url = parseURL(url); + + if (url.pathname !== '/' || url.search || url.hash) { + throw new InvalidArgumentError$l('invalid url') + } + + return url + } + + function getHostname (host) { + if (host[0] === '[') { + const idx = host.indexOf(']'); + + assert$9(idx !== -1); + return host.substr(1, idx - 1) + } + + const idx = host.indexOf(':'); + if (idx === -1) return host + + return host.substr(0, idx) + } + + // IP addresses are not valid server names per RFC6066 + // > Currently, the only server names supported are DNS hostnames + function getServerName (host) { + if (!host) { + return null + } + + assert$9.strictEqual(typeof host, 'string'); + + const servername = getHostname(host); + if (net$2.isIP(servername)) { + return '' + } + + return servername + } + + function deepClone$1 (obj) { + return JSON.parse(JSON.stringify(obj)) + } + + function isAsyncIterable (obj) { + return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') + } + + function isIterable (obj) { + return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) + } + + function bodyLength (body) { + if (body == null) { + return 0 + } else if (isStream(body)) { + const state = body._readableState; + return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) + ? state.length + : null + } else if (isBlobLike(body)) { + return body.size != null ? body.size : null + } else if (isBuffer(body)) { + return body.byteLength + } + + return null + } + + function isDestroyed (stream) { + return !stream || !!(stream.destroyed || stream[kDestroyed$1]) + } + + function isReadableAborted (stream) { + const state = stream && stream._readableState; + return isDestroyed(stream) && state && !state.endEmitted + } + + function destroy (stream, err) { + if (!isStream(stream) || isDestroyed(stream)) { + return + } + + if (typeof stream.destroy === 'function') { + if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { + // See: https://github.com/nodejs/node/pull/38505/files + stream.socket = null; + } + + stream.destroy(err); + } else if (err) { + browser$1$1.nextTick((stream, err) => { + stream.emit('error', err); + }, stream, err); + } + + if (stream.destroyed !== true) { + stream[kDestroyed$1] = true; + } + } + + const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/; + function parseKeepAliveTimeout (val) { + const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR); + return m ? parseInt(m[1], 10) * 1000 : null + } + + function parseHeaders (headers, obj = {}) { + // For H2 support + if (!Array.isArray(headers)) return headers + + for (let i = 0; i < headers.length; i += 2) { + const key = headers[i].toString().toLowerCase(); + let val = obj[key]; + + if (!val) { + if (Array.isArray(headers[i + 1])) { + obj[key] = headers[i + 1]; + } else { + obj[key] = headers[i + 1].toString('utf8'); + } + } else { + if (!Array.isArray(val)) { + val = [val]; + obj[key] = val; + } + val.push(headers[i + 1].toString('utf8')); + } + } + + // See https://github.com/nodejs/node/pull/46528 + if ('content-length' in obj && 'content-disposition' in obj) { + obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1'); + } + + return obj + } + + function parseRawHeaders (headers) { + const ret = []; + let hasContentLength = false; + let contentDispositionIdx = -1; + + for (let n = 0; n < headers.length; n += 2) { + const key = headers[n + 0].toString(); + const val = headers[n + 1].toString('utf8'); + + if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) { + ret.push(key, val); + hasContentLength = true; + } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { + contentDispositionIdx = ret.push(key, val) - 1; + } else { + ret.push(key, val); + } + } + + // See https://github.com/nodejs/node/pull/46528 + if (hasContentLength && contentDispositionIdx !== -1) { + ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1'); + } + + return ret + } + + function isBuffer (buffer) { + // See, https://github.com/mcollina/undici/pull/319 + return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) + } + + function validateHandler (handler, method, upgrade) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError$l('handler must be an object') + } + + if (typeof handler.onConnect !== 'function') { + throw new InvalidArgumentError$l('invalid onConnect method') + } + + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError$l('invalid onError method') + } + + if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { + throw new InvalidArgumentError$l('invalid onBodySent method') + } + + if (upgrade || method === 'CONNECT') { + if (typeof handler.onUpgrade !== 'function') { + throw new InvalidArgumentError$l('invalid onUpgrade method') + } + } else { + if (typeof handler.onHeaders !== 'function') { + throw new InvalidArgumentError$l('invalid onHeaders method') + } + + if (typeof handler.onData !== 'function') { + throw new InvalidArgumentError$l('invalid onData method') + } + + if (typeof handler.onComplete !== 'function') { + throw new InvalidArgumentError$l('invalid onComplete method') + } + } + } + + // A body is disturbed if it has been read from and it cannot + // be re-used without losing state or data. + function isDisturbed (body) { + return !!(body && ( + stream$1.isDisturbed + ? stream$1.isDisturbed(body) || body[kBodyUsed$1] // TODO (fix): Why is body[kBodyUsed] needed? + : body[kBodyUsed$1] || + body.readableDidRead || + (body._readableState && body._readableState.dataEmitted) || + isReadableAborted(body) + )) + } + + function isErrored (body) { + return !!(body && ( + stream$1.isErrored + ? stream$1.isErrored(body) + : /state: 'errored'/.test(nodeUtil.inspect(body) + ))) + } + + function isReadable (body) { + return !!(body && ( + stream$1.isReadable + ? stream$1.isReadable(body) + : /state: 'readable'/.test(nodeUtil.inspect(body) + ))) + } + + function getSocketInfo (socket) { + return { + localAddress: socket.localAddress, + localPort: socket.localPort, + remoteAddress: socket.remoteAddress, + remotePort: socket.remotePort, + remoteFamily: socket.remoteFamily, + timeout: socket.timeout, + bytesWritten: socket.bytesWritten, + bytesRead: socket.bytesRead + } + } + + async function * convertIterableToBuffer (iterable) { + for await (const chunk of iterable) { + yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + } + } + + let ReadableStream; + function ReadableStreamFrom$1 (iterable) { + if (!ReadableStream) { + ReadableStream = require$$14.ReadableStream; + } + + if (ReadableStream.from) { + return ReadableStream.from(convertIterableToBuffer(iterable)) + } + + let iterator; + return new ReadableStream( + { + async start () { + iterator = iterable[Symbol.asyncIterator](); + }, + async pull (controller) { + const { done, value } = await iterator.next(); + if (done) { + queueMicrotask(() => { + controller.close(); + }); + } else { + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value); + controller.enqueue(new Uint8Array(buf)); + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return(); + } + }, + 0 + ) + } + + // The chunk should be a FormData instance and contains + // all the required methods. + function isFormDataLike (object) { + return ( + object && + typeof object === 'object' && + typeof object.append === 'function' && + typeof object.delete === 'function' && + typeof object.get === 'function' && + typeof object.getAll === 'function' && + typeof object.has === 'function' && + typeof object.set === 'function' && + object[Symbol.toStringTag] === 'FormData' + ) + } + + function throwIfAborted (signal) { + if (!signal) { return } + if (typeof signal.throwIfAborted === 'function') { + signal.throwIfAborted(); + } else { + if (signal.aborted) { + // DOMException not available < v17.0.0 + const err = new Error('The operation was aborted'); + err.name = 'AbortError'; + throw err + } + } + } + + let events$1; + function addAbortListener$1 (signal, listener) { + if (typeof Symbol.dispose === 'symbol') { + if (!events$1) { + events$1 = require$$10$1; + } + if (typeof events$1.addAbortListener === 'function' && 'aborted' in signal) { + return events$1.addAbortListener(signal, listener) + } + } + if ('addEventListener' in signal) { + signal.addEventListener('abort', listener, { once: true }); + return () => signal.removeEventListener('abort', listener) + } + signal.addListener('abort', listener); + return () => signal.removeListener('abort', listener) + } + + const hasToWellFormed = !!String.prototype.toWellFormed; + + /** + * @param {string} val + */ + function toUSVString$2 (val) { + if (hasToWellFormed) { + return `${val}`.toWellFormed() + } else if (nodeUtil.toUSVString) { + return nodeUtil.toUSVString(val) + } + + return `${val}` + } + + const kEnumerableProperty = Object.create(null); + kEnumerableProperty.enumerable = true; + + var util$l = { + kEnumerableProperty, + nop: nop$1, + isDisturbed, + isErrored, + isReadable, + toUSVString: toUSVString$2, + isReadableAborted, + isBlobLike, + parseOrigin: parseOrigin$1, + parseURL, + getServerName, + isStream, + isIterable, + isAsyncIterable, + isDestroyed, + parseRawHeaders, + parseHeaders, + parseKeepAliveTimeout, + destroy, + bodyLength, + deepClone: deepClone$1, + ReadableStreamFrom: ReadableStreamFrom$1, + isBuffer, + validateHandler, + getSocketInfo, + isFormDataLike, + buildURL: buildURL$2, + throwIfAborted, + addAbortListener: addAbortListener$1, + nodeMajor, + nodeMinor, + nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13) + }; + + let fastNow = Date.now(); + let fastNowTimeout; + + const fastTimers = []; + + function onTimeout () { + fastNow = Date.now(); + + let len = fastTimers.length; + let idx = 0; + while (idx < len) { + const timer = fastTimers[idx]; + + if (timer.state === 0) { + timer.state = fastNow + timer.delay; + } else if (timer.state > 0 && fastNow >= timer.state) { + timer.state = -1; + timer.callback(timer.opaque); + } + + if (timer.state === -1) { + timer.state = -2; + if (idx !== len - 1) { + fastTimers[idx] = fastTimers.pop(); + } else { + fastTimers.pop(); + } + len -= 1; + } else { + idx += 1; + } + } + + if (fastTimers.length > 0) { + refreshTimeout(); + } + } + + function refreshTimeout () { + if (fastNowTimeout && fastNowTimeout.refresh) { + fastNowTimeout.refresh(); + } else { + clearTimeout(fastNowTimeout); + fastNowTimeout = setTimeout(onTimeout, 1e3); + if (fastNowTimeout.unref) { + fastNowTimeout.unref(); + } + } + } + + class Timeout { + constructor (callback, delay, opaque) { + this.callback = callback; + this.delay = delay; + this.opaque = opaque; + + // -2 not in timer list + // -1 in timer list but inactive + // 0 in timer list waiting for time + // > 0 in timer list waiting for time to expire + this.state = -2; + + this.refresh(); + } + + refresh () { + if (this.state === -2) { + fastTimers.push(this); + if (!fastNowTimeout || fastTimers.length === 1) { + refreshTimeout(); + } + } + + this.state = 0; + } + + clear () { + this.state = -1; + } + } + + var timers$1 = { + setTimeout (callback, delay, opaque) { + return delay < 1e3 + ? setTimeout(callback, delay, opaque) + : new Timeout(callback, delay, opaque) + }, + clearTimeout (timeout) { + if (timeout instanceof Timeout) { + timeout.clear(); + } else { + clearTimeout(timeout); + } + } + }; + + function channel() {} + + var _polyfillNode_diagnostics_channel = /*#__PURE__*/Object.freeze({ + __proto__: null, + channel: channel + }); + + var require$$1$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_diagnostics_channel); + + var main = {exports: {}}; + + var sbmh; + var hasRequiredSbmh; + + function requireSbmh () { + if (hasRequiredSbmh) return sbmh; + hasRequiredSbmh = 1; + + /** + * Copyright Brian White. All rights reserved. + * + * @see https://github.com/mscdex/streamsearch + * + * 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. + * + * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation + * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool + */ + const EventEmitter = require$$10$1.EventEmitter; + const inherits = require$$3$2.inherits; + + function SBMH (needle) { + if (typeof needle === 'string') { + needle = Buffer.from(needle); + } + + if (!Buffer.isBuffer(needle)) { + throw new TypeError('The needle has to be a String or a Buffer.') + } + + const needleLength = needle.length; + + if (needleLength === 0) { + throw new Error('The needle cannot be an empty String/Buffer.') + } + + if (needleLength > 256) { + throw new Error('The needle cannot have a length bigger than 256.') + } + + this.maxMatches = Infinity; + this.matches = 0; + + this._occ = new Array(256) + .fill(needleLength); // Initialize occurrence table. + this._lookbehind_size = 0; + this._needle = needle; + this._bufpos = 0; + + this._lookbehind = Buffer.alloc(needleLength); + + // Populate occurrence table with analysis of the needle, + // ignoring last letter. + for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var + this._occ[needle[i]] = needleLength - 1 - i; + } + } + inherits(SBMH, EventEmitter); + + SBMH.prototype.reset = function () { + this._lookbehind_size = 0; + this.matches = 0; + this._bufpos = 0; + }; + + SBMH.prototype.push = function (chunk, pos) { + if (!Buffer.isBuffer(chunk)) { + chunk = Buffer.from(chunk, 'binary'); + } + const chlen = chunk.length; + this._bufpos = pos || 0; + let r; + while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk); } + return r + }; + + SBMH.prototype._sbmh_feed = function (data) { + const len = data.length; + const needle = this._needle; + const needleLength = needle.length; + const lastNeedleChar = needle[needleLength - 1]; + + // Positive: points to a position in `data` + // pos == 3 points to data[3] + // Negative: points to a position in the lookbehind buffer + // pos == -2 points to lookbehind[lookbehind_size - 2] + let pos = -this._lookbehind_size; + let ch; + + if (pos < 0) { + // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool + // search with character lookup code that considers both the + // lookbehind buffer and the current round's haystack data. + // + // Loop until + // there is a match. + // or until + // we've moved past the position that requires the + // lookbehind buffer. In this case we switch to the + // optimized loop. + // or until + // the character to look at lies outside the haystack. + while (pos < 0 && pos <= len - needleLength) { + ch = this._sbmh_lookup_char(data, pos + needleLength - 1); + + if ( + ch === lastNeedleChar && + this._sbmh_memcmp(data, pos, needleLength - 1) + ) { + this._lookbehind_size = 0; + ++this.matches; + this.emit('info', true); + + return (this._bufpos = pos + needleLength) + } + pos += this._occ[ch]; + } + + // No match. + + if (pos < 0) { + // There's too few data for Boyer-Moore-Horspool to run, + // so let's use a different algorithm to skip as much as + // we can. + // Forward pos until + // the trailing part of lookbehind + data + // looks like the beginning of the needle + // or until + // pos == 0 + while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos; } + } + + if (pos >= 0) { + // Discard lookbehind buffer. + this.emit('info', false, this._lookbehind, 0, this._lookbehind_size); + this._lookbehind_size = 0; + } else { + // Cut off part of the lookbehind buffer that has + // been processed and append the entire haystack + // into it. + const bytesToCutOff = this._lookbehind_size + pos; + if (bytesToCutOff > 0) { + // The cut off data is guaranteed not to contain the needle. + this.emit('info', false, this._lookbehind, 0, bytesToCutOff); + } + + this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, + this._lookbehind_size - bytesToCutOff); + this._lookbehind_size -= bytesToCutOff; + + data.copy(this._lookbehind, this._lookbehind_size); + this._lookbehind_size += len; + + this._bufpos = len; + return len + } + } + + pos += (pos >= 0) * this._bufpos; + + // Lookbehind buffer is now empty. We only need to check if the + // needle is in the haystack. + if (data.indexOf(needle, pos) !== -1) { + pos = data.indexOf(needle, pos); + ++this.matches; + if (pos > 0) { this.emit('info', true, data, this._bufpos, pos); } else { this.emit('info', true); } + + return (this._bufpos = pos + needleLength) + } else { + pos = len - needleLength; + } + + // There was no match. If there's trailing haystack data that we cannot + // match yet using the Boyer-Moore-Horspool algorithm (because the trailing + // data is less than the needle size) then match using a modified + // algorithm that starts matching from the beginning instead of the end. + // Whatever trailing data is left after running this algorithm is added to + // the lookbehind buffer. + while ( + pos < len && + ( + data[pos] !== needle[0] || + ( + (Buffer.compare( + data.subarray(pos, pos + len - pos), + needle.subarray(0, len - pos) + ) !== 0) + ) + ) + ) { + ++pos; + } + if (pos < len) { + data.copy(this._lookbehind, 0, pos, pos + (len - pos)); + this._lookbehind_size = len - pos; + } + + // Everything until pos is guaranteed not to contain needle data. + if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len); } + + this._bufpos = len; + return len + }; + + SBMH.prototype._sbmh_lookup_char = function (data, pos) { + return (pos < 0) + ? this._lookbehind[this._lookbehind_size + pos] + : data[pos] + }; + + SBMH.prototype._sbmh_memcmp = function (data, pos, len) { + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } + } + return true + }; + + sbmh = SBMH; + return sbmh; + } + + var PartStream_1; + var hasRequiredPartStream; + + function requirePartStream () { + if (hasRequiredPartStream) return PartStream_1; + hasRequiredPartStream = 1; + + const inherits = require$$3$2.inherits; + const ReadableStream = require$$0$1.Readable; + + function PartStream (opts) { + ReadableStream.call(this, opts); + } + inherits(PartStream, ReadableStream); + + PartStream.prototype._read = function (n) {}; + + PartStream_1 = PartStream; + return PartStream_1; + } + + var getLimit; + var hasRequiredGetLimit; + + function requireGetLimit () { + if (hasRequiredGetLimit) return getLimit; + hasRequiredGetLimit = 1; + + getLimit = function getLimit (limits, name, defaultLimit) { + if ( + !limits || + limits[name] === undefined || + limits[name] === null + ) { return defaultLimit } + + if ( + typeof limits[name] !== 'number' || + isNaN(limits[name]) + ) { throw new TypeError('Limit ' + name + ' is not a valid number') } + + return limits[name] + }; + return getLimit; + } + + var HeaderParser_1; + var hasRequiredHeaderParser; + + function requireHeaderParser () { + if (hasRequiredHeaderParser) return HeaderParser_1; + hasRequiredHeaderParser = 1; + + const EventEmitter = require$$10$1.EventEmitter; + const inherits = require$$3$2.inherits; + const getLimit = requireGetLimit(); + + const StreamSearch = requireSbmh(); + + const B_DCRLF = Buffer.from('\r\n\r\n'); + const RE_CRLF = /\r\n/g; + const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/; // eslint-disable-line no-control-regex + + function HeaderParser (cfg) { + EventEmitter.call(this); + + cfg = cfg || {}; + const self = this; + this.nread = 0; + this.maxed = false; + this.npairs = 0; + this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000); + this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024); + this.buffer = ''; + this.header = {}; + this.finished = false; + this.ss = new StreamSearch(B_DCRLF); + this.ss.on('info', function (isMatch, data, start, end) { + if (data && !self.maxed) { + if (self.nread + end - start >= self.maxHeaderSize) { + end = self.maxHeaderSize - self.nread + start; + self.nread = self.maxHeaderSize; + self.maxed = true; + } else { self.nread += (end - start); } + + self.buffer += data.toString('binary', start, end); + } + if (isMatch) { self._finish(); } + }); + } + inherits(HeaderParser, EventEmitter); + + HeaderParser.prototype.push = function (data) { + const r = this.ss.push(data); + if (this.finished) { return r } + }; + + HeaderParser.prototype.reset = function () { + this.finished = false; + this.buffer = ''; + this.header = {}; + this.ss.reset(); + }; + + HeaderParser.prototype._finish = function () { + if (this.buffer) { this._parseHeader(); } + this.ss.matches = this.ss.maxMatches; + const header = this.header; + this.header = {}; + this.buffer = ''; + this.finished = true; + this.nread = this.npairs = 0; + this.maxed = false; + this.emit('header', header); + }; + + HeaderParser.prototype._parseHeader = function () { + if (this.npairs === this.maxHeaderPairs) { return } + + const lines = this.buffer.split(RE_CRLF); + const len = lines.length; + let m, h; + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (lines[i].length === 0) { continue } + if (lines[i][0] === '\t' || lines[i][0] === ' ') { + // folded header content + // RFC2822 says to just remove the CRLF and not the whitespace following + // it, so we follow the RFC and include the leading whitespace ... + if (h) { + this.header[h][this.header[h].length - 1] += lines[i]; + continue + } + } + + const posColon = lines[i].indexOf(':'); + if ( + posColon === -1 || + posColon === 0 + ) { + return + } + m = RE_HDR.exec(lines[i]); + h = m[1].toLowerCase(); + this.header[h] = this.header[h] || []; + this.header[h].push((m[2] || '')); + if (++this.npairs === this.maxHeaderPairs) { break } + } + }; + + HeaderParser_1 = HeaderParser; + return HeaderParser_1; + } + + var Dicer_1; + var hasRequiredDicer; + + function requireDicer () { + if (hasRequiredDicer) return Dicer_1; + hasRequiredDicer = 1; + + const WritableStream = require$$0$1.Writable; + const inherits = require$$3$2.inherits; + + const StreamSearch = requireSbmh(); + + const PartStream = requirePartStream(); + const HeaderParser = requireHeaderParser(); + + const DASH = 45; + const B_ONEDASH = Buffer.from('-'); + const B_CRLF = Buffer.from('\r\n'); + const EMPTY_FN = function () {}; + + function Dicer (cfg) { + if (!(this instanceof Dicer)) { return new Dicer(cfg) } + WritableStream.call(this, cfg); + + if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } + + if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary); } else { this._bparser = undefined; } + + this._headerFirst = cfg.headerFirst; + + this._dashes = 0; + this._parts = 0; + this._finished = false; + this._realFinish = false; + this._isPreamble = true; + this._justMatched = false; + this._firstWrite = true; + this._inHeader = true; + this._part = undefined; + this._cb = undefined; + this._ignoreData = false; + this._partOpts = { highWaterMark: cfg.partHwm }; + this._pause = false; + + const self = this; + this._hparser = new HeaderParser(cfg); + this._hparser.on('header', function (header) { + self._inHeader = false; + self._part.emit('header', header); + }); + } + inherits(Dicer, WritableStream); + + Dicer.prototype.emit = function (ev) { + if (ev === 'finish' && !this._realFinish) { + if (!this._finished) { + const self = this; + browser$1$1.nextTick(function () { + self.emit('error', new Error('Unexpected end of multipart data')); + if (self._part && !self._ignoreData) { + const type = (self._isPreamble ? 'Preamble' : 'Part'); + self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')); + self._part.push(null); + browser$1$1.nextTick(function () { + self._realFinish = true; + self.emit('finish'); + self._realFinish = false; + }); + return + } + self._realFinish = true; + self.emit('finish'); + self._realFinish = false; + }); + } + } else { WritableStream.prototype.emit.apply(this, arguments); } + }; + + Dicer.prototype._write = function (data, encoding, cb) { + // ignore unexpected data (e.g. extra trailer data after finished) + if (!this._hparser && !this._bparser) { return cb() } + + if (this._headerFirst && this._isPreamble) { + if (!this._part) { + this._part = new PartStream(this._partOpts); + if (this._events.preamble) { this.emit('preamble', this._part); } else { this._ignore(); } + } + const r = this._hparser.push(data); + if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r); } else { return cb() } + } + + // allows for "easier" testing + if (this._firstWrite) { + this._bparser.push(B_CRLF); + this._firstWrite = false; + } + + this._bparser.push(data); + + if (this._pause) { this._cb = cb; } else { cb(); } + }; + + Dicer.prototype.reset = function () { + this._part = undefined; + this._bparser = undefined; + this._hparser = undefined; + }; + + Dicer.prototype.setBoundary = function (boundary) { + const self = this; + this._bparser = new StreamSearch('\r\n--' + boundary); + this._bparser.on('info', function (isMatch, data, start, end) { + self._oninfo(isMatch, data, start, end); + }); + }; + + Dicer.prototype._ignore = function () { + if (this._part && !this._ignoreData) { + this._ignoreData = true; + this._part.on('error', EMPTY_FN); + // we must perform some kind of read on the stream even though we are + // ignoring the data, otherwise node's Readable stream will not emit 'end' + // after pushing null to the stream + this._part.resume(); + } + }; + + Dicer.prototype._oninfo = function (isMatch, data, start, end) { + let buf; const self = this; let i = 0; let r; let shouldWriteMore = true; + + if (!this._part && this._justMatched && data) { + while (this._dashes < 2 && (start + i) < end) { + if (data[start + i] === DASH) { + ++i; + ++this._dashes; + } else { + if (this._dashes) { buf = B_ONEDASH; } + this._dashes = 0; + break + } + } + if (this._dashes === 2) { + if ((start + i) < end && this._events.trailer) { this.emit('trailer', data.slice(start + i, end)); } + this.reset(); + this._finished = true; + // no more parts will be added + if (self._parts === 0) { + self._realFinish = true; + self.emit('finish'); + self._realFinish = false; + } + } + if (this._dashes) { return } + } + if (this._justMatched) { this._justMatched = false; } + if (!this._part) { + this._part = new PartStream(this._partOpts); + this._part._read = function (n) { + self._unpause(); + }; + if (this._isPreamble && this._events.preamble) { this.emit('preamble', this._part); } else if (this._isPreamble !== true && this._events.part) { this.emit('part', this._part); } else { this._ignore(); } + if (!this._isPreamble) { this._inHeader = true; } + } + if (data && start < end && !this._ignoreData) { + if (this._isPreamble || !this._inHeader) { + if (buf) { shouldWriteMore = this._part.push(buf); } + shouldWriteMore = this._part.push(data.slice(start, end)); + if (!shouldWriteMore) { this._pause = true; } + } else if (!this._isPreamble && this._inHeader) { + if (buf) { this._hparser.push(buf); } + r = this._hparser.push(data.slice(start, end)); + if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end); } + } + } + if (isMatch) { + this._hparser.reset(); + if (this._isPreamble) { this._isPreamble = false; } else { + if (start !== end) { + ++this._parts; + this._part.on('end', function () { + if (--self._parts === 0) { + if (self._finished) { + self._realFinish = true; + self.emit('finish'); + self._realFinish = false; + } else { + self._unpause(); + } + } + }); + } + } + this._part.push(null); + this._part = undefined; + this._ignoreData = false; + this._justMatched = true; + this._dashes = 0; + } + }; + + Dicer.prototype._unpause = function () { + if (!this._pause) { return } + + this._pause = false; + if (this._cb) { + const cb = this._cb; + this._cb = undefined; + cb(); + } + }; + + Dicer_1 = Dicer; + return Dicer_1; + } + + var decodeText_1; + var hasRequiredDecodeText; + + function requireDecodeText () { + if (hasRequiredDecodeText) return decodeText_1; + hasRequiredDecodeText = 1; + + // Node has always utf-8 + const utf8Decoder = new TextDecoder('utf-8'); + const textDecoders = new Map([ + ['utf-8', utf8Decoder], + ['utf8', utf8Decoder] + ]); + + function getDecoder (charset) { + let lc; + while (true) { + switch (charset) { + case 'utf-8': + case 'utf8': + return decoders.utf8 + case 'latin1': + case 'ascii': // TODO: Make these a separate, strict decoder? + case 'us-ascii': + case 'iso-8859-1': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'windows-1252': + case 'iso_8859-1:1987': + case 'cp1252': + case 'x-cp1252': + return decoders.latin1 + case 'utf16le': + case 'utf-16le': + case 'ucs2': + case 'ucs-2': + return decoders.utf16le + case 'base64': + return decoders.base64 + default: + if (lc === undefined) { + lc = true; + charset = charset.toLowerCase(); + continue + } + return decoders.other.bind(charset) + } + } + } + + const decoders = { + utf8: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding); + } + return data.utf8Slice(0, data.length) + }, + + latin1: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + return data + } + return data.latin1Slice(0, data.length) + }, + + utf16le: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding); + } + return data.ucs2Slice(0, data.length) + }, + + base64: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding); + } + return data.base64Slice(0, data.length) + }, + + other: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding); + } + + if (textDecoders.has(this.toString())) { + try { + return textDecoders.get(this).decode(data) + } catch (e) { } + } + return typeof data === 'string' + ? data + : data.toString() + } + }; + + function decodeText (text, sourceEncoding, destEncoding) { + if (text) { + return getDecoder(destEncoding)(text, sourceEncoding) + } + return text + } + + decodeText_1 = decodeText; + return decodeText_1; + } + + /* eslint-disable object-property-newline */ + + var parseParams_1; + var hasRequiredParseParams; + + function requireParseParams () { + if (hasRequiredParseParams) return parseParams_1; + hasRequiredParseParams = 1; + + const decodeText = requireDecodeText(); + + const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g; + + const EncodedLookup = { + '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', + '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', + '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', + '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', + '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', + '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', + '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', + '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', + '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', + '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', + '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', + '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', + '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', + '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', + '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', + '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', + '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', + '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', + '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', + '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', + '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', + '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', + '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', + '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', + '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', + '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', + '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', + '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', + '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', + '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', + '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', + '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', + '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', + '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', + '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', + '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', + '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', + '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', + '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', + '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', + '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', + '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', + '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', + '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', + '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', + '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', + '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', + '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', + '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', + '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', + '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', + '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', + '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', + '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', + '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', + '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', + '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', + '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', + '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', + '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', + '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', + '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', + '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', + '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', + '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', + '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', + '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', + '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', + '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', + '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', + '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', + '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', + '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', + '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', + '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', + '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', + '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', + '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', + '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', + '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', + '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', + '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', + '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', + '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', + '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', + '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', + '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', + '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', + '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', + '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', + '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', + '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', + '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', + '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', + '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', + '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', + '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' + }; + + function encodedReplacer (match) { + return EncodedLookup[match] + } + + const STATE_KEY = 0; + const STATE_VALUE = 1; + const STATE_CHARSET = 2; + const STATE_LANG = 3; + + function parseParams (str) { + const res = []; + let state = STATE_KEY; + let charset = ''; + let inquote = false; + let escaping = false; + let p = 0; + let tmp = ''; + const len = str.length; + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + const char = str[i]; + if (char === '\\' && inquote) { + if (escaping) { escaping = false; } else { + escaping = true; + continue + } + } else if (char === '"') { + if (!escaping) { + if (inquote) { + inquote = false; + state = STATE_KEY; + } else { inquote = true; } + continue + } else { escaping = false; } + } else { + if (escaping && inquote) { tmp += '\\'; } + escaping = false; + if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { + if (state === STATE_CHARSET) { + state = STATE_LANG; + charset = tmp.substring(1); + } else { state = STATE_VALUE; } + tmp = ''; + continue + } else if (state === STATE_KEY && + (char === '*' || char === '=') && + res.length) { + state = char === '*' + ? STATE_CHARSET + : STATE_VALUE; + res[p] = [tmp, undefined]; + tmp = ''; + continue + } else if (!inquote && char === ';') { + state = STATE_KEY; + if (charset) { + if (tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset); + } + charset = ''; + } else if (tmp.length) { + tmp = decodeText(tmp, 'binary', 'utf8'); + } + if (res[p] === undefined) { res[p] = tmp; } else { res[p][1] = tmp; } + tmp = ''; + ++p; + continue + } else if (!inquote && (char === ' ' || char === '\t')) { continue } + } + tmp += char; + } + if (charset && tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset); + } else if (tmp) { + tmp = decodeText(tmp, 'binary', 'utf8'); + } + + if (res[p] === undefined) { + if (tmp) { res[p] = tmp; } + } else { res[p][1] = tmp; } + + return res + } + + parseParams_1 = parseParams; + return parseParams_1; + } + + var basename; + var hasRequiredBasename; + + function requireBasename () { + if (hasRequiredBasename) return basename; + hasRequiredBasename = 1; + + basename = function basename (path) { + if (typeof path !== 'string') { return '' } + for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var + switch (path.charCodeAt(i)) { + case 0x2F: // '/' + case 0x5C: // '\' + path = path.slice(i + 1); + return (path === '..' || path === '.' ? '' : path) + } + } + return (path === '..' || path === '.' ? '' : path) + }; + return basename; + } + + var multipart; + var hasRequiredMultipart; + + function requireMultipart () { + if (hasRequiredMultipart) return multipart; + hasRequiredMultipart = 1; + + // TODO: + // * support 1 nested multipart level + // (see second multipart example here: + // http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) + // * support limits.fieldNameSize + // -- this will require modifications to utils.parseParams + + const { Readable } = require$$0$1; + const { inherits } = require$$3$2; + + const Dicer = requireDicer(); + + const parseParams = requireParseParams(); + const decodeText = requireDecodeText(); + const basename = requireBasename(); + const getLimit = requireGetLimit(); + + const RE_BOUNDARY = /^boundary$/i; + const RE_FIELD = /^form-data$/i; + const RE_CHARSET = /^charset$/i; + const RE_FILENAME = /^filename$/i; + const RE_NAME = /^name$/i; + + Multipart.detect = /^multipart\/form-data/i; + function Multipart (boy, cfg) { + let i; + let len; + const self = this; + let boundary; + const limits = cfg.limits; + const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)); + const parsedConType = cfg.parsedConType || []; + const defCharset = cfg.defCharset || 'utf8'; + const preservePath = cfg.preservePath; + const fileOpts = { highWaterMark: cfg.fileHwm }; + + for (i = 0, len = parsedConType.length; i < len; ++i) { + if (Array.isArray(parsedConType[i]) && + RE_BOUNDARY.test(parsedConType[i][0])) { + boundary = parsedConType[i][1]; + break + } + } + + function checkFinished () { + if (nends === 0 && finished && !boy._done) { + finished = false; + self.end(); + } + } + + if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } + + const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024); + const fileSizeLimit = getLimit(limits, 'fileSize', Infinity); + const filesLimit = getLimit(limits, 'files', Infinity); + const fieldsLimit = getLimit(limits, 'fields', Infinity); + const partsLimit = getLimit(limits, 'parts', Infinity); + const headerPairsLimit = getLimit(limits, 'headerPairs', 2000); + const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024); + + let nfiles = 0; + let nfields = 0; + let nends = 0; + let curFile; + let curField; + let finished = false; + + this._needDrain = false; + this._pause = false; + this._cb = undefined; + this._nparts = 0; + this._boy = boy; + + const parserCfg = { + boundary, + maxHeaderPairs: headerPairsLimit, + maxHeaderSize: headerSizeLimit, + partHwm: fileOpts.highWaterMark, + highWaterMark: cfg.highWaterMark + }; + + this.parser = new Dicer(parserCfg); + this.parser.on('drain', function () { + self._needDrain = false; + if (self._cb && !self._pause) { + const cb = self._cb; + self._cb = undefined; + cb(); + } + }).on('part', function onPart (part) { + if (++self._nparts > partsLimit) { + self.parser.removeListener('part', onPart); + self.parser.on('part', skipPart); + boy.hitPartsLimit = true; + boy.emit('partsLimit'); + return skipPart(part) + } + + // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let + // us emit 'end' early since we know the part has ended if we are already + // seeing the next part + if (curField) { + const field = curField; + field.emit('end'); + field.removeAllListeners('end'); + } + + part.on('header', function (header) { + let contype; + let fieldname; + let parsed; + let charset; + let encoding; + let filename; + let nsize = 0; + + if (header['content-type']) { + parsed = parseParams(header['content-type'][0]); + if (parsed[0]) { + contype = parsed[0].toLowerCase(); + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_CHARSET.test(parsed[i][0])) { + charset = parsed[i][1].toLowerCase(); + break + } + } + } + } + + if (contype === undefined) { contype = 'text/plain'; } + if (charset === undefined) { charset = defCharset; } + + if (header['content-disposition']) { + parsed = parseParams(header['content-disposition'][0]); + if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_NAME.test(parsed[i][0])) { + fieldname = parsed[i][1]; + } else if (RE_FILENAME.test(parsed[i][0])) { + filename = parsed[i][1]; + if (!preservePath) { filename = basename(filename); } + } + } + } else { return skipPart(part) } + + if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase(); } else { encoding = '7bit'; } + + let onData, + onEnd; + + if (isPartAFile(fieldname, contype, filename)) { + // file/binary field + if (nfiles === filesLimit) { + if (!boy.hitFilesLimit) { + boy.hitFilesLimit = true; + boy.emit('filesLimit'); + } + return skipPart(part) + } + + ++nfiles; + + if (!boy._events.file) { + self.parser._ignore(); + return + } + + ++nends; + const file = new FileStream(fileOpts); + curFile = file; + file.on('end', function () { + --nends; + self._pause = false; + checkFinished(); + if (self._cb && !self._needDrain) { + const cb = self._cb; + self._cb = undefined; + cb(); + } + }); + file._read = function (n) { + if (!self._pause) { return } + self._pause = false; + if (self._cb && !self._needDrain) { + const cb = self._cb; + self._cb = undefined; + cb(); + } + }; + boy.emit('file', fieldname, file, filename, encoding, contype); + + onData = function (data) { + if ((nsize += data.length) > fileSizeLimit) { + const extralen = fileSizeLimit - nsize + data.length; + if (extralen > 0) { file.push(data.slice(0, extralen)); } + file.truncated = true; + file.bytesRead = fileSizeLimit; + part.removeAllListeners('data'); + file.emit('limit'); + return + } else if (!file.push(data)) { self._pause = true; } + + file.bytesRead = nsize; + }; + + onEnd = function () { + curFile = undefined; + file.push(null); + }; + } else { + // non-file field + if (nfields === fieldsLimit) { + if (!boy.hitFieldsLimit) { + boy.hitFieldsLimit = true; + boy.emit('fieldsLimit'); + } + return skipPart(part) + } + + ++nfields; + ++nends; + let buffer = ''; + let truncated = false; + curField = part; + + onData = function (data) { + if ((nsize += data.length) > fieldSizeLimit) { + const extralen = (fieldSizeLimit - (nsize - data.length)); + buffer += data.toString('binary', 0, extralen); + truncated = true; + part.removeAllListeners('data'); + } else { buffer += data.toString('binary'); } + }; + + onEnd = function () { + curField = undefined; + if (buffer.length) { buffer = decodeText(buffer, 'binary', charset); } + boy.emit('field', fieldname, buffer, false, truncated, encoding, contype); + --nends; + checkFinished(); + }; + } + + /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become + broken. Streams2/streams3 is a huge black box of confusion, but + somehow overriding the sync state seems to fix things again (and still + seems to work for previous node versions). + */ + part._readableState.sync = false; + + part.on('data', onData); + part.on('end', onEnd); + }).on('error', function (err) { + if (curFile) { curFile.emit('error', err); } + }); + }).on('error', function (err) { + boy.emit('error', err); + }).on('finish', function () { + finished = true; + checkFinished(); + }); + } + + Multipart.prototype.write = function (chunk, cb) { + const r = this.parser.write(chunk); + if (r && !this._pause) { + cb(); + } else { + this._needDrain = !r; + this._cb = cb; + } + }; + + Multipart.prototype.end = function () { + const self = this; + + if (self.parser.writable) { + self.parser.end(); + } else if (!self._boy._done) { + browser$1$1.nextTick(function () { + self._boy._done = true; + self._boy.emit('finish'); + }); + } + }; + + function skipPart (part) { + part.resume(); + } + + function FileStream (opts) { + Readable.call(this, opts); + + this.bytesRead = 0; + + this.truncated = false; + } + + inherits(FileStream, Readable); + + FileStream.prototype._read = function (n) {}; + + multipart = Multipart; + return multipart; + } + + var Decoder_1; + var hasRequiredDecoder; + + function requireDecoder () { + if (hasRequiredDecoder) return Decoder_1; + hasRequiredDecoder = 1; + + const RE_PLUS = /\+/g; + + const HEX = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 + ]; + + function Decoder () { + this.buffer = undefined; + } + Decoder.prototype.write = function (str) { + // Replace '+' with ' ' before decoding + str = str.replace(RE_PLUS, ' '); + let res = ''; + let i = 0; let p = 0; const len = str.length; + for (; i < len; ++i) { + if (this.buffer !== undefined) { + if (!HEX[str.charCodeAt(i)]) { + res += '%' + this.buffer; + this.buffer = undefined; + --i; // retry character + } else { + this.buffer += str[i]; + ++p; + if (this.buffer.length === 2) { + res += String.fromCharCode(parseInt(this.buffer, 16)); + this.buffer = undefined; + } + } + } else if (str[i] === '%') { + if (i > p) { + res += str.substring(p, i); + p = i; + } + this.buffer = ''; + ++p; + } + } + if (p < len && this.buffer === undefined) { res += str.substring(p); } + return res + }; + Decoder.prototype.reset = function () { + this.buffer = undefined; + }; + + Decoder_1 = Decoder; + return Decoder_1; + } + + var urlencoded; + var hasRequiredUrlencoded; + + function requireUrlencoded () { + if (hasRequiredUrlencoded) return urlencoded; + hasRequiredUrlencoded = 1; + + const Decoder = requireDecoder(); + const decodeText = requireDecodeText(); + const getLimit = requireGetLimit(); + + const RE_CHARSET = /^charset$/i; + + UrlEncoded.detect = /^application\/x-www-form-urlencoded/i; + function UrlEncoded (boy, cfg) { + const limits = cfg.limits; + const parsedConType = cfg.parsedConType; + this.boy = boy; + + this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024); + this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100); + this.fieldsLimit = getLimit(limits, 'fields', Infinity); + + let charset; + for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var + if (Array.isArray(parsedConType[i]) && + RE_CHARSET.test(parsedConType[i][0])) { + charset = parsedConType[i][1].toLowerCase(); + break + } + } + + if (charset === undefined) { charset = cfg.defCharset || 'utf8'; } + + this.decoder = new Decoder(); + this.charset = charset; + this._fields = 0; + this._state = 'key'; + this._checkingBytes = true; + this._bytesKey = 0; + this._bytesVal = 0; + this._key = ''; + this._val = ''; + this._keyTrunc = false; + this._valTrunc = false; + this._hitLimit = false; + } + + UrlEncoded.prototype.write = function (data, cb) { + if (this._fields === this.fieldsLimit) { + if (!this.boy.hitFieldsLimit) { + this.boy.hitFieldsLimit = true; + this.boy.emit('fieldsLimit'); + } + return cb() + } + + let idxeq; let idxamp; let i; let p = 0; const len = data.length; + + while (p < len) { + if (this._state === 'key') { + idxeq = idxamp = undefined; + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p; } + if (data[i] === 0x3D/* = */) { + idxeq = i; + break + } else if (data[i] === 0x26/* & */) { + idxamp = i; + break + } + if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { + this._hitLimit = true; + break + } else if (this._checkingBytes) { ++this._bytesKey; } + } + + if (idxeq !== undefined) { + // key with assignment + if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)); } + this._state = 'val'; + + this._hitLimit = false; + this._checkingBytes = true; + this._val = ''; + this._bytesVal = 0; + this._valTrunc = false; + this.decoder.reset(); + + p = idxeq + 1; + } else if (idxamp !== undefined) { + // key with no assignment + ++this._fields; + let key; const keyTrunc = this._keyTrunc; + if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))); } else { key = this._key; } + + this._hitLimit = false; + this._checkingBytes = true; + this._key = ''; + this._bytesKey = 0; + this._keyTrunc = false; + this.decoder.reset(); + + if (key.length) { + this.boy.emit('field', decodeText(key, 'binary', this.charset), + '', + keyTrunc, + false); + } + + p = idxamp + 1; + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)); } + p = i; + if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false; + this._keyTrunc = true; + } + } else { + if (p < len) { this._key += this.decoder.write(data.toString('binary', p)); } + p = len; + } + } else { + idxamp = undefined; + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p; } + if (data[i] === 0x26/* & */) { + idxamp = i; + break + } + if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { + this._hitLimit = true; + break + } else if (this._checkingBytes) { ++this._bytesVal; } + } + + if (idxamp !== undefined) { + ++this._fields; + if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)); } + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc); + this._state = 'key'; + + this._hitLimit = false; + this._checkingBytes = true; + this._key = ''; + this._bytesKey = 0; + this._keyTrunc = false; + this.decoder.reset(); + + p = idxamp + 1; + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)); } + p = i; + if ((this._val === '' && this.fieldSizeLimit === 0) || + (this._bytesVal = this._val.length) === this.fieldSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false; + this._valTrunc = true; + } + } else { + if (p < len) { this._val += this.decoder.write(data.toString('binary', p)); } + p = len; + } + } + } + cb(); + }; + + UrlEncoded.prototype.end = function () { + if (this.boy._done) { return } + + if (this._state === 'key' && this._key.length > 0) { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + '', + this._keyTrunc, + false); + } else if (this._state === 'val') { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc); + } + this.boy._done = true; + this.boy.emit('finish'); + }; + + urlencoded = UrlEncoded; + return urlencoded; + } + + var hasRequiredMain; + + function requireMain () { + if (hasRequiredMain) return main.exports; + hasRequiredMain = 1; + + const WritableStream = require$$0$1.Writable; + const { inherits } = require$$3$2; + const Dicer = requireDicer(); + + const MultipartParser = requireMultipart(); + const UrlencodedParser = requireUrlencoded(); + const parseParams = requireParseParams(); + + function Busboy (opts) { + if (!(this instanceof Busboy)) { return new Busboy(opts) } + + if (typeof opts !== 'object') { + throw new TypeError('Busboy expected an options-Object.') + } + if (typeof opts.headers !== 'object') { + throw new TypeError('Busboy expected an options-Object with headers-attribute.') + } + if (typeof opts.headers['content-type'] !== 'string') { + throw new TypeError('Missing Content-Type-header.') + } + + const { + headers, + ...streamOptions + } = opts; + + this.opts = { + autoDestroy: false, + ...streamOptions + }; + WritableStream.call(this, this.opts); + + this._done = false; + this._parser = this.getParserByHeaders(headers); + this._finished = false; + } + inherits(Busboy, WritableStream); + + Busboy.prototype.emit = function (ev) { + if (ev === 'finish') { + if (!this._done) { + this._parser?.end(); + return + } else if (this._finished) { + return + } + this._finished = true; + } + WritableStream.prototype.emit.apply(this, arguments); + }; + + Busboy.prototype.getParserByHeaders = function (headers) { + const parsed = parseParams(headers['content-type']); + + const cfg = { + defCharset: this.opts.defCharset, + fileHwm: this.opts.fileHwm, + headers, + highWaterMark: this.opts.highWaterMark, + isPartAFile: this.opts.isPartAFile, + limits: this.opts.limits, + parsedConType: parsed, + preservePath: this.opts.preservePath + }; + + if (MultipartParser.detect.test(parsed[0])) { + return new MultipartParser(this, cfg) + } + if (UrlencodedParser.detect.test(parsed[0])) { + return new UrlencodedParser(this, cfg) + } + throw new Error('Unsupported Content-Type.') + }; + + Busboy.prototype._write = function (chunk, encoding, cb) { + this._parser.write(chunk, cb); + }; + + main.exports = Busboy; + main.exports.default = Busboy; + main.exports.Busboy = Busboy; + + main.exports.Dicer = Dicer; + return main.exports; + } + + var worker_threads_polyfillNodeIgnore = /*#__PURE__*/Object.freeze({ + __proto__: null + }); + + var require$$2$1 = /*@__PURE__*/getAugmentedNamespace(worker_threads_polyfillNodeIgnore); + + var constants$5; + var hasRequiredConstants$3; + + function requireConstants$3 () { + if (hasRequiredConstants$3) return constants$5; + hasRequiredConstants$3 = 1; + + const { MessageChannel, receiveMessageOnPort } = require$$2$1; + + const corsSafeListedMethods = ['GET', 'HEAD', 'POST']; + + const nullBodyStatus = [101, 204, 205, 304]; + + const redirectStatus = [301, 302, 303, 307, 308]; + + // https://fetch.spec.whatwg.org/#block-bad-port + const badPorts = [ + '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', + '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', + '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', + '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', + '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697', + '10080' + ]; + + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policies + const referrerPolicy = [ + '', + 'no-referrer', + 'no-referrer-when-downgrade', + 'same-origin', + 'origin', + 'strict-origin', + 'origin-when-cross-origin', + 'strict-origin-when-cross-origin', + 'unsafe-url' + ]; + + const requestRedirect = ['follow', 'manual', 'error']; + + const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE']; + + const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors']; + + const requestCredentials = ['omit', 'same-origin', 'include']; + + const requestCache = [ + 'default', + 'no-store', + 'reload', + 'no-cache', + 'force-cache', + 'only-if-cached' + ]; + + // https://fetch.spec.whatwg.org/#request-body-header-name + const requestBodyHeader = [ + 'content-encoding', + 'content-language', + 'content-location', + 'content-type', + // See https://github.com/nodejs/undici/issues/2021 + // 'Content-Length' is a forbidden header name, which is typically + // removed in the Headers implementation. However, undici doesn't + // filter out headers, so we add it here. + 'content-length' + ]; + + // https://fetch.spec.whatwg.org/#enumdef-requestduplex + const requestDuplex = [ + 'half' + ]; + + // http://fetch.spec.whatwg.org/#forbidden-method + const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK']; + + const subresource = [ + 'audio', + 'audioworklet', + 'font', + 'image', + 'manifest', + 'paintworklet', + 'script', + 'style', + 'track', + 'video', + 'xslt', + '' + ]; + + /** @type {globalThis['DOMException']} */ + const DOMException = globalThis.DOMException ?? (() => { + // DOMException was only made a global in Node v17.0.0, + // but fetch supports >= v16.8. + try { + atob('~'); + } catch (err) { + return Object.getPrototypeOf(err).constructor + } + })(); + + let channel; + + /** @type {globalThis['structuredClone']} */ + const structuredClone = + globalThis.structuredClone ?? + // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js + // structuredClone was added in v17.0.0, but fetch supports v16.8 + function structuredClone (value, options = undefined) { + if (arguments.length === 0) { + throw new TypeError('missing argument') + } + + if (!channel) { + channel = new MessageChannel(); + } + channel.port1.unref(); + channel.port2.unref(); + channel.port1.postMessage(value, options?.transfer); + return receiveMessageOnPort(channel.port2).message + }; + + constants$5 = { + DOMException, + structuredClone, + subresource, + forbiddenMethods, + requestBodyHeader, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + redirectStatus, + corsSafeListedMethods, + nullBodyStatus, + safeMethods, + badPorts, + requestDuplex + }; + return constants$5; + } + + var global$2; + var hasRequiredGlobal; + + function requireGlobal () { + if (hasRequiredGlobal) return global$2; + hasRequiredGlobal = 1; + + // In case of breaking changes, increase the version + // number to avoid conflicts. + const globalOrigin = Symbol.for('undici.globalOrigin.1'); + + function getGlobalOrigin () { + return globalThis[globalOrigin] + } + + function setGlobalOrigin (newOrigin) { + if (newOrigin === undefined) { + Object.defineProperty(globalThis, globalOrigin, { + value: undefined, + writable: true, + enumerable: false, + configurable: false + }); + + return + } + + const parsedURL = new URL(newOrigin); + + if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { + throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) + } + + Object.defineProperty(globalThis, globalOrigin, { + value: parsedURL, + writable: true, + enumerable: false, + configurable: false + }); + } + + global$2 = { + getGlobalOrigin, + setGlobalOrigin + }; + return global$2; + } + + var _polyfillNode_perf_hooks = {}; + + var _polyfillNode_perf_hooks$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + default: _polyfillNode_perf_hooks + }); + + var require$$2 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_perf_hooks$1); + + var types_polyfillNodeIgnore = /*#__PURE__*/Object.freeze({ + __proto__: null + }); + + var require$$10 = /*@__PURE__*/getAugmentedNamespace(types_polyfillNodeIgnore); + + var _polyfillNode_crypto = {}; + + var _polyfillNode_crypto$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + default: _polyfillNode_crypto + }); + + var require$$6$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_crypto$1); + + var util$k; + var hasRequiredUtil$4; + + function requireUtil$4 () { + if (hasRequiredUtil$4) return util$k; + hasRequiredUtil$4 = 1; + + const { redirectStatus, badPorts, referrerPolicy: referrerPolicyTokens } = requireConstants$3(); + const { getGlobalOrigin } = requireGlobal(); + const { performance } = require$$2; + const { isBlobLike, toUSVString, ReadableStreamFrom } = util$l; + const assert = require$$3$1; + const { isUint8Array } = require$$10; + + // https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable + /** @type {import('crypto')|undefined} */ + let crypto; + + try { + crypto = require$$6$1; + } catch { + + } + + function responseURL (response) { + // https://fetch.spec.whatwg.org/#responses + // A response has an associated URL. It is a pointer to the last URL + // in response’s URL list and null if response’s URL list is empty. + const urlList = response.urlList; + const length = urlList.length; + return length === 0 ? null : urlList[length - 1].toString() + } + + // https://fetch.spec.whatwg.org/#concept-response-location-url + function responseLocationURL (response, requestFragment) { + // 1. If response’s status is not a redirect status, then return null. + if (!redirectStatus.includes(response.status)) { + return null + } + + // 2. Let location be the result of extracting header list values given + // `Location` and response’s header list. + let location = response.headersList.get('location'); + + // 3. If location is a header value, then set location to the result of + // parsing location with response’s URL. + if (location !== null && isValidHeaderValue(location)) { + location = new URL(location, responseURL(response)); + } + + // 4. If location is a URL whose fragment is null, then set location’s + // fragment to requestFragment. + if (location && !location.hash) { + location.hash = requestFragment; + } + + // 5. Return location. + return location + } + + /** @returns {URL} */ + function requestCurrentURL (request) { + return request.urlList[request.urlList.length - 1] + } + + function requestBadPort (request) { + // 1. Let url be request’s current URL. + const url = requestCurrentURL(request); + + // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, + // then return blocked. + if (urlIsHttpHttpsScheme(url) && badPorts.includes(url.port)) { + return 'blocked' + } + + // 3. Return allowed. + return 'allowed' + } + + function isErrorLike (object) { + return object instanceof Error || ( + object?.constructor?.name === 'Error' || + object?.constructor?.name === 'DOMException' + ) + } + + // Check whether |statusText| is a ByteString and + // matches the Reason-Phrase token production. + // RFC 2616: https://tools.ietf.org/html/rfc2616 + // RFC 7230: https://tools.ietf.org/html/rfc7230 + // "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" + // https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 + function isValidReasonPhrase (statusText) { + for (let i = 0; i < statusText.length; ++i) { + const c = statusText.charCodeAt(i); + if ( + !( + ( + c === 0x09 || // HTAB + (c >= 0x20 && c <= 0x7e) || // SP / VCHAR + (c >= 0x80 && c <= 0xff) + ) // obs-text + ) + ) { + return false + } + } + return true + } + + function isTokenChar (c) { + return !( + c >= 0x7f || + c <= 0x20 || + c === '(' || + c === ')' || + c === '<' || + c === '>' || + c === '@' || + c === ',' || + c === ';' || + c === ':' || + c === '\\' || + c === '"' || + c === '/' || + c === '[' || + c === ']' || + c === '?' || + c === '=' || + c === '{' || + c === '}' + ) + } + + // See RFC 7230, Section 3.2.6. + // https://github.com/chromium/chromium/blob/d7da0240cae77824d1eda25745c4022757499131/third_party/blink/renderer/platform/network/http_parsers.cc#L321 + function isValidHTTPToken (characters) { + if (!characters || typeof characters !== 'string') { + return false + } + for (let i = 0; i < characters.length; ++i) { + const c = characters.charCodeAt(i); + if (c > 0x7f || !isTokenChar(c)) { + return false + } + } + return true + } + + // https://fetch.spec.whatwg.org/#header-name + // https://github.com/chromium/chromium/blob/b3d37e6f94f87d59e44662d6078f6a12de845d17/net/http/http_util.cc#L342 + function isValidHeaderName (potentialValue) { + if (potentialValue.length === 0) { + return false + } + + return isValidHTTPToken(potentialValue) + } + + /** + * @see https://fetch.spec.whatwg.org/#header-value + * @param {string} potentialValue + */ + function isValidHeaderValue (potentialValue) { + // - Has no leading or trailing HTTP tab or space bytes. + // - Contains no 0x00 (NUL) or HTTP newline bytes. + if ( + potentialValue.startsWith('\t') || + potentialValue.startsWith(' ') || + potentialValue.endsWith('\t') || + potentialValue.endsWith(' ') + ) { + return false + } + + if ( + potentialValue.includes('\0') || + potentialValue.includes('\r') || + potentialValue.includes('\n') + ) { + return false + } + + return true + } + + // https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect + function setRequestReferrerPolicyOnRedirect (request, actualResponse) { + // Given a request request and a response actualResponse, this algorithm + // updates request’s referrer policy according to the Referrer-Policy + // header (if any) in actualResponse. + + // 1. Let policy be the result of executing § 8.1 Parse a referrer policy + // from a Referrer-Policy header on actualResponse. + + // 8.1 Parse a referrer policy from a Referrer-Policy header + // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. + const { headersList } = actualResponse; + // 2. Let policy be the empty string. + // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. + // 4. Return policy. + const policyHeader = (headersList.get('referrer-policy') ?? '').split(','); + + // Note: As the referrer-policy can contain multiple policies + // separated by comma, we need to loop through all of them + // and pick the first valid one. + // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy + let policy = ''; + if (policyHeader.length > 0) { + // The right-most policy takes precedence. + // The left-most policy is the fallback. + for (let i = policyHeader.length; i !== 0; i--) { + const token = policyHeader[i - 1].trim(); + if (referrerPolicyTokens.includes(token)) { + policy = token; + break + } + } + } + + // 2. If policy is not the empty string, then set request’s referrer policy to policy. + if (policy !== '') { + request.referrerPolicy = policy; + } + } + + // https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check + function crossOriginResourcePolicyCheck () { + // TODO + return 'allowed' + } + + // https://fetch.spec.whatwg.org/#concept-cors-check + function corsCheck () { + // TODO + return 'success' + } + + // https://fetch.spec.whatwg.org/#concept-tao-check + function TAOCheck () { + // TODO + return 'success' + } + + function appendFetchMetadata (httpRequest) { + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header + + // 1. Assert: r’s url is a potentially trustworthy URL. + // TODO + + // 2. Let header be a Structured Header whose value is a token. + let header = null; + + // 3. Set header’s value to r’s mode. + header = httpRequest.mode; + + // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. + httpRequest.headersList.set('sec-fetch-mode', header); + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header + // TODO + } + + // https://fetch.spec.whatwg.org/#append-a-request-origin-header + function appendRequestOriginHeader (request) { + // 1. Let serializedOrigin be the result of byte-serializing a request origin with request. + let serializedOrigin = request.origin; + + // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list. + if (request.responseTainting === 'cors' || request.mode === 'websocket') { + if (serializedOrigin) { + request.headersList.append('origin', serializedOrigin); + } + + // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: + } else if (request.method !== 'GET' && request.method !== 'HEAD') { + // 1. Switch on request’s referrer policy: + switch (request.referrerPolicy) { + case 'no-referrer': + // Set serializedOrigin to `null`. + serializedOrigin = null; + break + case 'no-referrer-when-downgrade': + case 'strict-origin': + case 'strict-origin-when-cross-origin': + // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`. + if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { + serializedOrigin = null; + } + break + case 'same-origin': + // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`. + if (!sameOrigin(request, requestCurrentURL(request))) { + serializedOrigin = null; + } + break + // Do nothing. + } + + if (serializedOrigin) { + // 2. Append (`Origin`, serializedOrigin) to request’s header list. + request.headersList.append('origin', serializedOrigin); + } + } + } + + function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { + // TODO + return performance.now() + } + + // https://fetch.spec.whatwg.org/#create-an-opaque-timing-info + function createOpaqueTimingInfo (timingInfo) { + return { + startTime: timingInfo.startTime ?? 0, + redirectStartTime: 0, + redirectEndTime: 0, + postRedirectStartTime: timingInfo.startTime ?? 0, + finalServiceWorkerStartTime: 0, + finalNetworkResponseStartTime: 0, + finalNetworkRequestStartTime: 0, + endTime: 0, + encodedBodySize: 0, + decodedBodySize: 0, + finalConnectionTimingInfo: null + } + } + + // https://html.spec.whatwg.org/multipage/origin.html#policy-container + function makePolicyContainer () { + // Note: the fetch spec doesn't make use of embedder policy or CSP list + return { + referrerPolicy: 'strict-origin-when-cross-origin' + } + } + + // https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container + function clonePolicyContainer (policyContainer) { + return { + referrerPolicy: policyContainer.referrerPolicy + } + } + + // https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer + function determineRequestsReferrer (request) { + // 1. Let policy be request's referrer policy. + const policy = request.referrerPolicy; + + // Note: policy cannot (shouldn't) be null or an empty string. + assert(policy); + + // 2. Let environment be request’s client. + + let referrerSource = null; + + // 3. Switch on request’s referrer: + if (request.referrer === 'client') { + // Note: node isn't a browser and doesn't implement document/iframes, + // so we bypass this step and replace it with our own. + + const globalOrigin = getGlobalOrigin(); + + if (!globalOrigin || globalOrigin.origin === 'null') { + return 'no-referrer' + } + + // note: we need to clone it as it's mutated + referrerSource = new URL(globalOrigin); + } else if (request.referrer instanceof URL) { + // Let referrerSource be request’s referrer. + referrerSource = request.referrer; + } + + // 4. Let request’s referrerURL be the result of stripping referrerSource for + // use as a referrer. + let referrerURL = stripURLForReferrer(referrerSource); + + // 5. Let referrerOrigin be the result of stripping referrerSource for use as + // a referrer, with the origin-only flag set to true. + const referrerOrigin = stripURLForReferrer(referrerSource, true); + + // 6. If the result of serializing referrerURL is a string whose length is + // greater than 4096, set referrerURL to referrerOrigin. + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin; + } + + const areSameOrigin = sameOrigin(request, referrerURL); + const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && + !isURLPotentiallyTrustworthy(request.url); + + // 8. Execute the switch statements corresponding to the value of policy: + switch (policy) { + case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true) + case 'unsafe-url': return referrerURL + case 'same-origin': + return areSameOrigin ? referrerOrigin : 'no-referrer' + case 'origin-when-cross-origin': + return areSameOrigin ? referrerURL : referrerOrigin + case 'strict-origin-when-cross-origin': { + const currentURL = requestCurrentURL(request); + + // 1. If the origin of referrerURL and the origin of request’s current + // URL are the same, then return referrerURL. + if (sameOrigin(referrerURL, currentURL)) { + return referrerURL + } + + // 2. If referrerURL is a potentially trustworthy URL and request’s + // current URL is not a potentially trustworthy URL, then return no + // referrer. + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return 'no-referrer' + } + + // 3. Return referrerOrigin. + return referrerOrigin + } + case 'strict-origin': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + case 'no-referrer-when-downgrade': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + + default: // eslint-disable-line + return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin + } + } + + /** + * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url + * @param {URL} url + * @param {boolean|undefined} originOnly + */ + function stripURLForReferrer (url, originOnly) { + // 1. Assert: url is a URL. + assert(url instanceof URL); + + // 2. If url’s scheme is a local scheme, then return no referrer. + if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') { + return 'no-referrer' + } + + // 3. Set url’s username to the empty string. + url.username = ''; + + // 4. Set url’s password to the empty string. + url.password = ''; + + // 5. Set url’s fragment to null. + url.hash = ''; + + // 6. If the origin-only flag is true, then: + if (originOnly) { + // 1. Set url’s path to « the empty string ». + url.pathname = ''; + + // 2. Set url’s query to null. + url.search = ''; + } + + // 7. Return url. + return url + } + + function isURLPotentiallyTrustworthy (url) { + if (!(url instanceof URL)) { + return false + } + + // If child of about, return true + if (url.href === 'about:blank' || url.href === 'about:srcdoc') { + return true + } + + // If scheme is data, return true + if (url.protocol === 'data:') return true + + // If file, return true + if (url.protocol === 'file:') return true + + return isOriginPotentiallyTrustworthy(url.origin) + + function isOriginPotentiallyTrustworthy (origin) { + // If origin is explicitly null, return false + if (origin == null || origin === 'null') return false + + const originAsURL = new URL(origin); + + // If secure, return true + if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { + return true + } + + // If localhost or variants, return true + if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || + (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) || + (originAsURL.hostname.endsWith('.localhost'))) { + return true + } + + // If any other, return false + return false + } + } + + /** + * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist + * @param {Uint8Array} bytes + * @param {string} metadataList + */ + function bytesMatch (bytes, metadataList) { + // If node is not built with OpenSSL support, we cannot check + // a request's integrity, so allow it by default (the spec will + // allow requests if an invalid hash is given, as precedence). + /* istanbul ignore if: only if node is built with --without-ssl */ + if (crypto === undefined) { + return true + } + + // 1. Let parsedMetadata be the result of parsing metadataList. + const parsedMetadata = parseMetadata(metadataList); + + // 2. If parsedMetadata is no metadata, return true. + if (parsedMetadata === 'no metadata') { + return true + } + + // 3. If parsedMetadata is the empty set, return true. + if (parsedMetadata.length === 0) { + return true + } + + // 4. Let metadata be the result of getting the strongest + // metadata from parsedMetadata. + const list = parsedMetadata.sort((c, d) => d.algo.localeCompare(c.algo)); + // get the strongest algorithm + const strongest = list[0].algo; + // get all entries that use the strongest algorithm; ignore weaker + const metadata = list.filter((item) => item.algo === strongest); + + // 5. For each item in metadata: + for (const item of metadata) { + // 1. Let algorithm be the alg component of item. + const algorithm = item.algo; + + // 2. Let expectedValue be the val component of item. + let expectedValue = item.hash; + + // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e + // "be liberal with padding". This is annoying, and it's not even in the spec. + + if (expectedValue.endsWith('==')) { + expectedValue = expectedValue.slice(0, -2); + } + + // 3. Let actualValue be the result of applying algorithm to bytes. + let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64'); + + if (actualValue.endsWith('==')) { + actualValue = actualValue.slice(0, -2); + } + + // 4. If actualValue is a case-sensitive match for expectedValue, + // return true. + if (actualValue === expectedValue) { + return true + } + + let actualBase64URL = crypto.createHash(algorithm).update(bytes).digest('base64url'); + + if (actualBase64URL.endsWith('==')) { + actualBase64URL = actualBase64URL.slice(0, -2); + } + + if (actualBase64URL === expectedValue) { + return true + } + } + + // 6. Return false. + return false + } + + // https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options + // https://www.w3.org/TR/CSP2/#source-list-syntax + // https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 + const parseHashWithOptions = /((?sha256|sha384|sha512)-(?[A-z0-9+/]{1}.*={0,2}))( +[\x21-\x7e]?)?/i; + + /** + * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata + * @param {string} metadata + */ + function parseMetadata (metadata) { + // 1. Let result be the empty set. + /** @type {{ algo: string, hash: string }[]} */ + const result = []; + + // 2. Let empty be equal to true. + let empty = true; + + const supportedHashes = crypto.getHashes(); + + // 3. For each token returned by splitting metadata on spaces: + for (const token of metadata.split(' ')) { + // 1. Set empty to false. + empty = false; + + // 2. Parse token as a hash-with-options. + const parsedToken = parseHashWithOptions.exec(token); + + // 3. If token does not parse, continue to the next token. + if (parsedToken === null || parsedToken.groups === undefined) { + // Note: Chromium blocks the request at this point, but Firefox + // gives a warning that an invalid integrity was given. The + // correct behavior is to ignore these, and subsequently not + // check the integrity of the resource. + continue + } + + // 4. Let algorithm be the hash-algo component of token. + const algorithm = parsedToken.groups.algo; + + // 5. If algorithm is a hash function recognized by the user + // agent, add the parsed token to result. + if (supportedHashes.includes(algorithm.toLowerCase())) { + result.push(parsedToken.groups); + } + } + + // 4. Return no metadata if empty is true, otherwise return result. + if (empty === true) { + return 'no metadata' + } + + return result + } + + // https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request + function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { + // TODO + } + + /** + * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} + * @param {URL} A + * @param {URL} B + */ + function sameOrigin (A, B) { + // 1. If A and B are the same opaque origin, then return true. + if (A.origin === B.origin && A.origin === 'null') { + return true + } + + // 2. If A and B are both tuple origins and their schemes, + // hosts, and port are identical, then return true. + if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { + return true + } + + // 3. Return false. + return false + } + + function createDeferredPromise () { + let res; + let rej; + const promise = new Promise((resolve, reject) => { + res = resolve; + rej = reject; + }); + + return { promise, resolve: res, reject: rej } + } + + function isAborted (fetchParams) { + return fetchParams.controller.state === 'aborted' + } + + function isCancelled (fetchParams) { + return fetchParams.controller.state === 'aborted' || + fetchParams.controller.state === 'terminated' + } + + // https://fetch.spec.whatwg.org/#concept-method-normalize + function normalizeMethod (method) { + return /^(DELETE|GET|HEAD|OPTIONS|POST|PUT)$/i.test(method) + ? method.toUpperCase() + : method + } + + // https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string + function serializeJavascriptValueToJSONString (value) { + // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). + const result = JSON.stringify(value); + + // 2. If result is undefined, then throw a TypeError. + if (result === undefined) { + throw new TypeError('Value is not JSON serializable') + } + + // 3. Assert: result is a string. + assert(typeof result === 'string'); + + // 4. Return result. + return result + } + + // https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object + const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())); + + /** + * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + * @param {() => unknown[]} iterator + * @param {string} name name of the instance + * @param {'key'|'value'|'key+value'} kind + */ + function makeIterator (iterator, name, kind) { + const object = { + index: 0, + kind, + target: iterator + }; + + const i = { + next () { + // 1. Let interface be the interface for which the iterator prototype object exists. + + // 2. Let thisValue be the this value. + + // 3. Let object be ? ToObject(thisValue). + + // 4. If object is a platform object, then perform a security + // check, passing: + + // 5. If object is not a default iterator object for interface, + // then throw a TypeError. + if (Object.getPrototypeOf(this) !== i) { + throw new TypeError( + `'next' called on an object that does not implement interface ${name} Iterator.` + ) + } + + // 6. Let index be object’s index. + // 7. Let kind be object’s kind. + // 8. Let values be object’s target's value pairs to iterate over. + const { index, kind, target } = object; + const values = target(); + + // 9. Let len be the length of values. + const len = values.length; + + // 10. If index is greater than or equal to len, then return + // CreateIterResultObject(undefined, true). + if (index >= len) { + return { value: undefined, done: true } + } + + // 11. Let pair be the entry in values at index index. + const pair = values[index]; + + // 12. Set object’s index to index + 1. + object.index = index + 1; + + // 13. Return the iterator result for pair and kind. + return iteratorResult(pair, kind) + }, + // The class string of an iterator prototype object for a given interface is the + // result of concatenating the identifier of the interface and the string " Iterator". + [Symbol.toStringTag]: `${name} Iterator` + }; + + // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%. + Object.setPrototypeOf(i, esIteratorPrototype); + // esIteratorPrototype needs to be the prototype of i + // which is the prototype of an empty object. Yes, it's confusing. + return Object.setPrototypeOf({}, i) + } + + // https://webidl.spec.whatwg.org/#iterator-result + function iteratorResult (pair, kind) { + let result; + + // 1. Let result be a value determined by the value of kind: + switch (kind) { + case 'key': { + // 1. Let idlKey be pair’s key. + // 2. Let key be the result of converting idlKey to an + // ECMAScript value. + // 3. result is key. + result = pair[0]; + break + } + case 'value': { + // 1. Let idlValue be pair’s value. + // 2. Let value be the result of converting idlValue to + // an ECMAScript value. + // 3. result is value. + result = pair[1]; + break + } + case 'key+value': { + // 1. Let idlKey be pair’s key. + // 2. Let idlValue be pair’s value. + // 3. Let key be the result of converting idlKey to an + // ECMAScript value. + // 4. Let value be the result of converting idlValue to + // an ECMAScript value. + // 5. Let array be ! ArrayCreate(2). + // 6. Call ! CreateDataProperty(array, "0", key). + // 7. Call ! CreateDataProperty(array, "1", value). + // 8. result is array. + result = pair; + break + } + } + + // 2. Return CreateIterResultObject(result, false). + return { value: result, done: false } + } + + /** + * @see https://fetch.spec.whatwg.org/#body-fully-read + */ + async function fullyReadBody (body, processBody, processBodyError) { + // 1. If taskDestination is null, then set taskDestination to + // the result of starting a new parallel queue. + + // 2. Let successSteps given a byte sequence bytes be to queue a + // fetch task to run processBody given bytes, with taskDestination. + const successSteps = processBody; + + // 3. Let errorSteps be to queue a fetch task to run processBodyError, + // with taskDestination. + const errorSteps = processBodyError; + + // 4. Let reader be the result of getting a reader for body’s stream. + // If that threw an exception, then run errorSteps with that + // exception and return. + let reader; + + try { + reader = body.stream.getReader(); + } catch (e) { + errorSteps(e); + return + } + + // 5. Read all bytes from reader, given successSteps and errorSteps. + try { + const result = await readAllBytes(reader); + successSteps(result); + } catch (e) { + errorSteps(e); + } + } + + /** @type {ReadableStream} */ + let ReadableStream = globalThis.ReadableStream; + + function isReadableStreamLike (stream) { + if (!ReadableStream) { + ReadableStream = require$$14.ReadableStream; + } + + return stream instanceof ReadableStream || ( + stream[Symbol.toStringTag] === 'ReadableStream' && + typeof stream.tee === 'function' + ) + } + + const MAXIMUM_ARGUMENT_LENGTH = 65535; + + /** + * @see https://infra.spec.whatwg.org/#isomorphic-decode + * @param {number[]|Uint8Array} input + */ + function isomorphicDecode (input) { + // 1. To isomorphic decode a byte sequence input, return a string whose code point + // length is equal to input’s length and whose code points have the same values + // as the values of input’s bytes, in the same order. + + if (input.length < MAXIMUM_ARGUMENT_LENGTH) { + return String.fromCharCode(...input) + } + + return input.reduce((previous, current) => previous + String.fromCharCode(current), '') + } + + /** + * @param {ReadableStreamController} controller + */ + function readableStreamClose (controller) { + try { + controller.close(); + } catch (err) { + // TODO: add comment explaining why this error occurs. + if (!err.message.includes('Controller is already closed')) { + throw err + } + } + } + + /** + * @see https://infra.spec.whatwg.org/#isomorphic-encode + * @param {string} input + */ + function isomorphicEncode (input) { + // 1. Assert: input contains no code points greater than U+00FF. + for (let i = 0; i < input.length; i++) { + assert(input.charCodeAt(i) <= 0xFF); + } + + // 2. Return a byte sequence whose length is equal to input’s code + // point length and whose bytes have the same values as the + // values of input’s code points, in the same order + return input + } + + /** + * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes + * @see https://streams.spec.whatwg.org/#read-loop + * @param {ReadableStreamDefaultReader} reader + */ + async function readAllBytes (reader) { + const bytes = []; + let byteLength = 0; + + while (true) { + const { done, value: chunk } = await reader.read(); + + if (done) { + // 1. Call successSteps with bytes. + return Buffer.concat(bytes, byteLength) + } + + // 1. If chunk is not a Uint8Array object, call failureSteps + // with a TypeError and abort these steps. + if (!isUint8Array(chunk)) { + throw new TypeError('Received non-Uint8Array chunk') + } + + // 2. Append the bytes represented by chunk to bytes. + bytes.push(chunk); + byteLength += chunk.length; + + // 3. Read-loop given reader, bytes, successSteps, and failureSteps. + } + } + + /** + * @see https://fetch.spec.whatwg.org/#is-local + * @param {URL} url + */ + function urlIsLocal (url) { + assert('protocol' in url); // ensure it's a url object + + const protocol = url.protocol; + + return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' + } + + /** + * @param {string|URL} url + */ + function urlHasHttpsScheme (url) { + if (typeof url === 'string') { + return url.startsWith('https:') + } + + return url.protocol === 'https:' + } + + /** + * @see https://fetch.spec.whatwg.org/#http-scheme + * @param {URL} url + */ + function urlIsHttpHttpsScheme (url) { + assert('protocol' in url); // ensure it's a url object + + const protocol = url.protocol; + + return protocol === 'http:' || protocol === 'https:' + } + + /** + * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0. + */ + const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key)); + + util$k = { + isAborted, + isCancelled, + createDeferredPromise, + ReadableStreamFrom, + toUSVString, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + coarsenedSharedCurrentTime, + determineRequestsReferrer, + makePolicyContainer, + clonePolicyContainer, + appendFetchMetadata, + appendRequestOriginHeader, + TAOCheck, + corsCheck, + crossOriginResourcePolicyCheck, + createOpaqueTimingInfo, + setRequestReferrerPolicyOnRedirect, + isValidHTTPToken, + requestBadPort, + requestCurrentURL, + responseURL, + responseLocationURL, + isBlobLike, + isURLPotentiallyTrustworthy, + isValidReasonPhrase, + sameOrigin, + normalizeMethod, + serializeJavascriptValueToJSONString, + makeIterator, + isValidHeaderName, + isValidHeaderValue, + hasOwn, + isErrorLike, + fullyReadBody, + bytesMatch, + isReadableStreamLike, + readableStreamClose, + isomorphicEncode, + isomorphicDecode, + urlIsLocal, + urlHasHttpsScheme, + urlIsHttpHttpsScheme, + readAllBytes + }; + return util$k; + } + + var symbols$3; + var hasRequiredSymbols$3; + + function requireSymbols$3 () { + if (hasRequiredSymbols$3) return symbols$3; + hasRequiredSymbols$3 = 1; + + symbols$3 = { + kUrl: Symbol('url'), + kHeaders: Symbol('headers'), + kSignal: Symbol('signal'), + kState: Symbol('state'), + kGuard: Symbol('guard'), + kRealm: Symbol('realm') + }; + return symbols$3; + } + + var webidl_1; + var hasRequiredWebidl; + + function requireWebidl () { + if (hasRequiredWebidl) return webidl_1; + hasRequiredWebidl = 1; + + const { types } = require$$3$2; + const { hasOwn, toUSVString } = requireUtil$4(); + + /** @type {import('../../types/webidl').Webidl} */ + const webidl = {}; + webidl.converters = {}; + webidl.util = {}; + webidl.errors = {}; + + webidl.errors.exception = function (message) { + return new TypeError(`${message.header}: ${message.message}`) + }; + + webidl.errors.conversionFailed = function (context) { + const plural = context.types.length === 1 ? '' : ' one of'; + const message = + `${context.argument} could not be converted to` + + `${plural}: ${context.types.join(', ')}.`; + + return webidl.errors.exception({ + header: context.prefix, + message + }) + }; + + webidl.errors.invalidArgument = function (context) { + return webidl.errors.exception({ + header: context.prefix, + message: `"${context.value}" is an invalid ${context.type}.` + }) + }; + + // https://webidl.spec.whatwg.org/#implements + webidl.brandCheck = function (V, I, opts = undefined) { + if (opts?.strict !== false && !(V instanceof I)) { + throw new TypeError('Illegal invocation') + } else { + return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag] + } + }; + + webidl.argumentLengthCheck = function ({ length }, min, ctx) { + if (length < min) { + throw webidl.errors.exception({ + message: `${min} argument${min !== 1 ? 's' : ''} required, ` + + `but${length ? ' only' : ''} ${length} found.`, + ...ctx + }) + } + }; + + webidl.illegalConstructor = function () { + throw webidl.errors.exception({ + header: 'TypeError', + message: 'Illegal constructor' + }) + }; + + // https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values + webidl.util.Type = function (V) { + switch (typeof V) { + case 'undefined': return 'Undefined' + case 'boolean': return 'Boolean' + case 'string': return 'String' + case 'symbol': return 'Symbol' + case 'number': return 'Number' + case 'bigint': return 'BigInt' + case 'function': + case 'object': { + if (V === null) { + return 'Null' + } + + return 'Object' + } + } + }; + + // https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) { + let upperBound; + let lowerBound; + + // 1. If bitLength is 64, then: + if (bitLength === 64) { + // 1. Let upperBound be 2^53 − 1. + upperBound = Math.pow(2, 53) - 1; + + // 2. If signedness is "unsigned", then let lowerBound be 0. + if (signedness === 'unsigned') { + lowerBound = 0; + } else { + // 3. Otherwise let lowerBound be −2^53 + 1. + lowerBound = Math.pow(-2, 53) + 1; + } + } else if (signedness === 'unsigned') { + // 2. Otherwise, if signedness is "unsigned", then: + + // 1. Let lowerBound be 0. + lowerBound = 0; + + // 2. Let upperBound be 2^bitLength − 1. + upperBound = Math.pow(2, bitLength) - 1; + } else { + // 3. Otherwise: + + // 1. Let lowerBound be -2^bitLength − 1. + lowerBound = Math.pow(-2, bitLength) - 1; + + // 2. Let upperBound be 2^bitLength − 1 − 1. + upperBound = Math.pow(2, bitLength - 1) - 1; + } + + // 4. Let x be ? ToNumber(V). + let x = Number(V); + + // 5. If x is −0, then set x to +0. + if (x === 0) { + x = 0; + } + + // 6. If the conversion is to an IDL type associated + // with the [EnforceRange] extended attribute, then: + if (opts.enforceRange === true) { + // 1. If x is NaN, +∞, or −∞, then throw a TypeError. + if ( + Number.isNaN(x) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Could not convert ${V} to an integer.` + }) + } + + // 2. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x); + + // 3. If x < lowerBound or x > upperBound, then + // throw a TypeError. + if (x < lowerBound || x > upperBound) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` + }) + } + + // 4. Return x. + return x + } + + // 7. If x is not NaN and the conversion is to an IDL + // type associated with the [Clamp] extended + // attribute, then: + if (!Number.isNaN(x) && opts.clamp === true) { + // 1. Set x to min(max(x, lowerBound), upperBound). + x = Math.min(Math.max(x, lowerBound), upperBound); + + // 2. Round x to the nearest integer, choosing the + // even integer if it lies halfway between two, + // and choosing +0 rather than −0. + if (Math.floor(x) % 2 === 0) { + x = Math.floor(x); + } else { + x = Math.ceil(x); + } + + // 3. Return x. + return x + } + + // 8. If x is NaN, +0, +∞, or −∞, then return +0. + if ( + Number.isNaN(x) || + (x === 0 && Object.is(0, x)) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + return 0 + } + + // 9. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x); + + // 10. Set x to x modulo 2^bitLength. + x = x % Math.pow(2, bitLength); + + // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, + // then return x − 2^bitLength. + if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { + return x - Math.pow(2, bitLength) + } + + // 12. Otherwise, return x. + return x + }; + + // https://webidl.spec.whatwg.org/#abstract-opdef-integerpart + webidl.util.IntegerPart = function (n) { + // 1. Let r be floor(abs(n)). + const r = Math.floor(Math.abs(n)); + + // 2. If n < 0, then return -1 × r. + if (n < 0) { + return -1 * r + } + + // 3. Otherwise, return r. + return r + }; + + // https://webidl.spec.whatwg.org/#es-sequence + webidl.sequenceConverter = function (converter) { + return (V) => { + // 1. If Type(V) is not Object, throw a TypeError. + if (webidl.util.Type(V) !== 'Object') { + throw webidl.errors.exception({ + header: 'Sequence', + message: `Value of type ${webidl.util.Type(V)} is not an Object.` + }) + } + + // 2. Let method be ? GetMethod(V, @@iterator). + /** @type {Generator} */ + const method = V?.[Symbol.iterator]?.(); + const seq = []; + + // 3. If method is undefined, throw a TypeError. + if ( + method === undefined || + typeof method.next !== 'function' + ) { + throw webidl.errors.exception({ + header: 'Sequence', + message: 'Object is not an iterator.' + }) + } + + // https://webidl.spec.whatwg.org/#create-sequence-from-iterable + while (true) { + const { done, value } = method.next(); + + if (done) { + break + } + + seq.push(converter(value)); + } + + return seq + } + }; + + // https://webidl.spec.whatwg.org/#es-to-record + webidl.recordConverter = function (keyConverter, valueConverter) { + return (O) => { + // 1. If Type(O) is not Object, throw a TypeError. + if (webidl.util.Type(O) !== 'Object') { + throw webidl.errors.exception({ + header: 'Record', + message: `Value of type ${webidl.util.Type(O)} is not an Object.` + }) + } + + // 2. Let result be a new empty instance of record. + const result = {}; + + if (!types.isProxy(O)) { + // Object.keys only returns enumerable properties + const keys = Object.keys(O); + + for (const key of keys) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key); + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key]); + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue; + } + + // 5. Return result. + return result + } + + // 3. Let keys be ? O.[[OwnPropertyKeys]](). + const keys = Reflect.ownKeys(O); + + // 4. For each key of keys. + for (const key of keys) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const desc = Reflect.getOwnPropertyDescriptor(O, key); + + // 2. If desc is not undefined and desc.[[Enumerable]] is true: + if (desc?.enumerable) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key); + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key]); + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue; + } + } + + // 5. Return result. + return result + } + }; + + webidl.interfaceConverter = function (i) { + return (V, opts = {}) => { + if (opts.strict !== false && !(V instanceof i)) { + throw webidl.errors.exception({ + header: i.name, + message: `Expected ${V} to be an instance of ${i.name}.` + }) + } + + return V + } + }; + + webidl.dictionaryConverter = function (converters) { + return (dictionary) => { + const type = webidl.util.Type(dictionary); + const dict = {}; + + if (type === 'Null' || type === 'Undefined') { + return dict + } else if (type !== 'Object') { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` + }) + } + + for (const options of converters) { + const { key, defaultValue, required, converter } = options; + + if (required === true) { + if (!hasOwn(dictionary, key)) { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `Missing required key "${key}".` + }) + } + } + + let value = dictionary[key]; + const hasDefault = hasOwn(options, 'defaultValue'); + + // Only use defaultValue if value is undefined and + // a defaultValue options was provided. + if (hasDefault && value !== null) { + value = value ?? defaultValue; + } + + // A key can be optional and have no default value. + // When this happens, do not perform a conversion, + // and do not assign the key a value. + if (required || hasDefault || value !== undefined) { + value = converter(value); + + if ( + options.allowedValues && + !options.allowedValues.includes(value) + ) { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` + }) + } + + dict[key] = value; + } + } + + return dict + } + }; + + webidl.nullableConverter = function (converter) { + return (V) => { + if (V === null) { + return V + } + + return converter(V) + } + }; + + // https://webidl.spec.whatwg.org/#es-DOMString + webidl.converters.DOMString = function (V, opts = {}) { + // 1. If V is null and the conversion is to an IDL type + // associated with the [LegacyNullToEmptyString] + // extended attribute, then return the DOMString value + // that represents the empty string. + if (V === null && opts.legacyNullToEmptyString) { + return '' + } + + // 2. Let x be ? ToString(V). + if (typeof V === 'symbol') { + throw new TypeError('Could not convert argument of type symbol to string.') + } + + // 3. Return the IDL DOMString value that represents the + // same sequence of code units as the one the + // ECMAScript String value x represents. + return String(V) + }; + + // https://webidl.spec.whatwg.org/#es-ByteString + webidl.converters.ByteString = function (V) { + // 1. Let x be ? ToString(V). + // Note: DOMString converter perform ? ToString(V) + const x = webidl.converters.DOMString(V); + + // 2. If the value of any element of x is greater than + // 255, then throw a TypeError. + for (let index = 0; index < x.length; index++) { + const charCode = x.charCodeAt(index); + + if (charCode > 255) { + throw new TypeError( + 'Cannot convert argument to a ByteString because the character at ' + + `index ${index} has a value of ${charCode} which is greater than 255.` + ) + } + } + + // 3. Return an IDL ByteString value whose length is the + // length of x, and where the value of each element is + // the value of the corresponding element of x. + return x + }; + + // https://webidl.spec.whatwg.org/#es-USVString + webidl.converters.USVString = toUSVString; + + // https://webidl.spec.whatwg.org/#es-boolean + webidl.converters.boolean = function (V) { + // 1. Let x be the result of computing ToBoolean(V). + const x = Boolean(V); + + // 2. Return the IDL boolean value that is the one that represents + // the same truth value as the ECMAScript Boolean value x. + return x + }; + + // https://webidl.spec.whatwg.org/#es-any + webidl.converters.any = function (V) { + return V + }; + + // https://webidl.spec.whatwg.org/#es-long-long + webidl.converters['long long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 64, "signed"). + const x = webidl.util.ConvertToInt(V, 64, 'signed'); + + // 2. Return the IDL long long value that represents + // the same numeric value as x. + return x + }; + + // https://webidl.spec.whatwg.org/#es-unsigned-long-long + webidl.converters['unsigned long long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). + const x = webidl.util.ConvertToInt(V, 64, 'unsigned'); + + // 2. Return the IDL unsigned long long value that + // represents the same numeric value as x. + return x + }; + + // https://webidl.spec.whatwg.org/#es-unsigned-long + webidl.converters['unsigned long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). + const x = webidl.util.ConvertToInt(V, 32, 'unsigned'); + + // 2. Return the IDL unsigned long value that + // represents the same numeric value as x. + return x + }; + + // https://webidl.spec.whatwg.org/#es-unsigned-short + webidl.converters['unsigned short'] = function (V, opts) { + // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). + const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts); + + // 2. Return the IDL unsigned short value that represents + // the same numeric value as x. + return x + }; + + // https://webidl.spec.whatwg.org/#idl-ArrayBuffer + webidl.converters.ArrayBuffer = function (V, opts = {}) { + // 1. If Type(V) is not Object, or V does not have an + // [[ArrayBufferData]] internal slot, then throw a + // TypeError. + // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances + // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances + if ( + webidl.util.Type(V) !== 'Object' || + !types.isAnyArrayBuffer(V) + ) { + throw webidl.errors.conversionFailed({ + prefix: `${V}`, + argument: `${V}`, + types: ['ArrayBuffer'] + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V) is true, then throw a + // TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V) is true, then throw a + // TypeError. + // Note: resizable ArrayBuffers are currently a proposal. + + // 4. Return the IDL ArrayBuffer value that is a + // reference to the same object as V. + return V + }; + + webidl.converters.TypedArray = function (V, T, opts = {}) { + // 1. Let T be the IDL type V is being converted to. + + // 2. If Type(V) is not Object, or V does not have a + // [[TypedArrayName]] internal slot with a value + // equal to T’s name, then throw a TypeError. + if ( + webidl.util.Type(V) !== 'Object' || + !types.isTypedArray(V) || + V.constructor.name !== T.name + ) { + throw webidl.errors.conversionFailed({ + prefix: `${T.name}`, + argument: `${V}`, + types: [T.name] + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 4. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + // Note: resizable array buffers are currently a proposal + + // 5. Return the IDL value of type T that is a reference + // to the same object as V. + return V + }; + + webidl.converters.DataView = function (V, opts = {}) { + // 1. If Type(V) is not Object, or V does not have a + // [[DataView]] internal slot, then throw a TypeError. + if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) { + throw webidl.errors.exception({ + header: 'DataView', + message: 'Object is not a DataView.' + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, + // then throw a TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + // Note: resizable ArrayBuffers are currently a proposal + + // 4. Return the IDL DataView value that is a reference + // to the same object as V. + return V + }; + + // https://webidl.spec.whatwg.org/#BufferSource + webidl.converters.BufferSource = function (V, opts = {}) { + if (types.isAnyArrayBuffer(V)) { + return webidl.converters.ArrayBuffer(V, opts) + } + + if (types.isTypedArray(V)) { + return webidl.converters.TypedArray(V, V.constructor) + } + + if (types.isDataView(V)) { + return webidl.converters.DataView(V, opts) + } + + throw new TypeError(`Could not convert ${V} to a BufferSource.`) + }; + + webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.ByteString + ); + + webidl.converters['sequence>'] = webidl.sequenceConverter( + webidl.converters['sequence'] + ); + + webidl.converters['record'] = webidl.recordConverter( + webidl.converters.ByteString, + webidl.converters.ByteString + ); + + webidl_1 = { + webidl + }; + return webidl_1; + } + + var dataURL; + var hasRequiredDataURL; + + function requireDataURL () { + if (hasRequiredDataURL) return dataURL; + hasRequiredDataURL = 1; + const assert = require$$3$1; + const { atob } = require$$7; + const { isomorphicDecode } = requireUtil$4(); + + const encoder = new TextEncoder(); + + /** + * @see https://mimesniff.spec.whatwg.org/#http-token-code-point + */ + const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/; + const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/; // eslint-disable-line + /** + * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point + */ + const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/; // eslint-disable-line + + // https://fetch.spec.whatwg.org/#data-url-processor + /** @param {URL} dataURL */ + function dataURLProcessor (dataURL) { + // 1. Assert: dataURL’s scheme is "data". + assert(dataURL.protocol === 'data:'); + + // 2. Let input be the result of running the URL + // serializer on dataURL with exclude fragment + // set to true. + let input = URLSerializer(dataURL, true); + + // 3. Remove the leading "data:" string from input. + input = input.slice(5); + + // 4. Let position point at the start of input. + const position = { position: 0 }; + + // 5. Let mimeType be the result of collecting a + // sequence of code points that are not equal + // to U+002C (,), given position. + let mimeType = collectASequenceOfCodePointsFast( + ',', + input, + position + ); + + // 6. Strip leading and trailing ASCII whitespace + // from mimeType. + // Undici implementation note: we need to store the + // length because if the mimetype has spaces removed, + // the wrong amount will be sliced from the input in + // step #9 + const mimeTypeLength = mimeType.length; + mimeType = removeASCIIWhitespace(mimeType, true, true); + + // 7. If position is past the end of input, then + // return failure + if (position.position >= input.length) { + return 'failure' + } + + // 8. Advance position by 1. + position.position++; + + // 9. Let encodedBody be the remainder of input. + const encodedBody = input.slice(mimeTypeLength + 1); + + // 10. Let body be the percent-decoding of encodedBody. + let body = stringPercentDecode(encodedBody); + + // 11. If mimeType ends with U+003B (;), followed by + // zero or more U+0020 SPACE, followed by an ASCII + // case-insensitive match for "base64", then: + if (/;(\u0020){0,}base64$/i.test(mimeType)) { + // 1. Let stringBody be the isomorphic decode of body. + const stringBody = isomorphicDecode(body); + + // 2. Set body to the forgiving-base64 decode of + // stringBody. + body = forgivingBase64(stringBody); + + // 3. If body is failure, then return failure. + if (body === 'failure') { + return 'failure' + } + + // 4. Remove the last 6 code points from mimeType. + mimeType = mimeType.slice(0, -6); + + // 5. Remove trailing U+0020 SPACE code points from mimeType, + // if any. + mimeType = mimeType.replace(/(\u0020)+$/, ''); + + // 6. Remove the last U+003B (;) code point from mimeType. + mimeType = mimeType.slice(0, -1); + } + + // 12. If mimeType starts with U+003B (;), then prepend + // "text/plain" to mimeType. + if (mimeType.startsWith(';')) { + mimeType = 'text/plain' + mimeType; + } + + // 13. Let mimeTypeRecord be the result of parsing + // mimeType. + let mimeTypeRecord = parseMIMEType(mimeType); + + // 14. If mimeTypeRecord is failure, then set + // mimeTypeRecord to text/plain;charset=US-ASCII. + if (mimeTypeRecord === 'failure') { + mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII'); + } + + // 15. Return a new data: URL struct whose MIME + // type is mimeTypeRecord and body is body. + // https://fetch.spec.whatwg.org/#data-url-struct + return { mimeType: mimeTypeRecord, body } + } + + // https://url.spec.whatwg.org/#concept-url-serializer + /** + * @param {URL} url + * @param {boolean} excludeFragment + */ + function URLSerializer (url, excludeFragment = false) { + const href = url.href; + + if (!excludeFragment) { + return href + } + + const hash = href.lastIndexOf('#'); + if (hash === -1) { + return href + } + return href.slice(0, hash) + } + + // https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points + /** + * @param {(char: string) => boolean} condition + * @param {string} input + * @param {{ position: number }} position + */ + function collectASequenceOfCodePoints (condition, input, position) { + // 1. Let result be the empty string. + let result = ''; + + // 2. While position doesn’t point past the end of input and the + // code point at position within input meets the condition condition: + while (position.position < input.length && condition(input[position.position])) { + // 1. Append that code point to the end of result. + result += input[position.position]; + + // 2. Advance position by 1. + position.position++; + } + + // 3. Return result. + return result + } + + /** + * A faster collectASequenceOfCodePoints that only works when comparing a single character. + * @param {string} char + * @param {string} input + * @param {{ position: number }} position + */ + function collectASequenceOfCodePointsFast (char, input, position) { + const idx = input.indexOf(char, position.position); + const start = position.position; + + if (idx === -1) { + position.position = input.length; + return input.slice(start) + } + + position.position = idx; + return input.slice(start, position.position) + } + + // https://url.spec.whatwg.org/#string-percent-decode + /** @param {string} input */ + function stringPercentDecode (input) { + // 1. Let bytes be the UTF-8 encoding of input. + const bytes = encoder.encode(input); + + // 2. Return the percent-decoding of bytes. + return percentDecode(bytes) + } + + // https://url.spec.whatwg.org/#percent-decode + /** @param {Uint8Array} input */ + function percentDecode (input) { + // 1. Let output be an empty byte sequence. + /** @type {number[]} */ + const output = []; + + // 2. For each byte byte in input: + for (let i = 0; i < input.length; i++) { + const byte = input[i]; + + // 1. If byte is not 0x25 (%), then append byte to output. + if (byte !== 0x25) { + output.push(byte); + + // 2. Otherwise, if byte is 0x25 (%) and the next two bytes + // after byte in input are not in the ranges + // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), + // and 0x61 (a) to 0x66 (f), all inclusive, append byte + // to output. + } else if ( + byte === 0x25 && + !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2])) + ) { + output.push(0x25); + + // 3. Otherwise: + } else { + // 1. Let bytePoint be the two bytes after byte in input, + // decoded, and then interpreted as hexadecimal number. + const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2]); + const bytePoint = Number.parseInt(nextTwoBytes, 16); + + // 2. Append a byte whose value is bytePoint to output. + output.push(bytePoint); + + // 3. Skip the next two bytes in input. + i += 2; + } + } + + // 3. Return output. + return Uint8Array.from(output) + } + + // https://mimesniff.spec.whatwg.org/#parse-a-mime-type + /** @param {string} input */ + function parseMIMEType (input) { + // 1. Remove any leading and trailing HTTP whitespace + // from input. + input = removeHTTPWhitespace(input, true, true); + + // 2. Let position be a position variable for input, + // initially pointing at the start of input. + const position = { position: 0 }; + + // 3. Let type be the result of collecting a sequence + // of code points that are not U+002F (/) from + // input, given position. + const type = collectASequenceOfCodePointsFast( + '/', + input, + position + ); + + // 4. If type is the empty string or does not solely + // contain HTTP token code points, then return failure. + // https://mimesniff.spec.whatwg.org/#http-token-code-point + if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { + return 'failure' + } + + // 5. If position is past the end of input, then return + // failure + if (position.position > input.length) { + return 'failure' + } + + // 6. Advance position by 1. (This skips past U+002F (/).) + position.position++; + + // 7. Let subtype be the result of collecting a sequence of + // code points that are not U+003B (;) from input, given + // position. + let subtype = collectASequenceOfCodePointsFast( + ';', + input, + position + ); + + // 8. Remove any trailing HTTP whitespace from subtype. + subtype = removeHTTPWhitespace(subtype, false, true); + + // 9. If subtype is the empty string or does not solely + // contain HTTP token code points, then return failure. + if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { + return 'failure' + } + + const typeLowercase = type.toLowerCase(); + const subtypeLowercase = subtype.toLowerCase(); + + // 10. Let mimeType be a new MIME type record whose type + // is type, in ASCII lowercase, and subtype is subtype, + // in ASCII lowercase. + // https://mimesniff.spec.whatwg.org/#mime-type + const mimeType = { + type: typeLowercase, + subtype: subtypeLowercase, + /** @type {Map} */ + parameters: new Map(), + // https://mimesniff.spec.whatwg.org/#mime-type-essence + essence: `${typeLowercase}/${subtypeLowercase}` + }; + + // 11. While position is not past the end of input: + while (position.position < input.length) { + // 1. Advance position by 1. (This skips past U+003B (;).) + position.position++; + + // 2. Collect a sequence of code points that are HTTP + // whitespace from input given position. + collectASequenceOfCodePoints( + // https://fetch.spec.whatwg.org/#http-whitespace + char => HTTP_WHITESPACE_REGEX.test(char), + input, + position + ); + + // 3. Let parameterName be the result of collecting a + // sequence of code points that are not U+003B (;) + // or U+003D (=) from input, given position. + let parameterName = collectASequenceOfCodePoints( + (char) => char !== ';' && char !== '=', + input, + position + ); + + // 4. Set parameterName to parameterName, in ASCII + // lowercase. + parameterName = parameterName.toLowerCase(); + + // 5. If position is not past the end of input, then: + if (position.position < input.length) { + // 1. If the code point at position within input is + // U+003B (;), then continue. + if (input[position.position] === ';') { + continue + } + + // 2. Advance position by 1. (This skips past U+003D (=).) + position.position++; + } + + // 6. If position is past the end of input, then break. + if (position.position > input.length) { + break + } + + // 7. Let parameterValue be null. + let parameterValue = null; + + // 8. If the code point at position within input is + // U+0022 ("), then: + if (input[position.position] === '"') { + // 1. Set parameterValue to the result of collecting + // an HTTP quoted string from input, given position + // and the extract-value flag. + parameterValue = collectAnHTTPQuotedString(input, position, true); + + // 2. Collect a sequence of code points that are not + // U+003B (;) from input, given position. + collectASequenceOfCodePointsFast( + ';', + input, + position + ); + + // 9. Otherwise: + } else { + // 1. Set parameterValue to the result of collecting + // a sequence of code points that are not U+003B (;) + // from input, given position. + parameterValue = collectASequenceOfCodePointsFast( + ';', + input, + position + ); + + // 2. Remove any trailing HTTP whitespace from parameterValue. + parameterValue = removeHTTPWhitespace(parameterValue, false, true); + + // 3. If parameterValue is the empty string, then continue. + if (parameterValue.length === 0) { + continue + } + } + + // 10. If all of the following are true + // - parameterName is not the empty string + // - parameterName solely contains HTTP token code points + // - parameterValue solely contains HTTP quoted-string token code points + // - mimeType’s parameters[parameterName] does not exist + // then set mimeType’s parameters[parameterName] to parameterValue. + if ( + parameterName.length !== 0 && + HTTP_TOKEN_CODEPOINTS.test(parameterName) && + (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && + !mimeType.parameters.has(parameterName) + ) { + mimeType.parameters.set(parameterName, parameterValue); + } + } + + // 12. Return mimeType. + return mimeType + } + + // https://infra.spec.whatwg.org/#forgiving-base64-decode + /** @param {string} data */ + function forgivingBase64 (data) { + // 1. Remove all ASCII whitespace from data. + data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, ''); // eslint-disable-line + + // 2. If data’s code point length divides by 4 leaving + // no remainder, then: + if (data.length % 4 === 0) { + // 1. If data ends with one or two U+003D (=) code points, + // then remove them from data. + data = data.replace(/=?=$/, ''); + } + + // 3. If data’s code point length divides by 4 leaving + // a remainder of 1, then return failure. + if (data.length % 4 === 1) { + return 'failure' + } + + // 4. If data contains a code point that is not one of + // U+002B (+) + // U+002F (/) + // ASCII alphanumeric + // then return failure. + if (/[^+/0-9A-Za-z]/.test(data)) { + return 'failure' + } + + const binary = atob(data); + const bytes = new Uint8Array(binary.length); + + for (let byte = 0; byte < binary.length; byte++) { + bytes[byte] = binary.charCodeAt(byte); + } + + return bytes + } + + // https://fetch.spec.whatwg.org/#collect-an-http-quoted-string + // tests: https://fetch.spec.whatwg.org/#example-http-quoted-string + /** + * @param {string} input + * @param {{ position: number }} position + * @param {boolean?} extractValue + */ + function collectAnHTTPQuotedString (input, position, extractValue) { + // 1. Let positionStart be position. + const positionStart = position.position; + + // 2. Let value be the empty string. + let value = ''; + + // 3. Assert: the code point at position within input + // is U+0022 ("). + assert(input[position.position] === '"'); + + // 4. Advance position by 1. + position.position++; + + // 5. While true: + while (true) { + // 1. Append the result of collecting a sequence of code points + // that are not U+0022 (") or U+005C (\) from input, given + // position, to value. + value += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== '\\', + input, + position + ); + + // 2. If position is past the end of input, then break. + if (position.position >= input.length) { + break + } + + // 3. Let quoteOrBackslash be the code point at position within + // input. + const quoteOrBackslash = input[position.position]; + + // 4. Advance position by 1. + position.position++; + + // 5. If quoteOrBackslash is U+005C (\), then: + if (quoteOrBackslash === '\\') { + // 1. If position is past the end of input, then append + // U+005C (\) to value and break. + if (position.position >= input.length) { + value += '\\'; + break + } + + // 2. Append the code point at position within input to value. + value += input[position.position]; + + // 3. Advance position by 1. + position.position++; + + // 6. Otherwise: + } else { + // 1. Assert: quoteOrBackslash is U+0022 ("). + assert(quoteOrBackslash === '"'); + + // 2. Break. + break + } + } + + // 6. If the extract-value flag is set, then return value. + if (extractValue) { + return value + } + + // 7. Return the code points from positionStart to position, + // inclusive, within input. + return input.slice(positionStart, position.position) + } + + /** + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ + function serializeAMimeType (mimeType) { + assert(mimeType !== 'failure'); + const { parameters, essence } = mimeType; + + // 1. Let serialization be the concatenation of mimeType’s + // type, U+002F (/), and mimeType’s subtype. + let serialization = essence; + + // 2. For each name → value of mimeType’s parameters: + for (let [name, value] of parameters.entries()) { + // 1. Append U+003B (;) to serialization. + serialization += ';'; + + // 2. Append name to serialization. + serialization += name; + + // 3. Append U+003D (=) to serialization. + serialization += '='; + + // 4. If value does not solely contain HTTP token code + // points or value is the empty string, then: + if (!HTTP_TOKEN_CODEPOINTS.test(value)) { + // 1. Precede each occurence of U+0022 (") or + // U+005C (\) in value with U+005C (\). + value = value.replace(/(\\|")/g, '\\$1'); + + // 2. Prepend U+0022 (") to value. + value = '"' + value; + + // 3. Append U+0022 (") to value. + value += '"'; + } + + // 5. Append value to serialization. + serialization += value; + } + + // 3. Return serialization. + return serialization + } + + /** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} char + */ + function isHTTPWhiteSpace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === ' ' + } + + /** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} str + */ + function removeHTTPWhitespace (str, leading = true, trailing = true) { + let lead = 0; + let trail = str.length - 1; + + if (leading) { + for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++); + } + + if (trailing) { + for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--); + } + + return str.slice(lead, trail + 1) + } + + /** + * @see https://infra.spec.whatwg.org/#ascii-whitespace + * @param {string} char + */ + function isASCIIWhitespace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' ' + } + + /** + * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace + */ + function removeASCIIWhitespace (str, leading = true, trailing = true) { + let lead = 0; + let trail = str.length - 1; + + if (leading) { + for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++); + } + + if (trailing) { + for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--); + } + + return str.slice(lead, trail + 1) + } + + dataURL = { + dataURLProcessor, + URLSerializer, + collectASequenceOfCodePoints, + collectASequenceOfCodePointsFast, + stringPercentDecode, + parseMIMEType, + collectAnHTTPQuotedString, + serializeAMimeType + }; + return dataURL; + } + + var file; + var hasRequiredFile; + + function requireFile () { + if (hasRequiredFile) return file; + hasRequiredFile = 1; + + const { Blob, File: NativeFile } = require$$7; + const { types } = require$$3$2; + const { kState } = requireSymbols$3(); + const { isBlobLike } = requireUtil$4(); + const { webidl } = requireWebidl(); + const { parseMIMEType, serializeAMimeType } = requireDataURL(); + const { kEnumerableProperty } = util$l; + + class File extends Blob { + constructor (fileBits, fileName, options = {}) { + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: + webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' }); + + fileBits = webidl.converters['sequence'](fileBits); + fileName = webidl.converters.USVString(fileName); + options = webidl.converters.FilePropertyBag(options); + + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + // Note: Blob handles this for us + + // 2. Let n be the fileName argument to the constructor. + const n = fileName; + + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: + + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // 2. Convert every character in t to ASCII lowercase. + let t = options.type; + let d; + + // eslint-disable-next-line no-labels + substep: { + if (t) { + t = parseMIMEType(t); + + if (t === 'failure') { + t = ''; + // eslint-disable-next-line no-labels + break substep + } + + t = serializeAMimeType(t).toLowerCase(); + } + + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + d = options.lastModified; + } + + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. + + super(processBlobParts(fileBits, options), { type: t }); + this[kState] = { + name: n, + lastModified: d, + type: t + }; + } + + get name () { + webidl.brandCheck(this, File); + + return this[kState].name + } + + get lastModified () { + webidl.brandCheck(this, File); + + return this[kState].lastModified + } + + get type () { + webidl.brandCheck(this, File); + + return this[kState].type + } + } + + class FileLike { + constructor (blobLike, fileName, options = {}) { + // TODO: argument idl type check + + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: + + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + + // 2. Let n be the fileName argument to the constructor. + const n = fileName; + + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: + + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // TODO + const t = options.type; + + // 2. Convert every character in t to ASCII lowercase. + // TODO + + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + const d = options.lastModified ?? Date.now(); + + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. + + this[kState] = { + blobLike, + name: n, + type: t, + lastModified: d + }; + } + + stream (...args) { + webidl.brandCheck(this, FileLike); + + return this[kState].blobLike.stream(...args) + } + + arrayBuffer (...args) { + webidl.brandCheck(this, FileLike); + + return this[kState].blobLike.arrayBuffer(...args) + } + + slice (...args) { + webidl.brandCheck(this, FileLike); + + return this[kState].blobLike.slice(...args) + } + + text (...args) { + webidl.brandCheck(this, FileLike); + + return this[kState].blobLike.text(...args) + } + + get size () { + webidl.brandCheck(this, FileLike); + + return this[kState].blobLike.size + } + + get type () { + webidl.brandCheck(this, FileLike); + + return this[kState].blobLike.type + } + + get name () { + webidl.brandCheck(this, FileLike); + + return this[kState].name + } + + get lastModified () { + webidl.brandCheck(this, FileLike); + + return this[kState].lastModified + } + + get [Symbol.toStringTag] () { + return 'File' + } + } + + Object.defineProperties(File.prototype, { + [Symbol.toStringTag]: { + value: 'File', + configurable: true + }, + name: kEnumerableProperty, + lastModified: kEnumerableProperty + }); + + webidl.converters.Blob = webidl.interfaceConverter(Blob); + + webidl.converters.BlobPart = function (V, opts) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if ( + ArrayBuffer.isView(V) || + types.isAnyArrayBuffer(V) + ) { + return webidl.converters.BufferSource(V, opts) + } + } + + return webidl.converters.USVString(V, opts) + }; + + webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.BlobPart + ); + + // https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag + webidl.converters.FilePropertyBag = webidl.dictionaryConverter([ + { + key: 'lastModified', + converter: webidl.converters['long long'], + get defaultValue () { + return Date.now() + } + }, + { + key: 'type', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'endings', + converter: (value) => { + value = webidl.converters.DOMString(value); + value = value.toLowerCase(); + + if (value !== 'native') { + value = 'transparent'; + } + + return value + }, + defaultValue: 'transparent' + } + ]); + + /** + * @see https://www.w3.org/TR/FileAPI/#process-blob-parts + * @param {(NodeJS.TypedArray|Blob|string)[]} parts + * @param {{ type: string, endings: string }} options + */ + function processBlobParts (parts, options) { + // 1. Let bytes be an empty sequence of bytes. + /** @type {NodeJS.TypedArray[]} */ + const bytes = []; + + // 2. For each element in parts: + for (const element of parts) { + // 1. If element is a USVString, run the following substeps: + if (typeof element === 'string') { + // 1. Let s be element. + let s = element; + + // 2. If the endings member of options is "native", set s + // to the result of converting line endings to native + // of element. + if (options.endings === 'native') { + s = convertLineEndingsNative(s); + } + + // 3. Append the result of UTF-8 encoding s to bytes. + bytes.push(new TextEncoder().encode(s)); + } else if ( + types.isAnyArrayBuffer(element) || + types.isTypedArray(element) + ) { + // 2. If element is a BufferSource, get a copy of the + // bytes held by the buffer source, and append those + // bytes to bytes. + if (!element.buffer) { // ArrayBuffer + bytes.push(new Uint8Array(element)); + } else { + bytes.push( + new Uint8Array(element.buffer, element.byteOffset, element.byteLength) + ); + } + } else if (isBlobLike(element)) { + // 3. If element is a Blob, append the bytes it represents + // to bytes. + bytes.push(element); + } + } + + // 3. Return bytes. + return bytes + } + + /** + * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native + * @param {string} s + */ + function convertLineEndingsNative (s) { + // 1. Let native line ending be be the code point U+000A LF. + let nativeLineEnding = '\n'; + + // 2. If the underlying platform’s conventions are to + // represent newlines as a carriage return and line feed + // sequence, set native line ending to the code point + // U+000D CR followed by the code point U+000A LF. + if (browser$1$1.platform === 'win32') { + nativeLineEnding = '\r\n'; + } + + return s.replace(/\r?\n/g, nativeLineEnding) + } + + // If this function is moved to ./util.js, some tools (such as + // rollup) will warn about circular dependencies. See: + // https://github.com/nodejs/undici/issues/1629 + function isFileLike (object) { + return ( + (NativeFile && object instanceof NativeFile) || + object instanceof File || ( + object && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + object[Symbol.toStringTag] === 'File' + ) + ) + } + + file = { File, FileLike, isFileLike }; + return file; + } + + var formdata; + var hasRequiredFormdata; + + function requireFormdata () { + if (hasRequiredFormdata) return formdata; + hasRequiredFormdata = 1; + + const { isBlobLike, toUSVString, makeIterator } = requireUtil$4(); + const { kState } = requireSymbols$3(); + const { File: UndiciFile, FileLike, isFileLike } = requireFile(); + const { webidl } = requireWebidl(); + const { Blob, File: NativeFile } = require$$7; + + /** @type {globalThis['File']} */ + const File = NativeFile ?? UndiciFile; + + // https://xhr.spec.whatwg.org/#formdata + class FormData { + constructor (form) { + if (form !== undefined) { + throw webidl.errors.conversionFailed({ + prefix: 'FormData constructor', + argument: 'Argument 1', + types: ['undefined'] + }) + } + + this[kState] = []; + } + + append (name, value, filename = undefined) { + webidl.brandCheck(this, FormData); + + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }); + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name); + value = isBlobLike(value) + ? webidl.converters.Blob(value, { strict: false }) + : webidl.converters.USVString(value); + filename = arguments.length === 3 + ? webidl.converters.USVString(filename) + : undefined; + + // 2. Let entry be the result of creating an entry with + // name, value, and filename if given. + const entry = makeEntry(name, value, filename); + + // 3. Append entry to this’s entry list. + this[kState].push(entry); + } + + delete (name) { + webidl.brandCheck(this, FormData); + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }); + + name = webidl.converters.USVString(name); + + // The delete(name) method steps are to remove all entries whose name + // is name from this’s entry list. + this[kState] = this[kState].filter(entry => entry.name !== name); + } + + get (name) { + webidl.brandCheck(this, FormData); + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }); + + name = webidl.converters.USVString(name); + + // 1. If there is no entry whose name is name in this’s entry list, + // then return null. + const idx = this[kState].findIndex((entry) => entry.name === name); + if (idx === -1) { + return null + } + + // 2. Return the value of the first entry whose name is name from + // this’s entry list. + return this[kState][idx].value + } + + getAll (name) { + webidl.brandCheck(this, FormData); + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }); + + name = webidl.converters.USVString(name); + + // 1. If there is no entry whose name is name in this’s entry list, + // then return the empty list. + // 2. Return the values of all entries whose name is name, in order, + // from this’s entry list. + return this[kState] + .filter((entry) => entry.name === name) + .map((entry) => entry.value) + } + + has (name) { + webidl.brandCheck(this, FormData); + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }); + + name = webidl.converters.USVString(name); + + // The has(name) method steps are to return true if there is an entry + // whose name is name in this’s entry list; otherwise false. + return this[kState].findIndex((entry) => entry.name === name) !== -1 + } + + set (name, value, filename = undefined) { + webidl.brandCheck(this, FormData); + + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' }); + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // The set(name, value) and set(name, blobValue, filename) method steps + // are: + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name); + value = isBlobLike(value) + ? webidl.converters.Blob(value, { strict: false }) + : webidl.converters.USVString(value); + filename = arguments.length === 3 + ? toUSVString(filename) + : undefined; + + // 2. Let entry be the result of creating an entry with name, value, and + // filename if given. + const entry = makeEntry(name, value, filename); + + // 3. If there are entries in this’s entry list whose name is name, then + // replace the first such entry with entry and remove the others. + const idx = this[kState].findIndex((entry) => entry.name === name); + if (idx !== -1) { + this[kState] = [ + ...this[kState].slice(0, idx), + entry, + ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name) + ]; + } else { + // 4. Otherwise, append entry to this’s entry list. + this[kState].push(entry); + } + } + + entries () { + webidl.brandCheck(this, FormData); + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key+value' + ) + } + + keys () { + webidl.brandCheck(this, FormData); + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key' + ) + } + + values () { + webidl.brandCheck(this, FormData); + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'value' + ) + } + + /** + * @param {(value: string, key: string, self: FormData) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, FormData); + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' }); + + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." + ) + } + + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]); + } + } + } + + FormData.prototype[Symbol.iterator] = FormData.prototype.entries; + + Object.defineProperties(FormData.prototype, { + [Symbol.toStringTag]: { + value: 'FormData', + configurable: true + } + }); + + /** + * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry + * @param {string} name + * @param {string|Blob} value + * @param {?string} filename + * @returns + */ + function makeEntry (name, value, filename) { + // 1. Set name to the result of converting name into a scalar value string. + // "To convert a string into a scalar value string, replace any surrogates + // with U+FFFD." + // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end + name = Buffer.from(name).toString('utf8'); + + // 2. If value is a string, then set value to the result of converting + // value into a scalar value string. + if (typeof value === 'string') { + value = Buffer.from(value).toString('utf8'); + } else { + // 3. Otherwise: + + // 1. If value is not a File object, then set value to a new File object, + // representing the same bytes, whose name attribute value is "blob" + if (!isFileLike(value)) { + value = value instanceof Blob + ? new File([value], 'blob', { type: value.type }) + : new FileLike(value, 'blob', { type: value.type }); + } + + // 2. If filename is given, then set value to a new File object, + // representing the same bytes, whose name attribute is filename. + if (filename !== undefined) { + /** @type {FilePropertyBag} */ + const options = { + type: value.type, + lastModified: value.lastModified + }; + + value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile + ? new File([value], filename, options) + : new FileLike(value, filename, options); + } + } + + // 4. Return an entry whose name is name and whose value is value. + return { name, value } + } + + formdata = { FormData }; + return formdata; + } + + var body; + var hasRequiredBody; + + function requireBody () { + if (hasRequiredBody) return body; + hasRequiredBody = 1; + + const Busboy = requireMain(); + const util = util$l; + const { + ReadableStreamFrom, + isBlobLike, + isReadableStreamLike, + readableStreamClose, + createDeferredPromise, + fullyReadBody + } = requireUtil$4(); + const { FormData } = requireFormdata(); + const { kState } = requireSymbols$3(); + const { webidl } = requireWebidl(); + const { DOMException, structuredClone } = requireConstants$3(); + const { Blob, File: NativeFile } = require$$7; + const { kBodyUsed } = symbols$4; + const assert = require$$3$1; + const { isErrored } = util$l; + const { isUint8Array, isArrayBuffer } = require$$10; + const { File: UndiciFile } = requireFile(); + const { parseMIMEType, serializeAMimeType } = requireDataURL(); + + let ReadableStream = globalThis.ReadableStream; + + /** @type {globalThis['File']} */ + const File = NativeFile ?? UndiciFile; + + // https://fetch.spec.whatwg.org/#concept-bodyinit-extract + function extractBody (object, keepalive = false) { + if (!ReadableStream) { + ReadableStream = require$$14.ReadableStream; + } + + // 1. Let stream be null. + let stream = null; + + // 2. If object is a ReadableStream object, then set stream to object. + if (object instanceof ReadableStream) { + stream = object; + } else if (isBlobLike(object)) { + // 3. Otherwise, if object is a Blob object, set stream to the + // result of running object’s get stream. + stream = object.stream(); + } else { + // 4. Otherwise, set stream to a new ReadableStream object, and set + // up stream. + stream = new ReadableStream({ + async pull (controller) { + controller.enqueue( + typeof source === 'string' ? new TextEncoder().encode(source) : source + ); + queueMicrotask(() => readableStreamClose(controller)); + }, + start () {}, + type: undefined + }); + } + + // 5. Assert: stream is a ReadableStream object. + assert(isReadableStreamLike(stream)); + + // 6. Let action be null. + let action = null; + + // 7. Let source be null. + let source = null; + + // 8. Let length be null. + let length = null; + + // 9. Let type be null. + let type = null; + + // 10. Switch on object: + if (typeof object === 'string') { + // Set source to the UTF-8 encoding of object. + // Note: setting source to a Uint8Array here breaks some mocking assumptions. + source = object; + + // Set type to `text/plain;charset=UTF-8`. + type = 'text/plain;charset=UTF-8'; + } else if (object instanceof URLSearchParams) { + // URLSearchParams + + // spec says to run application/x-www-form-urlencoded on body.list + // this is implemented in Node.js as apart of an URLSearchParams instance toString method + // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 + // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 + + // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. + source = object.toString(); + + // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. + type = 'application/x-www-form-urlencoded;charset=UTF-8'; + } else if (isArrayBuffer(object)) { + // BufferSource/ArrayBuffer + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.slice()); + } else if (ArrayBuffer.isView(object)) { + // BufferSource/ArrayBufferView + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)); + } else if (util.isFormDataLike(object)) { + const boundary = `----formdata-undici-0${`${Math.floor(Math.random() * 1e11)}`.padStart(11, '0')}`; + const prefix = `--${boundary}\r\nContent-Disposition: form-data`; + + /*! formdata-polyfill. MIT License. Jimmy Wärting */ + const escape = (str) => + str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22'); + const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n'); + + // Set action to this step: run the multipart/form-data + // encoding algorithm, with object’s entry list and UTF-8. + // - This ensures that the body is immutable and can't be changed afterwords + // - That the content-length is calculated in advance. + // - And that all parts are pre-encoded and ready to be sent. + + const enc = new TextEncoder(); + const blobParts = []; + const rn = new Uint8Array([13, 10]); // '\r\n' + length = 0; + let hasUnknownSizeValue = false; + + for (const [name, value] of object) { + if (typeof value === 'string') { + const chunk = enc.encode(prefix + + `; name="${escape(normalizeLinefeeds(name))}"` + + `\r\n\r\n${normalizeLinefeeds(value)}\r\n`); + blobParts.push(chunk); + length += chunk.byteLength; + } else { + const chunk = enc.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + + `Content-Type: ${ + value.type || 'application/octet-stream' + }\r\n\r\n`); + blobParts.push(chunk, value, rn); + if (typeof value.size === 'number') { + length += chunk.byteLength + value.size + rn.byteLength; + } else { + hasUnknownSizeValue = true; + } + } + } + + const chunk = enc.encode(`--${boundary}--`); + blobParts.push(chunk); + length += chunk.byteLength; + if (hasUnknownSizeValue) { + length = null; + } + + // Set source to object. + source = object; + + action = async function * () { + for (const part of blobParts) { + if (part.stream) { + yield * part.stream(); + } else { + yield part; + } + } + }; + + // Set type to `multipart/form-data; boundary=`, + // followed by the multipart/form-data boundary string generated + // by the multipart/form-data encoding algorithm. + type = 'multipart/form-data; boundary=' + boundary; + } else if (isBlobLike(object)) { + // Blob + + // Set source to object. + source = object; + + // Set length to object’s size. + length = object.size; + + // If object’s type attribute is not the empty byte sequence, set + // type to its value. + if (object.type) { + type = object.type; + } + } else if (typeof object[Symbol.asyncIterator] === 'function') { + // If keepalive is true, then throw a TypeError. + if (keepalive) { + throw new TypeError('keepalive') + } + + // If object is disturbed or locked, then throw a TypeError. + if (util.isDisturbed(object) || object.locked) { + throw new TypeError( + 'Response body object should not be disturbed or locked' + ) + } + + stream = + object instanceof ReadableStream ? object : ReadableStreamFrom(object); + } + + // 11. If source is a byte sequence, then set action to a + // step that returns source and length to source’s length. + if (typeof source === 'string' || util.isBuffer(source)) { + length = Buffer.byteLength(source); + } + + // 12. If action is non-null, then run these steps in in parallel: + if (action != null) { + // Run action. + let iterator; + stream = new ReadableStream({ + async start () { + iterator = action(object)[Symbol.asyncIterator](); + }, + async pull (controller) { + const { value, done } = await iterator.next(); + if (done) { + // When running action is done, close stream. + queueMicrotask(() => { + controller.close(); + }); + } else { + // Whenever one or more bytes are available and stream is not errored, + // enqueue a Uint8Array wrapping an ArrayBuffer containing the available + // bytes into stream. + if (!isErrored(stream)) { + controller.enqueue(new Uint8Array(value)); + } + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return(); + }, + type: undefined + }); + } + + // 13. Let body be a body whose stream is stream, source is source, + // and length is length. + const body = { stream, source, length }; + + // 14. Return (body, type). + return [body, type] + } + + // https://fetch.spec.whatwg.org/#bodyinit-safely-extract + function safelyExtractBody (object, keepalive = false) { + if (!ReadableStream) { + // istanbul ignore next + ReadableStream = require$$14.ReadableStream; + } + + // To safely extract a body and a `Content-Type` value from + // a byte sequence or BodyInit object object, run these steps: + + // 1. If object is a ReadableStream object, then: + if (object instanceof ReadableStream) { + // Assert: object is neither disturbed nor locked. + // istanbul ignore next + assert(!util.isDisturbed(object), 'The body has already been consumed.'); + // istanbul ignore next + assert(!object.locked, 'The stream is locked.'); + } + + // 2. Return the results of extracting object. + return extractBody(object, keepalive) + } + + function cloneBody (body) { + // To clone a body body, run these steps: + + // https://fetch.spec.whatwg.org/#concept-body-clone + + // 1. Let « out1, out2 » be the result of teeing body’s stream. + const [out1, out2] = body.stream.tee(); + const out2Clone = structuredClone(out2, { transfer: [out2] }); + // This, for whatever reasons, unrefs out2Clone which allows + // the process to exit by itself. + const [, finalClone] = out2Clone.tee(); + + // 2. Set body’s stream to out1. + body.stream = out1; + + // 3. Return a body whose stream is out2 and other members are copied from body. + return { + stream: finalClone, + length: body.length, + source: body.source + } + } + + async function * consumeBody (body) { + if (body) { + if (isUint8Array(body)) { + yield body; + } else { + const stream = body.stream; + + if (util.isDisturbed(stream)) { + throw new TypeError('The body has already been consumed.') + } + + if (stream.locked) { + throw new TypeError('The stream is locked.') + } + + // Compat. + stream[kBodyUsed] = true; + + yield * stream; + } + } + } + + function throwIfAborted (state) { + if (state.aborted) { + throw new DOMException('The operation was aborted.', 'AbortError') + } + } + + function bodyMixinMethods (instance) { + const methods = { + blob () { + // The blob() method steps are to return the result of + // running consume body with this and the following step + // given a byte sequence bytes: return a Blob whose + // contents are bytes and whose type attribute is this’s + // MIME type. + return specConsumeBody(this, (bytes) => { + let mimeType = bodyMimeType(this); + + if (mimeType === 'failure') { + mimeType = ''; + } else if (mimeType) { + mimeType = serializeAMimeType(mimeType); + } + + // Return a Blob whose contents are bytes and type attribute + // is mimeType. + return new Blob([bytes], { type: mimeType }) + }, instance) + }, + + arrayBuffer () { + // The arrayBuffer() method steps are to return the result + // of running consume body with this and the following step + // given a byte sequence bytes: return a new ArrayBuffer + // whose contents are bytes. + return specConsumeBody(this, (bytes) => { + return new Uint8Array(bytes).buffer + }, instance) + }, + + text () { + // The text() method steps are to return the result of running + // consume body with this and UTF-8 decode. + return specConsumeBody(this, utf8DecodeBytes, instance) + }, + + json () { + // The json() method steps are to return the result of running + // consume body with this and parse JSON from bytes. + return specConsumeBody(this, parseJSONFromBytes, instance) + }, + + async formData () { + webidl.brandCheck(this, instance); + + throwIfAborted(this[kState]); + + const contentType = this.headers.get('Content-Type'); + + // If mimeType’s essence is "multipart/form-data", then: + if (/multipart\/form-data/.test(contentType)) { + const headers = {}; + for (const [key, value] of this.headers) headers[key.toLowerCase()] = value; + + const responseFormData = new FormData(); + + let busboy; + + try { + busboy = new Busboy({ + headers, + preservePath: true + }); + } catch (err) { + throw new DOMException(`${err}`, 'AbortError') + } + + busboy.on('field', (name, value) => { + responseFormData.append(name, value); + }); + busboy.on('file', (name, value, filename, encoding, mimeType) => { + const chunks = []; + + if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { + let base64chunk = ''; + + value.on('data', (chunk) => { + base64chunk += chunk.toString().replace(/[\r\n]/gm, ''); + + const end = base64chunk.length - base64chunk.length % 4; + chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64')); + + base64chunk = base64chunk.slice(end); + }); + value.on('end', () => { + chunks.push(Buffer.from(base64chunk, 'base64')); + responseFormData.append(name, new File(chunks, filename, { type: mimeType })); + }); + } else { + value.on('data', (chunk) => { + chunks.push(chunk); + }); + value.on('end', () => { + responseFormData.append(name, new File(chunks, filename, { type: mimeType })); + }); + } + }); + + const busboyResolve = new Promise((resolve, reject) => { + busboy.on('finish', resolve); + busboy.on('error', (err) => reject(new TypeError(err))); + }); + + if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk); + busboy.end(); + await busboyResolve; + + return responseFormData + } else if (/application\/x-www-form-urlencoded/.test(contentType)) { + // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then: + + // 1. Let entries be the result of parsing bytes. + let entries; + try { + let text = ''; + // application/x-www-form-urlencoded parser will keep the BOM. + // https://url.spec.whatwg.org/#concept-urlencoded-parser + const textDecoder = new TextDecoder('utf-8', { ignoreBOM: true }); + for await (const chunk of consumeBody(this[kState].body)) { + if (!isUint8Array(chunk)) { + throw new TypeError('Expected Uint8Array chunk') + } + text += textDecoder.decode(chunk, { stream: true }); + } + text += textDecoder.decode(); + entries = new URLSearchParams(text); + } catch (err) { + // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. + // 2. If entries is failure, then throw a TypeError. + throw Object.assign(new TypeError(), { cause: err }) + } + + // 3. Return a new FormData object whose entries are entries. + const formData = new FormData(); + for (const [name, value] of entries) { + formData.append(name, value); + } + return formData + } else { + // Wait a tick before checking if the request has been aborted. + // Otherwise, a TypeError can be thrown when an AbortError should. + await Promise.resolve(); + + throwIfAborted(this[kState]); + + // Otherwise, throw a TypeError. + throw webidl.errors.exception({ + header: `${instance.name}.formData`, + message: 'Could not parse content as FormData.' + }) + } + } + }; + + return methods + } + + function mixinBody (prototype) { + Object.assign(prototype.prototype, bodyMixinMethods(prototype)); + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-body-consume-body + * @param {Response|Request} object + * @param {(value: unknown) => unknown} convertBytesToJSValue + * @param {Response|Request} instance + */ + async function specConsumeBody (object, convertBytesToJSValue, instance) { + webidl.brandCheck(object, instance); + + throwIfAborted(object[kState]); + + // 1. If object is unusable, then return a promise rejected + // with a TypeError. + if (bodyUnusable(object[kState].body)) { + throw new TypeError('Body is unusable') + } + + // 2. Let promise be a new promise. + const promise = createDeferredPromise(); + + // 3. Let errorSteps given error be to reject promise with error. + const errorSteps = (error) => promise.reject(error); + + // 4. Let successSteps given a byte sequence data be to resolve + // promise with the result of running convertBytesToJSValue + // with data. If that threw an exception, then run errorSteps + // with that exception. + const successSteps = (data) => { + try { + promise.resolve(convertBytesToJSValue(data)); + } catch (e) { + errorSteps(e); + } + }; + + // 5. If object’s body is null, then run successSteps with an + // empty byte sequence. + if (object[kState].body == null) { + successSteps(new Uint8Array()); + return promise.promise + } + + // 6. Otherwise, fully read object’s body given successSteps, + // errorSteps, and object’s relevant global object. + await fullyReadBody(object[kState].body, successSteps, errorSteps); + + // 7. Return promise. + return promise.promise + } + + // https://fetch.spec.whatwg.org/#body-unusable + function bodyUnusable (body) { + // An object including the Body interface mixin is + // said to be unusable if its body is non-null and + // its body’s stream is disturbed or locked. + return body != null && (body.stream.locked || util.isDisturbed(body.stream)) + } + + /** + * @see https://encoding.spec.whatwg.org/#utf-8-decode + * @param {Buffer} buffer + */ + function utf8DecodeBytes (buffer) { + if (buffer.length === 0) { + return '' + } + + // 1. Let buffer be the result of peeking three bytes from + // ioQueue, converted to a byte sequence. + + // 2. If buffer is 0xEF 0xBB 0xBF, then read three + // bytes from ioQueue. (Do nothing with those bytes.) + if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + buffer = buffer.subarray(3); + } + + // 3. Process a queue with an instance of UTF-8’s + // decoder, ioQueue, output, and "replacement". + const output = new TextDecoder().decode(buffer); + + // 4. Return output. + return output + } + + /** + * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value + * @param {Uint8Array} bytes + */ + function parseJSONFromBytes (bytes) { + return JSON.parse(utf8DecodeBytes(bytes)) + } + + /** + * @see https://fetch.spec.whatwg.org/#concept-body-mime-type + * @param {import('./response').Response|import('./request').Request} object + */ + function bodyMimeType (object) { + const { headersList } = object[kState]; + const contentType = headersList.get('content-type'); + + if (contentType === null) { + return 'failure' + } + + return parseMIMEType(contentType) + } + + body = { + extractBody, + safelyExtractBody, + cloneBody, + mixinBody + }; + return body; + } + + const { + InvalidArgumentError: InvalidArgumentError$k, + NotSupportedError: NotSupportedError$1 + } = errors$1; + const assert$8 = require$$3$1; + const { kHTTP2BuildRequest: kHTTP2BuildRequest$1, kHTTP2CopyHeaders: kHTTP2CopyHeaders$1, kHTTP1BuildRequest: kHTTP1BuildRequest$1 } = symbols$4; + const util$j = util$l; + + // tokenRegExp and headerCharRegex have been lifted from + // https://github.com/nodejs/node/blob/main/lib/_http_common.js + + /** + * Verifies that the given val is a valid HTTP token + * per the rules defined in RFC 7230 + * See https://tools.ietf.org/html/rfc7230#section-3.2.6 + */ + const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/; + + /** + * Matches if val contains an invalid field-vchar + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + */ + const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/; + + // Verifies that a given path is valid does not contain control chars \x00 to \x20 + const invalidPathRegex = /[^\u0021-\u00ff]/; + + const kHandler = Symbol('handler'); + + const channels$1 = {}; + + let extractBody; + + try { + const diagnosticsChannel = require$$1$2; + channels$1.create = diagnosticsChannel.channel('undici:request:create'); + channels$1.bodySent = diagnosticsChannel.channel('undici:request:bodySent'); + channels$1.headers = diagnosticsChannel.channel('undici:request:headers'); + channels$1.trailers = diagnosticsChannel.channel('undici:request:trailers'); + channels$1.error = diagnosticsChannel.channel('undici:request:error'); + } catch { + channels$1.create = { hasSubscribers: false }; + channels$1.bodySent = { hasSubscribers: false }; + channels$1.headers = { hasSubscribers: false }; + channels$1.trailers = { hasSubscribers: false }; + channels$1.error = { hasSubscribers: false }; + } + + let Request$1 = class Request { + constructor (origin, { + path, + method, + body, + headers, + query, + idempotent, + blocking, + upgrade, + headersTimeout, + bodyTimeout, + reset, + throwOnError, + expectContinue + }, handler) { + if (typeof path !== 'string') { + throw new InvalidArgumentError$k('path must be a string') + } else if ( + path[0] !== '/' && + !(path.startsWith('http://') || path.startsWith('https://')) && + method !== 'CONNECT' + ) { + throw new InvalidArgumentError$k('path must be an absolute URL or start with a slash') + } else if (invalidPathRegex.exec(path) !== null) { + throw new InvalidArgumentError$k('invalid request path') + } + + if (typeof method !== 'string') { + throw new InvalidArgumentError$k('method must be a string') + } else if (tokenRegExp.exec(method) === null) { + throw new InvalidArgumentError$k('invalid request method') + } + + if (upgrade && typeof upgrade !== 'string') { + throw new InvalidArgumentError$k('upgrade must be a string') + } + + if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError$k('invalid headersTimeout') + } + + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError$k('invalid bodyTimeout') + } + + if (reset != null && typeof reset !== 'boolean') { + throw new InvalidArgumentError$k('invalid reset') + } + + if (expectContinue != null && typeof expectContinue !== 'boolean') { + throw new InvalidArgumentError$k('invalid expectContinue') + } + + this.headersTimeout = headersTimeout; + + this.bodyTimeout = bodyTimeout; + + this.throwOnError = throwOnError === true; + + this.method = method; + + if (body == null) { + this.body = null; + } else if (util$j.isStream(body)) { + this.body = body; + } else if (util$j.isBuffer(body)) { + this.body = body.byteLength ? body : null; + } else if (ArrayBuffer.isView(body)) { + this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null; + } else if (body instanceof ArrayBuffer) { + this.body = body.byteLength ? Buffer.from(body) : null; + } else if (typeof body === 'string') { + this.body = body.length ? Buffer.from(body) : null; + } else if (util$j.isFormDataLike(body) || util$j.isIterable(body) || util$j.isBlobLike(body)) { + this.body = body; + } else { + throw new InvalidArgumentError$k('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') + } + + this.completed = false; + + this.aborted = false; + + this.upgrade = upgrade || null; + + this.path = query ? util$j.buildURL(path, query) : path; + + this.origin = origin; + + this.idempotent = idempotent == null + ? method === 'HEAD' || method === 'GET' + : idempotent; + + this.blocking = blocking == null ? false : blocking; + + this.reset = reset == null ? null : reset; + + this.host = null; + + this.contentLength = null; + + this.contentType = null; + + this.headers = ''; + + // Only for H2 + this.expectContinue = expectContinue != null ? expectContinue : false; + + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError$k('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(this, headers[i], headers[i + 1]); + } + } else if (headers && typeof headers === 'object') { + const keys = Object.keys(headers); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + processHeader(this, key, headers[key]); + } + } else if (headers != null) { + throw new InvalidArgumentError$k('headers must be an object or an array') + } + + if (util$j.isFormDataLike(this.body)) { + if (util$j.nodeMajor < 16 || (util$j.nodeMajor === 16 && util$j.nodeMinor < 8)) { + throw new InvalidArgumentError$k('Form-Data bodies are only supported in node v16.8 and newer.') + } + + if (!extractBody) { + extractBody = requireBody().extractBody; + } + + const [bodyStream, contentType] = extractBody(body); + if (this.contentType == null) { + this.contentType = contentType; + this.headers += `content-type: ${contentType}\r\n`; + } + this.body = bodyStream.stream; + this.contentLength = bodyStream.length; + } else if (util$j.isBlobLike(body) && this.contentType == null && body.type) { + this.contentType = body.type; + this.headers += `content-type: ${body.type}\r\n`; + } + + util$j.validateHandler(handler, method, upgrade); + + this.servername = util$j.getServerName(this.host); + + this[kHandler] = handler; + + if (channels$1.create.hasSubscribers) { + channels$1.create.publish({ request: this }); + } + } + + onBodySent (chunk) { + if (this[kHandler].onBodySent) { + try { + this[kHandler].onBodySent(chunk); + } catch (err) { + this.onError(err); + } + } + } + + onRequestSent () { + if (channels$1.bodySent.hasSubscribers) { + channels$1.bodySent.publish({ request: this }); + } + } + + onConnect (abort) { + assert$8(!this.aborted); + assert$8(!this.completed); + + return this[kHandler].onConnect(abort) + } + + onHeaders (statusCode, headers, resume, statusText) { + assert$8(!this.aborted); + assert$8(!this.completed); + + if (channels$1.headers.hasSubscribers) { + channels$1.headers.publish({ request: this, response: { statusCode, headers, statusText } }); + } + + return this[kHandler].onHeaders(statusCode, headers, resume, statusText) + } + + onData (chunk) { + assert$8(!this.aborted); + assert$8(!this.completed); + + return this[kHandler].onData(chunk) + } + + onUpgrade (statusCode, headers, socket) { + assert$8(!this.aborted); + assert$8(!this.completed); + + return this[kHandler].onUpgrade(statusCode, headers, socket) + } + + onComplete (trailers) { + assert$8(!this.aborted); + + this.completed = true; + if (channels$1.trailers.hasSubscribers) { + channels$1.trailers.publish({ request: this, trailers }); + } + return this[kHandler].onComplete(trailers) + } + + onError (error) { + if (channels$1.error.hasSubscribers) { + channels$1.error.publish({ request: this, error }); + } + + if (this.aborted) { + return + } + this.aborted = true; + return this[kHandler].onError(error) + } + + // TODO: adjust to support H2 + addHeader (key, value) { + processHeader(this, key, value); + return this + } + + static [kHTTP1BuildRequest$1] (origin, opts, handler) { + // TODO: Migrate header parsing here, to make Requests + // HTTP agnostic + return new Request(origin, opts, handler) + } + + static [kHTTP2BuildRequest$1] (origin, opts, handler) { + const headers = opts.headers; + opts = { ...opts, headers: null }; + + const request = new Request(origin, opts, handler); + + request.headers = {}; + + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError$k('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(request, headers[i], headers[i + 1], true); + } + } else if (headers && typeof headers === 'object') { + const keys = Object.keys(headers); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + processHeader(request, key, headers[key], true); + } + } else if (headers != null) { + throw new InvalidArgumentError$k('headers must be an object or an array') + } + + return request + } + + static [kHTTP2CopyHeaders$1] (raw) { + const rawHeaders = raw.split('\r\n'); + const headers = {}; + + for (const header of rawHeaders) { + const [key, value] = header.split(': '); + + if (value == null || value.length === 0) continue + + if (headers[key]) headers[key] += `,${value}`; + else headers[key] = value; + } + + return headers + } + }; + + function processHeaderValue (key, val, skipAppend) { + if (val && typeof val === 'object') { + throw new InvalidArgumentError$k(`invalid ${key} header`) + } + + val = val != null ? `${val}` : ''; + + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError$k(`invalid ${key} header`) + } + + return skipAppend ? val : `${key}: ${val}\r\n` + } + + function processHeader (request, key, val, skipAppend = false) { + if (val && (typeof val === 'object' && !Array.isArray(val))) { + throw new InvalidArgumentError$k(`invalid ${key} header`) + } else if (val === undefined) { + return + } + + if ( + request.host === null && + key.length === 4 && + key.toLowerCase() === 'host' + ) { + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError$k(`invalid ${key} header`) + } + // Consumed by Client + request.host = val; + } else if ( + request.contentLength === null && + key.length === 14 && + key.toLowerCase() === 'content-length' + ) { + request.contentLength = parseInt(val, 10); + if (!Number.isFinite(request.contentLength)) { + throw new InvalidArgumentError$k('invalid content-length header') + } + } else if ( + request.contentType === null && + key.length === 12 && + key.toLowerCase() === 'content-type' + ) { + request.contentType = val; + if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend); + else request.headers += processHeaderValue(key, val); + } else if ( + key.length === 17 && + key.toLowerCase() === 'transfer-encoding' + ) { + throw new InvalidArgumentError$k('invalid transfer-encoding header') + } else if ( + key.length === 10 && + key.toLowerCase() === 'connection' + ) { + const value = typeof val === 'string' ? val.toLowerCase() : null; + if (value !== 'close' && value !== 'keep-alive') { + throw new InvalidArgumentError$k('invalid connection header') + } else if (value === 'close') { + request.reset = true; + } + } else if ( + key.length === 10 && + key.toLowerCase() === 'keep-alive' + ) { + throw new InvalidArgumentError$k('invalid keep-alive header') + } else if ( + key.length === 7 && + key.toLowerCase() === 'upgrade' + ) { + throw new InvalidArgumentError$k('invalid upgrade header') + } else if ( + key.length === 6 && + key.toLowerCase() === 'expect' + ) { + throw new NotSupportedError$1('expect header not supported') + } else if (tokenRegExp.exec(key) === null) { + throw new InvalidArgumentError$k('invalid header key') + } else { + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + if (skipAppend) { + if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}`; + else request.headers[key] = processHeaderValue(key, val[i], skipAppend); + } else { + request.headers += processHeaderValue(key, val[i]); + } + } + } else { + if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend); + else request.headers += processHeaderValue(key, val); + } + } + } + + var request$2 = Request$1; + + const EventEmitter = require$$10$1; + + let Dispatcher$3 = class Dispatcher extends EventEmitter { + dispatch () { + throw new Error('not implemented') + } + + close () { + throw new Error('not implemented') + } + + destroy () { + throw new Error('not implemented') + } + }; + + var dispatcher = Dispatcher$3; + + const Dispatcher$2 = dispatcher; + const { + ClientDestroyedError: ClientDestroyedError$1, + ClientClosedError, + InvalidArgumentError: InvalidArgumentError$j + } = errors$1; + const { kDestroy: kDestroy$4, kClose: kClose$6, kDispatch: kDispatch$3, kInterceptors: kInterceptors$5 } = symbols$4; + + const kDestroyed = Symbol('destroyed'); + const kClosed = Symbol('closed'); + const kOnDestroyed = Symbol('onDestroyed'); + const kOnClosed = Symbol('onClosed'); + const kInterceptedDispatch = Symbol('Intercepted Dispatch'); + + let DispatcherBase$4 = class DispatcherBase extends Dispatcher$2 { + constructor () { + super(); + + this[kDestroyed] = false; + this[kOnDestroyed] = null; + this[kClosed] = false; + this[kOnClosed] = []; + } + + get destroyed () { + return this[kDestroyed] + } + + get closed () { + return this[kClosed] + } + + get interceptors () { + return this[kInterceptors$5] + } + + set interceptors (newInterceptors) { + if (newInterceptors) { + for (let i = newInterceptors.length - 1; i >= 0; i--) { + const interceptor = this[kInterceptors$5][i]; + if (typeof interceptor !== 'function') { + throw new InvalidArgumentError$j('interceptor must be an function') + } + } + } + + this[kInterceptors$5] = newInterceptors; + } + + close (callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.close((err, data) => { + return err ? reject(err) : resolve(data) + }); + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError$j('invalid callback') + } + + if (this[kDestroyed]) { + queueMicrotask(() => callback(new ClientDestroyedError$1(), null)); + return + } + + if (this[kClosed]) { + if (this[kOnClosed]) { + this[kOnClosed].push(callback); + } else { + queueMicrotask(() => callback(null, null)); + } + return + } + + this[kClosed] = true; + this[kOnClosed].push(callback); + + const onClosed = () => { + const callbacks = this[kOnClosed]; + this[kOnClosed] = null; + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null); + } + }; + + // Should not error. + this[kClose$6]() + .then(() => this.destroy()) + .then(() => { + queueMicrotask(onClosed); + }); + } + + destroy (err, callback) { + if (typeof err === 'function') { + callback = err; + err = null; + } + + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.destroy(err, (err, data) => { + return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) + }); + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError$j('invalid callback') + } + + if (this[kDestroyed]) { + if (this[kOnDestroyed]) { + this[kOnDestroyed].push(callback); + } else { + queueMicrotask(() => callback(null, null)); + } + return + } + + if (!err) { + err = new ClientDestroyedError$1(); + } + + this[kDestroyed] = true; + this[kOnDestroyed] = this[kOnDestroyed] || []; + this[kOnDestroyed].push(callback); + + const onDestroyed = () => { + const callbacks = this[kOnDestroyed]; + this[kOnDestroyed] = null; + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null); + } + }; + + // Should not error. + this[kDestroy$4](err).then(() => { + queueMicrotask(onDestroyed); + }); + } + + [kInterceptedDispatch] (opts, handler) { + if (!this[kInterceptors$5] || this[kInterceptors$5].length === 0) { + this[kInterceptedDispatch] = this[kDispatch$3]; + return this[kDispatch$3](opts, handler) + } + + let dispatch = this[kDispatch$3].bind(this); + for (let i = this[kInterceptors$5].length - 1; i >= 0; i--) { + dispatch = this[kInterceptors$5][i](dispatch); + } + this[kInterceptedDispatch] = dispatch; + return dispatch(opts, handler) + } + + dispatch (opts, handler) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError$j('handler must be an object') + } + + try { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError$j('opts must be an object.') + } + + if (this[kDestroyed] || this[kOnDestroyed]) { + throw new ClientDestroyedError$1() + } + + if (this[kClosed]) { + throw new ClientClosedError() + } + + return this[kInterceptedDispatch](opts, handler) + } catch (err) { + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError$j('invalid onError method') + } + + handler.onError(err); + + return false + } + } + }; + + var dispatcherBase = DispatcherBase$4; + + var _polyfillNode_tls = {}; + + var _polyfillNode_tls$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + default: _polyfillNode_tls + }); + + var require$$4 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_tls$1); + + const net$1 = require$$1$3; + const assert$7 = require$$3$1; + const util$i = util$l; + const { InvalidArgumentError: InvalidArgumentError$i, ConnectTimeoutError } = errors$1; + + let tls; // include tls conditionally since it is not always available + + // TODO: session re-use does not wait for the first + // connection to resolve the session and might therefore + // resolve the same servername multiple times even when + // re-use is enabled. + + let SessionCache; + // FIXME: remove workaround when the Node bug is fixed + // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 + if (commonjsGlobal.FinalizationRegistry && !browser$1$1.env.NODE_V8_COVERAGE) { + SessionCache = class WeakSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions; + this._sessionCache = new Map(); + this._sessionRegistry = new commonjsGlobal.FinalizationRegistry((key) => { + if (this._sessionCache.size < this._maxCachedSessions) { + return + } + + const ref = this._sessionCache.get(key); + if (ref !== undefined && ref.deref() === undefined) { + this._sessionCache.delete(key); + } + }); + } + + get (sessionKey) { + const ref = this._sessionCache.get(sessionKey); + return ref ? ref.deref() : null + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + this._sessionCache.set(sessionKey, new WeakRef(session)); + this._sessionRegistry.register(session, sessionKey); + } + }; + } else { + SessionCache = class SimpleSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions; + this._sessionCache = new Map(); + } + + get (sessionKey) { + return this._sessionCache.get(sessionKey) + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + if (this._sessionCache.size >= this._maxCachedSessions) { + // remove the oldest session + const { value: oldestKey } = this._sessionCache.keys().next(); + this._sessionCache.delete(oldestKey); + } + + this._sessionCache.set(sessionKey, session); + } + }; + } + + function buildConnector$4 ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) { + if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { + throw new InvalidArgumentError$i('maxCachedSessions must be a positive integer or zero') + } + + const options = { path: socketPath, ...opts }; + const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions); + timeout = timeout == null ? 10e3 : timeout; + allowH2 = allowH2 != null ? allowH2 : false; + return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { + let socket; + if (protocol === 'https:') { + if (!tls) { + tls = require$$4; + } + servername = servername || options.servername || util$i.getServerName(host) || null; + + const sessionKey = servername || hostname; + const session = sessionCache.get(sessionKey) || null; + + assert$7(sessionKey); + + socket = tls.connect({ + highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... + ...options, + servername, + session, + localAddress, + // TODO(HTTP/2): Add support for h2c + ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], + socket: httpSocket, // upgrade socket connection + port: port || 443, + host: hostname + }); + + socket + .on('session', function (session) { + // TODO (fix): Can a session become invalid once established? Don't think so? + sessionCache.set(sessionKey, session); + }); + } else { + assert$7(!httpSocket, 'httpSocket can only be sent on TLS update'); + socket = net$1.connect({ + highWaterMark: 64 * 1024, // Same as nodejs fs streams. + ...options, + localAddress, + port: port || 80, + host: hostname + }); + } + + // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket + if (options.keepAlive == null || options.keepAlive) { + const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay; + socket.setKeepAlive(true, keepAliveInitialDelay); + } + + const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout); + + socket + .setNoDelay(true) + .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { + cancelTimeout(); + + if (callback) { + const cb = callback; + callback = null; + cb(null, this); + } + }) + .on('error', function (err) { + cancelTimeout(); + + if (callback) { + const cb = callback; + callback = null; + cb(err); + } + }); + + return socket + } + } + + function setupTimeout (onConnectTimeout, timeout) { + if (!timeout) { + return () => {} + } + + let s1 = null; + let s2 = null; + const timeoutId = setTimeout(() => { + // setImmediate is added to make sure that we priotorise socket error events over timeouts + s1 = setImmediate(() => { + if (browser$1$1.platform === 'win32') { + // Windows needs an extra setImmediate probably due to implementation differences in the socket logic + s2 = setImmediate(() => onConnectTimeout()); + } else { + onConnectTimeout(); + } + }); + }, timeout); + return () => { + clearTimeout(timeoutId); + clearImmediate(s1); + clearImmediate(s2); + } + } + + function onConnectTimeout (socket) { + util$i.destroy(socket, new ConnectTimeoutError()); + } + + var connect$2 = buildConnector$4; + + const constants$4 = { + HTTP2_HEADER_AUTHORITY: "authority", + HTTP2_HEADER_METHOD: "method", + HTTP2_HEADER_PATH: "path", + HTTP2_HEADER_SCHEME: "scheme", + HTTP2_HEADER_CONTENT_LENGTH: "content-length", + HTTP2_HEADER_EXPECT: "expect", + HTTP2_HEADER_STATUS: "status", + }; + + var _polyfillNode_http2 = /*#__PURE__*/Object.freeze({ + __proto__: null, + constants: constants$4 + }); + + var require$$11 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_http2); + + var constants$3 = {}; + + var utils = {}; + + var hasRequiredUtils; + + function requireUtils () { + if (hasRequiredUtils) return utils; + hasRequiredUtils = 1; + Object.defineProperty(utils, "__esModule", { value: true }); + utils.enumToMap = void 0; + function enumToMap(obj) { + const res = {}; + Object.keys(obj).forEach((key) => { + const value = obj[key]; + if (typeof value === 'number') { + res[key] = value; + } + }); + return res; + } + utils.enumToMap = enumToMap; + + return utils; + } + + var hasRequiredConstants$2; + + function requireConstants$2 () { + if (hasRequiredConstants$2) return constants$3; + hasRequiredConstants$2 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; + const utils_1 = requireUtils(); + (function (ERROR) { + ERROR[ERROR["OK"] = 0] = "OK"; + ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL"; + ERROR[ERROR["STRICT"] = 2] = "STRICT"; + ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED"; + ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; + ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; + ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD"; + ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL"; + ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; + ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION"; + ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; + ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; + ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; + ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS"; + ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; + ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; + ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; + ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; + ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; + ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; + ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; + ERROR[ERROR["PAUSED"] = 21] = "PAUSED"; + ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; + ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; + ERROR[ERROR["USER"] = 24] = "USER"; + })(exports.ERROR || (exports.ERROR = {})); + (function (TYPE) { + TYPE[TYPE["BOTH"] = 0] = "BOTH"; + TYPE[TYPE["REQUEST"] = 1] = "REQUEST"; + TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE"; + })(exports.TYPE || (exports.TYPE = {})); + (function (FLAGS) { + FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; + FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; + FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; + FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED"; + FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE"; + FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; + FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY"; + FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING"; + // 1 << 8 is unused + FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; + })(exports.FLAGS || (exports.FLAGS = {})); + (function (LENIENT_FLAGS) { + LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS"; + LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; + LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; + })(exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {})); + var METHODS; + (function (METHODS) { + METHODS[METHODS["DELETE"] = 0] = "DELETE"; + METHODS[METHODS["GET"] = 1] = "GET"; + METHODS[METHODS["HEAD"] = 2] = "HEAD"; + METHODS[METHODS["POST"] = 3] = "POST"; + METHODS[METHODS["PUT"] = 4] = "PUT"; + /* pathological */ + METHODS[METHODS["CONNECT"] = 5] = "CONNECT"; + METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS"; + METHODS[METHODS["TRACE"] = 7] = "TRACE"; + /* WebDAV */ + METHODS[METHODS["COPY"] = 8] = "COPY"; + METHODS[METHODS["LOCK"] = 9] = "LOCK"; + METHODS[METHODS["MKCOL"] = 10] = "MKCOL"; + METHODS[METHODS["MOVE"] = 11] = "MOVE"; + METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND"; + METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH"; + METHODS[METHODS["SEARCH"] = 14] = "SEARCH"; + METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK"; + METHODS[METHODS["BIND"] = 16] = "BIND"; + METHODS[METHODS["REBIND"] = 17] = "REBIND"; + METHODS[METHODS["UNBIND"] = 18] = "UNBIND"; + METHODS[METHODS["ACL"] = 19] = "ACL"; + /* subversion */ + METHODS[METHODS["REPORT"] = 20] = "REPORT"; + METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY"; + METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT"; + METHODS[METHODS["MERGE"] = 23] = "MERGE"; + /* upnp */ + METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH"; + METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY"; + METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE"; + METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; + /* RFC-5789 */ + METHODS[METHODS["PATCH"] = 28] = "PATCH"; + METHODS[METHODS["PURGE"] = 29] = "PURGE"; + /* CalDAV */ + METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR"; + /* RFC-2068, section 19.6.1.2 */ + METHODS[METHODS["LINK"] = 31] = "LINK"; + METHODS[METHODS["UNLINK"] = 32] = "UNLINK"; + /* icecast */ + METHODS[METHODS["SOURCE"] = 33] = "SOURCE"; + /* RFC-7540, section 11.6 */ + METHODS[METHODS["PRI"] = 34] = "PRI"; + /* RFC-2326 RTSP */ + METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE"; + METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE"; + METHODS[METHODS["SETUP"] = 37] = "SETUP"; + METHODS[METHODS["PLAY"] = 38] = "PLAY"; + METHODS[METHODS["PAUSE"] = 39] = "PAUSE"; + METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN"; + METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER"; + METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER"; + METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT"; + METHODS[METHODS["RECORD"] = 44] = "RECORD"; + /* RAOP */ + METHODS[METHODS["FLUSH"] = 45] = "FLUSH"; + })(METHODS = exports.METHODS || (exports.METHODS = {})); + exports.METHODS_HTTP = [ + METHODS.DELETE, + METHODS.GET, + METHODS.HEAD, + METHODS.POST, + METHODS.PUT, + METHODS.CONNECT, + METHODS.OPTIONS, + METHODS.TRACE, + METHODS.COPY, + METHODS.LOCK, + METHODS.MKCOL, + METHODS.MOVE, + METHODS.PROPFIND, + METHODS.PROPPATCH, + METHODS.SEARCH, + METHODS.UNLOCK, + METHODS.BIND, + METHODS.REBIND, + METHODS.UNBIND, + METHODS.ACL, + METHODS.REPORT, + METHODS.MKACTIVITY, + METHODS.CHECKOUT, + METHODS.MERGE, + METHODS['M-SEARCH'], + METHODS.NOTIFY, + METHODS.SUBSCRIBE, + METHODS.UNSUBSCRIBE, + METHODS.PATCH, + METHODS.PURGE, + METHODS.MKCALENDAR, + METHODS.LINK, + METHODS.UNLINK, + METHODS.PRI, + // TODO(indutny): should we allow it with HTTP? + METHODS.SOURCE, + ]; + exports.METHODS_ICE = [ + METHODS.SOURCE, + ]; + exports.METHODS_RTSP = [ + METHODS.OPTIONS, + METHODS.DESCRIBE, + METHODS.ANNOUNCE, + METHODS.SETUP, + METHODS.PLAY, + METHODS.PAUSE, + METHODS.TEARDOWN, + METHODS.GET_PARAMETER, + METHODS.SET_PARAMETER, + METHODS.REDIRECT, + METHODS.RECORD, + METHODS.FLUSH, + // For AirPlay + METHODS.GET, + METHODS.POST, + ]; + exports.METHOD_MAP = utils_1.enumToMap(METHODS); + exports.H_METHOD_MAP = {}; + Object.keys(exports.METHOD_MAP).forEach((key) => { + if (/^H/.test(key)) { + exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key]; + } + }); + (function (FINISH) { + FINISH[FINISH["SAFE"] = 0] = "SAFE"; + FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; + FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE"; + })(exports.FINISH || (exports.FINISH = {})); + exports.ALPHA = []; + for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { + // Upper case + exports.ALPHA.push(String.fromCharCode(i)); + // Lower case + exports.ALPHA.push(String.fromCharCode(i + 0x20)); + } + exports.NUM_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, + }; + exports.HEX_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, + A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, + a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, + }; + exports.NUM = [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', + ]; + exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); + exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; + exports.USERINFO_CHARS = exports.ALPHANUM + .concat(exports.MARK) + .concat(['%', ';', ':', '&', '=', '+', '$', ',']); + // TODO(indutny): use RFC + exports.STRICT_URL_CHAR = [ + '!', '"', '$', '%', '&', '\'', + '(', ')', '*', '+', ',', '-', '.', '/', + ':', ';', '<', '=', '>', + '@', '[', '\\', ']', '^', '_', + '`', + '{', '|', '}', '~', + ].concat(exports.ALPHANUM); + exports.URL_CHAR = exports.STRICT_URL_CHAR + .concat(['\t', '\f']); + // All characters with 0x80 bit set to 1 + for (let i = 0x80; i <= 0xff; i++) { + exports.URL_CHAR.push(i); + } + exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); + /* Tokens as defined by rfc 2616. Also lowercases them. + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + */ + exports.STRICT_TOKEN = [ + '!', '#', '$', '%', '&', '\'', + '*', '+', '-', '.', + '^', '_', '`', + '|', '~', + ].concat(exports.ALPHANUM); + exports.TOKEN = exports.STRICT_TOKEN.concat([' ']); + /* + * Verify that a char is a valid visible (printable) US-ASCII + * character or %x80-FF + */ + exports.HEADER_CHARS = ['\t']; + for (let i = 32; i <= 255; i++) { + if (i !== 127) { + exports.HEADER_CHARS.push(i); + } + } + // ',' = \x44 + exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); + exports.MAJOR = exports.NUM_MAP; + exports.MINOR = exports.MAJOR; + var HEADER_STATE; + (function (HEADER_STATE) { + HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL"; + HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION"; + HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; + HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE"; + HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; + HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; + HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; + })(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {})); + exports.SPECIAL_HEADERS = { + 'connection': HEADER_STATE.CONNECTION, + 'content-length': HEADER_STATE.CONTENT_LENGTH, + 'proxy-connection': HEADER_STATE.CONNECTION, + 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING, + 'upgrade': HEADER_STATE.UPGRADE, + }; + + } (constants$3)); + return constants$3; + } + + const util$h = util$l; + const { kBodyUsed } = symbols$4; + const assert$6 = require$$3$1; + const { InvalidArgumentError: InvalidArgumentError$h } = errors$1; + const EE = require$$10$1; + + const redirectableStatusCodes = [300, 301, 302, 303, 307, 308]; + + const kBody$1 = Symbol('body'); + + class BodyAsyncIterable { + constructor (body) { + this[kBody$1] = body; + this[kBodyUsed] = false; + } + + async * [Symbol.asyncIterator] () { + assert$6(!this[kBodyUsed], 'disturbed'); + this[kBodyUsed] = true; + yield * this[kBody$1]; + } + } + + let RedirectHandler$2 = class RedirectHandler { + constructor (dispatch, maxRedirections, opts, handler) { + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError$h('maxRedirections must be a positive number') + } + + util$h.validateHandler(handler, opts.method, opts.upgrade); + + this.dispatch = dispatch; + this.location = null; + this.abort = null; + this.opts = { ...opts, maxRedirections: 0 }; // opts must be a copy + this.maxRedirections = maxRedirections; + this.handler = handler; + this.history = []; + + if (util$h.isStream(this.opts.body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (util$h.bodyLength(this.opts.body) === 0) { + this.opts.body + .on('data', function () { + assert$6(false); + }); + } + + if (typeof this.opts.body.readableDidRead !== 'boolean') { + this.opts.body[kBodyUsed] = false; + EE.prototype.on.call(this.opts.body, 'data', function () { + this[kBodyUsed] = true; + }); + } + } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + this.opts.body = new BodyAsyncIterable(this.opts.body); + } else if ( + this.opts.body && + typeof this.opts.body !== 'string' && + !ArrayBuffer.isView(this.opts.body) && + util$h.isIterable(this.opts.body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + this.opts.body = new BodyAsyncIterable(this.opts.body); + } + } + + onConnect (abort) { + this.abort = abort; + this.handler.onConnect(abort, { history: this.history }); + } + + onUpgrade (statusCode, headers, socket) { + this.handler.onUpgrade(statusCode, headers, socket); + } + + onError (error) { + this.handler.onError(error); + } + + onHeaders (statusCode, headers, resume, statusText) { + this.location = this.history.length >= this.maxRedirections || util$h.isDisturbed(this.opts.body) + ? null + : parseLocation(statusCode, headers); + + if (this.opts.origin) { + this.history.push(new URL(this.opts.path, this.opts.origin)); + } + + if (!this.location) { + return this.handler.onHeaders(statusCode, headers, resume, statusText) + } + + const { origin, pathname, search } = util$h.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))); + const path = search ? `${pathname}${search}` : pathname; + + // Remove headers referring to the original URL. + // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. + // https://tools.ietf.org/html/rfc7231#section-6.4 + this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin); + this.opts.path = path; + this.opts.origin = origin; + this.opts.maxRedirections = 0; + this.opts.query = null; + + // https://tools.ietf.org/html/rfc7231#section-6.4.4 + // In case of HTTP 303, always replace method to be either HEAD or GET + if (statusCode === 303 && this.opts.method !== 'HEAD') { + this.opts.method = 'GET'; + this.opts.body = null; + } + } + + onData (chunk) { + if (this.location) ; else { + return this.handler.onData(chunk) + } + } + + onComplete (trailers) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections + and neither are useful if present. + + See comment on onData method above for more detailed informations. + */ + + this.location = null; + this.abort = null; + + this.dispatch(this.opts, this); + } else { + this.handler.onComplete(trailers); + } + } + + onBodySent (chunk) { + if (this.handler.onBodySent) { + this.handler.onBodySent(chunk); + } + } + }; + + function parseLocation (statusCode, headers) { + if (redirectableStatusCodes.indexOf(statusCode) === -1) { + return null + } + + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toString().toLowerCase() === 'location') { + return headers[i + 1] + } + } + } + + // https://tools.ietf.org/html/rfc7231#section-6.4.4 + function shouldRemoveHeader (header, removeContent, unknownOrigin) { + return ( + (header.length === 4 && header.toString().toLowerCase() === 'host') || + (removeContent && header.toString().toLowerCase().indexOf('content-') === 0) || + (unknownOrigin && header.length === 13 && header.toString().toLowerCase() === 'authorization') || + (unknownOrigin && header.length === 6 && header.toString().toLowerCase() === 'cookie') + ) + } + + // https://tools.ietf.org/html/rfc7231#section-6.4 + function cleanRequestHeaders (headers, removeContent, unknownOrigin) { + const ret = []; + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { + ret.push(headers[i], headers[i + 1]); + } + } + } else if (headers && typeof headers === 'object') { + for (const key of Object.keys(headers)) { + if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { + ret.push(key, headers[key]); + } + } + } else { + assert$6(headers == null, 'headers must be an object or an array'); + } + return ret + } + + var RedirectHandler_1 = RedirectHandler$2; + + const RedirectHandler$1 = RedirectHandler_1; + + function createRedirectInterceptor$3 ({ maxRedirections: defaultMaxRedirections }) { + return (dispatch) => { + return function Intercept (opts, handler) { + const { maxRedirections = defaultMaxRedirections } = opts; + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler$1(dispatch, maxRedirections, opts, handler); + opts = { ...opts, maxRedirections: 0 }; // Stop sub dispatcher from also redirecting. + return dispatch(opts, redirectHandler) + } + } + } + + var redirectInterceptor = createRedirectInterceptor$3; + + var llhttpWasm; + var hasRequiredLlhttpWasm; + + function requireLlhttpWasm () { + if (hasRequiredLlhttpWasm) return llhttpWasm; + hasRequiredLlhttpWasm = 1; + llhttpWasm = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB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gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAk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EHNgIMQQAhEAyvAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAyuAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAytAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAUNgIUIAAgATYCDEEAIRAMogELIABBADYCHCAAIBQ2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKEBCyAAQQA2AhwgACABNgIUIABBw4+AgAA2AhAgAEEHNgIMQQAhEAygAQtBACEQIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgwMnwELI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AABOT1VOQ0VFQ0tPVVRORUNURVRFQ1JJQkVMVVNIRVRFQURTRUFSQ0hSR0VDVElWSVRZTEVOREFSVkVPVElGWVBUSU9OU0NIU0VBWVNUQVRDSEdFT1JESVJFQ1RPUlRSQ0hQQVJBTUVURVJVUkNFQlNDUklCRUFSRE9XTkFDRUlORE5LQ0tVQlNDUklCRUhUVFAvQURUUC8='; + return llhttpWasm; + } + + var llhttp_simdWasm; + var hasRequiredLlhttp_simdWasm; + + function requireLlhttp_simdWasm () { + if (hasRequiredLlhttp_simdWasm) return llhttp_simdWasm; + hasRequiredLlhttp_simdWasm = 1; + llhttp_simdWasm = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYWxsb2MARgtsbGh0dHBfZnJlZQANBGZyZWUASA9sbGh0dHBfZ2V0X3R5cGUADhVsbGh0dHBfZ2V0X2h0dHBfbWFqb3IADxVsbGh0dHBfZ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ewEBfwJAIAAoAgwiAw0AAkAgACgCBEUNACAAIAE2AgQLAkAgACABIAIQxICAgAAiAw0AIAAoAgwPCyAAIAM2AhxBACEDIAAoAgQiAUUNACAAIAEgAiAAKAIIEYGAgIAAACIBRQ0AIAAgAjYCFCAAIAE2AgwgASEDCyADC+TzAQMOfwN+BH8jgICAgABBEGsiAySAgICAACABIQQgASEFIAEhBiABIQcgASEIIAEhCSABIQogASELIAEhDCABIQ0gASEOIAEhDwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAKAIcIhBBf2oO3QHaAQHZAQIDBAUGBwgJCgsMDQ7YAQ8Q1wEREtYBExQVFhcYGRob4AHfARwdHtUBHyAhIiMkJdQBJicoKSorLNMB0gEtLtEB0AEvMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUbbAUdISUrPAc4BS80BTMwBTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5ent8fX5/gAGBAYIBgwGEAYUBhgGHAYgBiQGKAY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ASEQDA4LQbYBIRAMDQtBtwEhEAwMC0G4ASEQDAsLQbkBIRAMCgtBugEhEAwJC0G7ASEQDAgLQcYBIRAMBwtBvAEhEAwGC0G9ASEQDAULQb4BIRAMBAtBvwEhEAwDC0HAASEQDAILQcIBIRAMAQtBwQEhEAsDQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJA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IgEgAhC0gICAACIQDecBIAEhAQz1AgsCQCABIgEgAkcNAEEGIRAM8AMLIAAgAUEBaiIBIAIQu4CAgAAiEA3oASABIQEMMQsgAEIANwMgQRIhEAzVAwsgASIQIAJHDStBHSEQDO0DCwJAIAEiASACRg0AIAFBAWohAUEQIRAM1AMLQQchEAzsAwsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3lAUEIIRAM6wMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQRQhEAzSAwtBCSEQDOoDCyABIQEgACkDIFAN5AEgASEBDPICCwJAIAEiASACRw0AQQshEAzpAwsgACABQQFqIgEgAhC2gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeYBIAEhAQwNCyAAIAEiASACELqAgIAAIhAN5wEgASEBDPACCwJAIAEiASACRw0AQQ8hEAzlAwsgAS0AACIQQTtGDQggEEENRw3oASABQQFqIQEM7wILIAAgASIBIAIQuoCAgAAiEA3oASABIQEM8gILA0ACQCABLQAAQfC1gIAAai0AACIQQQFGDQAgEEECRw3rASAAKAIEIRAgAEEANgIEIAAgECABQQFqIgEQuYCAgAAiEA3qASABIQEM9AILIAFBAWoiASACRw0AC0ESIRAM4gMLIAAgASIBIAIQuoCAgAAiEA3pASABIQEMCgsgASIBIAJHDQZBGyEQDOADCwJAIAEiASACRw0AQRYhEAzgAwsgAEGKgICAADYCCCAAIAE2AgQgACABIAIQuICAgAAiEA3qASABIQFBICEQDMYDCwJAIAEiASACRg0AA0ACQCABLQAAQfC3gIAAai0AACIQQQJGDQACQCAQQX9qDgTlAewBAOsB7AELIAFBAWohAUEIIRAMyAMLIAFBAWoiASACRw0AC0EVIRAM3wMLQRUhEAzeAwsDQAJAIAEtAABB8LmAgABqLQAAIhBBAkYNACAQQX9qDgTeAewB4AHrAewBCyABQQFqIgEgAkcNAAtBGCEQDN0DCwJAIAEiASACRg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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAgAAAAACAAAAAAAAAAAAAAAAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw=='; + return llhttp_simdWasm; + } + + /* global WebAssembly */ + + const assert$5 = require$$3$1; + const net = require$$1$3; + const http = require$$17; + const { pipeline: pipeline$1 } = require$$0$1; + const util$g = util$l; + const timers = timers$1; + const Request = request$2; + const DispatcherBase$3 = dispatcherBase; + const { + RequestContentLengthMismatchError, + ResponseContentLengthMismatchError, + InvalidArgumentError: InvalidArgumentError$g, + RequestAbortedError: RequestAbortedError$8, + HeadersTimeoutError, + HeadersOverflowError, + SocketError: SocketError$2, + InformationalError, + BodyTimeoutError, + HTTPParserError, + ResponseExceededMaxSizeError, + ClientDestroyedError + } = errors$1; + const buildConnector$3 = connect$2; + const { + kUrl: kUrl$3, + kReset, + kServerName, + kClient: kClient$1, + kBusy: kBusy$1, + kParser, + kConnect, + kBlocking, + kResuming, + kRunning: kRunning$3, + kPending: kPending$2, + kSize: kSize$4, + kWriting, + kQueue: kQueue$1, + kConnected: kConnected$5, + kConnecting, + kNeedDrain: kNeedDrain$3, + kNoRef, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kSocket, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kConnector, + kMaxRedirections: kMaxRedirections$1, + kMaxRequests, + kCounter, + kClose: kClose$5, + kDestroy: kDestroy$3, + kDispatch: kDispatch$2, + kInterceptors: kInterceptors$4, + kLocalAddress, + kMaxResponseSize, + kHTTPConnVersion, + // HTTP2 + kHost, + kHTTP2Session, + kHTTP2SessionState, + kHTTP2BuildRequest, + kHTTP2CopyHeaders, + kHTTP1BuildRequest + } = symbols$4; + + /** @type {import('http2')} */ + let http2; + try { + http2 = require$$11; + } catch { + // @ts-ignore + http2 = { constants: {} }; + } + + const { + constants: { + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_SCHEME, + HTTP2_HEADER_CONTENT_LENGTH, + HTTP2_HEADER_EXPECT, + HTTP2_HEADER_STATUS + } + } = http2; + + // Experimental + let h2ExperimentalWarned = false; + + const FastBuffer = Buffer[Symbol.species]; + + const kClosedResolve$1 = Symbol('kClosedResolve'); + + const channels = {}; + + try { + const diagnosticsChannel = require$$1$2; + channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders'); + channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect'); + channels.connectError = diagnosticsChannel.channel('undici:client:connectError'); + channels.connected = diagnosticsChannel.channel('undici:client:connected'); + } catch { + channels.sendHeaders = { hasSubscribers: false }; + channels.beforeConnect = { hasSubscribers: false }; + channels.connectError = { hasSubscribers: false }; + channels.connected = { hasSubscribers: false }; + } + + /** + * @type {import('../types/client').default} + */ + let Client$4 = class Client extends DispatcherBase$3 { + /** + * + * @param {string|URL} url + * @param {import('../types/client').Client.Options} options + */ + constructor (url, { + interceptors, + maxHeaderSize, + headersTimeout, + socketTimeout, + requestTimeout, + connectTimeout, + bodyTimeout, + idleTimeout, + keepAlive, + keepAliveTimeout, + maxKeepAliveTimeout, + keepAliveMaxTimeout, + keepAliveTimeoutThreshold, + socketPath, + pipelining, + tls, + strictContentLength, + maxCachedSessions, + maxRedirections, + connect, + maxRequestsPerClient, + localAddress, + maxResponseSize, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + // h2 + allowH2, + maxConcurrentStreams + } = {}) { + super(); + + if (keepAlive !== undefined) { + throw new InvalidArgumentError$g('unsupported keepAlive, use pipelining=0 instead') + } + + if (socketTimeout !== undefined) { + throw new InvalidArgumentError$g('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') + } + + if (requestTimeout !== undefined) { + throw new InvalidArgumentError$g('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') + } + + if (idleTimeout !== undefined) { + throw new InvalidArgumentError$g('unsupported idleTimeout, use keepAliveTimeout instead') + } + + if (maxKeepAliveTimeout !== undefined) { + throw new InvalidArgumentError$g('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') + } + + if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { + throw new InvalidArgumentError$g('invalid maxHeaderSize') + } + + if (socketPath != null && typeof socketPath !== 'string') { + throw new InvalidArgumentError$g('invalid socketPath') + } + + if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { + throw new InvalidArgumentError$g('invalid connectTimeout') + } + + if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { + throw new InvalidArgumentError$g('invalid keepAliveTimeout') + } + + if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { + throw new InvalidArgumentError$g('invalid keepAliveMaxTimeout') + } + + if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { + throw new InvalidArgumentError$g('invalid keepAliveTimeoutThreshold') + } + + if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError$g('headersTimeout must be a positive integer or zero') + } + + if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError$g('bodyTimeout must be a positive integer or zero') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError$g('connect must be a function or an object') + } + + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError$g('maxRedirections must be a positive number') + } + + if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { + throw new InvalidArgumentError$g('maxRequestsPerClient must be a positive number') + } + + if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { + throw new InvalidArgumentError$g('localAddress must be valid string IP address') + } + + if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { + throw new InvalidArgumentError$g('maxResponseSize must be a positive number') + } + + if ( + autoSelectFamilyAttemptTimeout != null && + (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) + ) { + throw new InvalidArgumentError$g('autoSelectFamilyAttemptTimeout must be a positive number') + } + + // h2 + if (allowH2 != null && typeof allowH2 !== 'boolean') { + throw new InvalidArgumentError$g('allowH2 must be a valid boolean value') + } + + if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { + throw new InvalidArgumentError$g('maxConcurrentStreams must be a possitive integer, greater than 0') + } + + if (typeof connect !== 'function') { + connect = buildConnector$3({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(util$g.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }); + } + + this[kInterceptors$4] = interceptors && interceptors.Client && Array.isArray(interceptors.Client) + ? interceptors.Client + : [createRedirectInterceptor$2({ maxRedirections })]; + this[kUrl$3] = util$g.parseOrigin(url); + this[kConnector] = connect; + this[kSocket] = null; + this[kPipelining] = pipelining != null ? pipelining : 1; + this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize; + this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout; + this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout; + this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold; + this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout]; + this[kServerName] = null; + this[kLocalAddress] = localAddress != null ? localAddress : null; + this[kResuming] = 0; // 0, idle, 1, scheduled, 2 resuming + this[kNeedDrain$3] = 0; // 0, idle, 1, scheduled, 2 resuming + this[kHostHeader] = `host: ${this[kUrl$3].hostname}${this[kUrl$3].port ? `:${this[kUrl$3].port}` : ''}\r\n`; + this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3; + this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3; + this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength; + this[kMaxRedirections$1] = maxRedirections; + this[kMaxRequests] = maxRequestsPerClient; + this[kClosedResolve$1] = null; + this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1; + this[kHTTPConnVersion] = 'h1'; + + // HTTP/2 + this[kHTTP2Session] = null; + this[kHTTP2SessionState] = !allowH2 + ? null + : { + // streams: null, // Fixed queue of streams - For future support of `push` + openStreams: 0, // Keep track of them to decide wether or not unref the session + maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server + }; + this[kHost] = `${this[kUrl$3].hostname}${this[kUrl$3].port ? `:${this[kUrl$3].port}` : ''}`; + + // kQueue is built up of 3 sections separated by + // the kRunningIdx and kPendingIdx indices. + // | complete | running | pending | + // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length + // kRunningIdx points to the first running element. + // kPendingIdx points to the first pending element. + // This implements a fast queue with an amortized + // time of O(1). + + this[kQueue$1] = []; + this[kRunningIdx] = 0; + this[kPendingIdx] = 0; + } + + get pipelining () { + return this[kPipelining] + } + + set pipelining (value) { + this[kPipelining] = value; + resume(this, true); + } + + get [kPending$2] () { + return this[kQueue$1].length - this[kPendingIdx] + } + + get [kRunning$3] () { + return this[kPendingIdx] - this[kRunningIdx] + } + + get [kSize$4] () { + return this[kQueue$1].length - this[kRunningIdx] + } + + get [kConnected$5] () { + return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed + } + + get [kBusy$1] () { + const socket = this[kSocket]; + return ( + (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) || + (this[kSize$4] >= (this[kPipelining] || 1)) || + this[kPending$2] > 0 + ) + } + + /* istanbul ignore: only used for test */ + [kConnect] (cb) { + connect$1(this); + this.once('connect', cb); + } + + [kDispatch$2] (opts, handler) { + const origin = opts.origin || this[kUrl$3].origin; + + const request = this[kHTTPConnVersion] === 'h2' + ? Request[kHTTP2BuildRequest](origin, opts, handler) + : Request[kHTTP1BuildRequest](origin, opts, handler); + + this[kQueue$1].push(request); + if (this[kResuming]) ; else if (util$g.bodyLength(request.body) == null && util$g.isIterable(request.body)) { + // Wait a tick in case stream/iterator is ended in the same tick. + this[kResuming] = 1; + browser$1$1.nextTick(resume, this); + } else { + resume(this, true); + } + + if (this[kResuming] && this[kNeedDrain$3] !== 2 && this[kBusy$1]) { + this[kNeedDrain$3] = 2; + } + + return this[kNeedDrain$3] < 2 + } + + async [kClose$5] () { + // TODO: for H2 we need to gracefully flush the remaining enqueued + // request and close each stream. + return new Promise((resolve) => { + if (!this[kSize$4]) { + resolve(null); + } else { + this[kClosedResolve$1] = resolve; + } + }) + } + + async [kDestroy$3] (err) { + return new Promise((resolve) => { + const requests = this[kQueue$1].splice(this[kPendingIdx]); + for (let i = 0; i < requests.length; i++) { + const request = requests[i]; + errorRequest(this, request, err); + } + + const callback = () => { + if (this[kClosedResolve$1]) { + // TODO (fix): Should we error here with ClientDestroyedError? + this[kClosedResolve$1](); + this[kClosedResolve$1] = null; + } + resolve(); + }; + + if (this[kHTTP2Session] != null) { + util$g.destroy(this[kHTTP2Session], err); + this[kHTTP2Session] = null; + this[kHTTP2SessionState] = null; + } + + if (!this[kSocket]) { + queueMicrotask(callback); + } else { + util$g.destroy(this[kSocket].on('close', callback), err); + } + + resume(this); + }) + } + }; + + function onHttp2SessionError (err) { + assert$5(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID'); + + this[kSocket][kError] = err; + + onError(this[kClient$1], err); + } + + function onHttp2FrameError (type, code, id) { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`); + + if (id === 0) { + this[kSocket][kError] = err; + onError(this[kClient$1], err); + } + } + + function onHttp2SessionEnd () { + util$g.destroy(this, new SocketError$2('other side closed')); + util$g.destroy(this[kSocket], new SocketError$2('other side closed')); + } + + function onHTTP2GoAway (code) { + const client = this[kClient$1]; + const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`); + client[kSocket] = null; + client[kHTTP2Session] = null; + + if (client.destroyed) { + assert$5(this[kPending$2] === 0); + + // Fail entire queue. + const requests = client[kQueue$1].splice(client[kRunningIdx]); + for (let i = 0; i < requests.length; i++) { + const request = requests[i]; + errorRequest(this, request, err); + } + } else if (client[kRunning$3] > 0) { + // Fail head of pipeline. + const request = client[kQueue$1][client[kRunningIdx]]; + client[kQueue$1][client[kRunningIdx]++] = null; + + errorRequest(client, request, err); + } + + client[kPendingIdx] = client[kRunningIdx]; + + assert$5(client[kRunning$3] === 0); + + client.emit('disconnect', + client[kUrl$3], + [client], + err + ); + + resume(client); + } + + const constants$2 = requireConstants$2(); + const createRedirectInterceptor$2 = redirectInterceptor; + const EMPTY_BUF = Buffer.alloc(0); + + async function lazyllhttp () { + const llhttpWasmData = browser$1$1.env.JEST_WORKER_ID ? requireLlhttpWasm() : undefined; + + let mod; + try { + mod = await WebAssembly.compile(Buffer.from(requireLlhttp_simdWasm(), 'base64')); + } catch (e) { + /* istanbul ignore next */ + + // We could check if the error was caused by the simd option not + // being enabled, but the occurring of this other error + // * https://github.com/emscripten-core/emscripten/issues/11495 + // got me to remove that check to avoid breaking Node 12. + mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || requireLlhttpWasm(), 'base64')); + } + + return await WebAssembly.instantiate(mod, { + env: { + /* eslint-disable camelcase */ + + wasm_on_url: (p, at, len) => { + /* istanbul ignore next */ + return 0 + }, + wasm_on_status: (p, at, len) => { + assert$5.strictEqual(currentParser.ptr, p); + const start = at - currentBufferPtr + currentBufferRef.byteOffset; + return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_begin: (p) => { + assert$5.strictEqual(currentParser.ptr, p); + return currentParser.onMessageBegin() || 0 + }, + wasm_on_header_field: (p, at, len) => { + assert$5.strictEqual(currentParser.ptr, p); + const start = at - currentBufferPtr + currentBufferRef.byteOffset; + return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_header_value: (p, at, len) => { + assert$5.strictEqual(currentParser.ptr, p); + const start = at - currentBufferPtr + currentBufferRef.byteOffset; + return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { + assert$5.strictEqual(currentParser.ptr, p); + return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0 + }, + wasm_on_body: (p, at, len) => { + assert$5.strictEqual(currentParser.ptr, p); + const start = at - currentBufferPtr + currentBufferRef.byteOffset; + return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_complete: (p) => { + assert$5.strictEqual(currentParser.ptr, p); + return currentParser.onMessageComplete() || 0 + } + + /* eslint-enable camelcase */ + } + }) + } + + let llhttpInstance = null; + let llhttpPromise = lazyllhttp(); + llhttpPromise.catch(); + + let currentParser = null; + let currentBufferRef = null; + let currentBufferSize = 0; + let currentBufferPtr = null; + + const TIMEOUT_HEADERS = 1; + const TIMEOUT_BODY = 2; + const TIMEOUT_IDLE = 3; + + class Parser { + constructor (client, socket, { exports }) { + assert$5(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0); + + this.llhttp = exports; + this.ptr = this.llhttp.llhttp_alloc(constants$2.TYPE.RESPONSE); + this.client = client; + this.socket = socket; + this.timeout = null; + this.timeoutValue = null; + this.timeoutType = null; + this.statusCode = null; + this.statusText = ''; + this.upgrade = false; + this.headers = []; + this.headersSize = 0; + this.headersMaxSize = client[kMaxHeadersSize]; + this.shouldKeepAlive = false; + this.paused = false; + this.resume = this.resume.bind(this); + + this.bytesRead = 0; + + this.keepAlive = ''; + this.contentLength = ''; + this.connection = ''; + this.maxResponseSize = client[kMaxResponseSize]; + } + + setTimeout (value, type) { + this.timeoutType = type; + if (value !== this.timeoutValue) { + timers.clearTimeout(this.timeout); + if (value) { + this.timeout = timers.setTimeout(onParserTimeout, value, this); + // istanbul ignore else: only for jest + if (this.timeout.unref) { + this.timeout.unref(); + } + } else { + this.timeout = null; + } + this.timeoutValue = value; + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh(); + } + } + } + + resume () { + if (this.socket.destroyed || !this.paused) { + return + } + + assert$5(this.ptr != null); + assert$5(currentParser == null); + + this.llhttp.llhttp_resume(this.ptr); + + assert$5(this.timeoutType === TIMEOUT_BODY); + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh(); + } + } + + this.paused = false; + this.execute(this.socket.read() || EMPTY_BUF); // Flush parser. + this.readMore(); + } + + readMore () { + while (!this.paused && this.ptr) { + const chunk = this.socket.read(); + if (chunk === null) { + break + } + this.execute(chunk); + } + } + + execute (data) { + assert$5(this.ptr != null); + assert$5(currentParser == null); + assert$5(!this.paused); + + const { socket, llhttp } = this; + + if (data.length > currentBufferSize) { + if (currentBufferPtr) { + llhttp.free(currentBufferPtr); + } + currentBufferSize = Math.ceil(data.length / 4096) * 4096; + currentBufferPtr = llhttp.malloc(currentBufferSize); + } + + new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data); + + // Call `execute` on the wasm parser. + // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, + // and finally the length of bytes to parse. + // The return value is an error code or `constants.ERROR.OK`. + try { + let ret; + + try { + currentBufferRef = data; + currentParser = this; + ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length); + /* eslint-disable-next-line no-useless-catch */ + } catch (err) { + /* istanbul ignore next: difficult to make a test case for */ + throw err + } finally { + currentParser = null; + currentBufferRef = null; + } + + const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr; + + if (ret === constants$2.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)); + } else if (ret === constants$2.ERROR.PAUSED) { + this.paused = true; + socket.unshift(data.slice(offset)); + } else if (ret !== constants$2.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr); + let message = ''; + /* istanbul ignore else: difficult to make a test case for */ + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0); + message = + 'Response does not match the HTTP/1.1 protocol (' + + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + + ')'; + } + throw new HTTPParserError(message, constants$2.ERROR[ret], data.slice(offset)) + } + } catch (err) { + util$g.destroy(socket, err); + } + } + + destroy () { + assert$5(this.ptr != null); + assert$5(currentParser == null); + + this.llhttp.llhttp_free(this.ptr); + this.ptr = null; + + timers.clearTimeout(this.timeout); + this.timeout = null; + this.timeoutValue = null; + this.timeoutType = null; + + this.paused = false; + } + + onStatus (buf) { + this.statusText = buf.toString(); + } + + onMessageBegin () { + const { socket, client } = this; + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue$1][client[kRunningIdx]]; + if (!request) { + return -1 + } + } + + onHeaderField (buf) { + const len = this.headers.length; + + if ((len & 1) === 0) { + this.headers.push(buf); + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]); + } + + this.trackHeader(buf.length); + } + + onHeaderValue (buf) { + let len = this.headers.length; + + if ((len & 1) === 1) { + this.headers.push(buf); + len += 1; + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]); + } + + const key = this.headers[len - 2]; + if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') { + this.keepAlive += buf.toString(); + } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') { + this.connection += buf.toString(); + } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') { + this.contentLength += buf.toString(); + } + + this.trackHeader(buf.length); + } + + trackHeader (len) { + this.headersSize += len; + if (this.headersSize >= this.headersMaxSize) { + util$g.destroy(this.socket, new HeadersOverflowError()); + } + } + + onUpgrade (head) { + const { upgrade, client, socket, headers, statusCode } = this; + + assert$5(upgrade); + + const request = client[kQueue$1][client[kRunningIdx]]; + assert$5(request); + + assert$5(!socket.destroyed); + assert$5(socket === client[kSocket]); + assert$5(!this.paused); + assert$5(request.upgrade || request.method === 'CONNECT'); + + this.statusCode = null; + this.statusText = ''; + this.shouldKeepAlive = null; + + assert$5(this.headers.length % 2 === 0); + this.headers = []; + this.headersSize = 0; + + socket.unshift(head); + + socket[kParser].destroy(); + socket[kParser] = null; + + socket[kClient$1] = null; + socket[kError] = null; + socket + .removeListener('error', onSocketError) + .removeListener('readable', onSocketReadable) + .removeListener('end', onSocketEnd) + .removeListener('close', onSocketClose); + + client[kSocket] = null; + client[kQueue$1][client[kRunningIdx]++] = null; + client.emit('disconnect', client[kUrl$3], [client], new InformationalError('upgrade')); + + try { + request.onUpgrade(statusCode, headers, socket); + } catch (err) { + util$g.destroy(socket, err); + } + + resume(client); + } + + onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { + const { client, socket, headers, statusText } = this; + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue$1][client[kRunningIdx]]; + + /* istanbul ignore next: difficult to make a test case for */ + if (!request) { + return -1 + } + + assert$5(!this.upgrade); + assert$5(this.statusCode < 200); + + if (statusCode === 100) { + util$g.destroy(socket, new SocketError$2('bad response', util$g.getSocketInfo(socket))); + return -1 + } + + /* this can only happen if server is misbehaving */ + if (upgrade && !request.upgrade) { + util$g.destroy(socket, new SocketError$2('bad upgrade', util$g.getSocketInfo(socket))); + return -1 + } + + assert$5.strictEqual(this.timeoutType, TIMEOUT_HEADERS); + + this.statusCode = statusCode; + this.shouldKeepAlive = ( + shouldKeepAlive || + // Override llhttp value which does not allow keepAlive for HEAD. + (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') + ); + + if (this.statusCode >= 200) { + const bodyTimeout = request.bodyTimeout != null + ? request.bodyTimeout + : client[kBodyTimeout]; + this.setTimeout(bodyTimeout, TIMEOUT_BODY); + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh(); + } + } + + if (request.method === 'CONNECT') { + assert$5(client[kRunning$3] === 1); + this.upgrade = true; + return 2 + } + + if (upgrade) { + assert$5(client[kRunning$3] === 1); + this.upgrade = true; + return 2 + } + + assert$5(this.headers.length % 2 === 0); + this.headers = []; + this.headersSize = 0; + + if (this.shouldKeepAlive && client[kPipelining]) { + const keepAliveTimeout = this.keepAlive ? util$g.parseKeepAliveTimeout(this.keepAlive) : null; + + if (keepAliveTimeout != null) { + const timeout = Math.min( + keepAliveTimeout - client[kKeepAliveTimeoutThreshold], + client[kKeepAliveMaxTimeout] + ); + if (timeout <= 0) { + socket[kReset] = true; + } else { + client[kKeepAliveTimeoutValue] = timeout; + } + } else { + client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout]; + } + } else { + // Stop more requests from being dispatched. + socket[kReset] = true; + } + + let pause; + try { + pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false; + } catch (err) { + util$g.destroy(socket, err); + return -1 + } + + if (request.method === 'HEAD') { + return 1 + } + + if (statusCode < 200) { + return 1 + } + + if (socket[kBlocking]) { + socket[kBlocking] = false; + resume(client); + } + + return pause ? constants$2.ERROR.PAUSED : 0 + } + + onBody (buf) { + const { client, socket, statusCode, maxResponseSize } = this; + + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue$1][client[kRunningIdx]]; + assert$5(request); + + assert$5.strictEqual(this.timeoutType, TIMEOUT_BODY); + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh(); + } + } + + assert$5(statusCode >= 200); + + if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { + util$g.destroy(socket, new ResponseExceededMaxSizeError()); + return -1 + } + + this.bytesRead += buf.length; + + try { + if (request.onData(buf) === false) { + return constants$2.ERROR.PAUSED + } + } catch (err) { + util$g.destroy(socket, err); + return -1 + } + } + + onMessageComplete () { + const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this; + + if (socket.destroyed && (!statusCode || shouldKeepAlive)) { + return -1 + } + + if (upgrade) { + return + } + + const request = client[kQueue$1][client[kRunningIdx]]; + assert$5(request); + + assert$5(statusCode >= 100); + + this.statusCode = null; + this.statusText = ''; + this.bytesRead = 0; + this.contentLength = ''; + this.keepAlive = ''; + this.connection = ''; + + assert$5(this.headers.length % 2 === 0); + this.headers = []; + this.headersSize = 0; + + if (statusCode < 200) { + return + } + + /* istanbul ignore next: should be handled by llhttp? */ + if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { + util$g.destroy(socket, new ResponseContentLengthMismatchError()); + return -1 + } + + try { + request.onComplete(headers); + } catch (err) { + errorRequest(client, request, err); + } + + client[kQueue$1][client[kRunningIdx]++] = null; + + if (socket[kWriting]) { + assert$5.strictEqual(client[kRunning$3], 0); + // Response completed before request. + util$g.destroy(socket, new InformationalError('reset')); + return constants$2.ERROR.PAUSED + } else if (!shouldKeepAlive) { + util$g.destroy(socket, new InformationalError('reset')); + return constants$2.ERROR.PAUSED + } else if (socket[kReset] && client[kRunning$3] === 0) { + // Destroy socket once all requests have completed. + // The request at the tail of the pipeline is the one + // that requested reset and no further requests should + // have been queued since then. + util$g.destroy(socket, new InformationalError('reset')); + return constants$2.ERROR.PAUSED + } else if (client[kPipelining] === 1) { + // We must wait a full event loop cycle to reuse this socket to make sure + // that non-spec compliant servers are not closing the connection even if they + // said they won't. + setImmediate(resume, client); + } else { + resume(client); + } + } + } + + function onParserTimeout (parser) { + const { socket, timeoutType, client } = parser; + + /* istanbul ignore else */ + if (timeoutType === TIMEOUT_HEADERS) { + if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning$3] > 1) { + assert$5(!parser.paused, 'cannot be paused while waiting for headers'); + util$g.destroy(socket, new HeadersTimeoutError()); + } + } else if (timeoutType === TIMEOUT_BODY) { + if (!parser.paused) { + util$g.destroy(socket, new BodyTimeoutError()); + } + } else if (timeoutType === TIMEOUT_IDLE) { + assert$5(client[kRunning$3] === 0 && client[kKeepAliveTimeoutValue]); + util$g.destroy(socket, new InformationalError('socket idle timeout')); + } + } + + function onSocketReadable () { + const { [kParser]: parser } = this; + if (parser) { + parser.readMore(); + } + } + + function onSocketError (err) { + const { [kClient$1]: client, [kParser]: parser } = this; + + assert$5(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID'); + + if (client[kHTTPConnVersion] !== 'h2') { + // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded + // to the user. + if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so for as a valid response. + parser.onMessageComplete(); + return + } + } + + this[kError] = err; + + onError(this[kClient$1], err); + } + + function onError (client, err) { + if ( + client[kRunning$3] === 0 && + err.code !== 'UND_ERR_INFO' && + err.code !== 'UND_ERR_SOCKET' + ) { + // Error is not caused by running request and not a recoverable + // socket error. + + assert$5(client[kPendingIdx] === client[kRunningIdx]); + + const requests = client[kQueue$1].splice(client[kRunningIdx]); + for (let i = 0; i < requests.length; i++) { + const request = requests[i]; + errorRequest(client, request, err); + } + assert$5(client[kSize$4] === 0); + } + } + + function onSocketEnd () { + const { [kParser]: parser, [kClient$1]: client } = this; + + if (client[kHTTPConnVersion] !== 'h2') { + if (parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete(); + return + } + } + + util$g.destroy(this, new SocketError$2('other side closed', util$g.getSocketInfo(this))); + } + + function onSocketClose () { + const { [kClient$1]: client, [kParser]: parser } = this; + + if (client[kHTTPConnVersion] === 'h1' && parser) { + if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete(); + } + + this[kParser].destroy(); + this[kParser] = null; + } + + const err = this[kError] || new SocketError$2('closed', util$g.getSocketInfo(this)); + + client[kSocket] = null; + + if (client.destroyed) { + assert$5(client[kPending$2] === 0); + + // Fail entire queue. + const requests = client[kQueue$1].splice(client[kRunningIdx]); + for (let i = 0; i < requests.length; i++) { + const request = requests[i]; + errorRequest(client, request, err); + } + } else if (client[kRunning$3] > 0 && err.code !== 'UND_ERR_INFO') { + // Fail head of pipeline. + const request = client[kQueue$1][client[kRunningIdx]]; + client[kQueue$1][client[kRunningIdx]++] = null; + + errorRequest(client, request, err); + } + + client[kPendingIdx] = client[kRunningIdx]; + + assert$5(client[kRunning$3] === 0); + + client.emit('disconnect', client[kUrl$3], [client], err); + + resume(client); + } + + async function connect$1 (client) { + assert$5(!client[kConnecting]); + assert$5(!client[kSocket]); + + let { host, hostname, protocol, port } = client[kUrl$3]; + + // Resolve ipv6 + if (hostname[0] === '[') { + const idx = hostname.indexOf(']'); + + assert$5(idx !== -1); + const ip = hostname.substr(1, idx - 1); + + assert$5(net.isIP(ip)); + hostname = ip; + } + + client[kConnecting] = true; + + if (channels.beforeConnect.hasSubscribers) { + channels.beforeConnect.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector] + }); + } + + try { + const socket = await new Promise((resolve, reject) => { + client[kConnector]({ + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, (err, socket) => { + if (err) { + reject(err); + } else { + resolve(socket); + } + }); + }); + + if (client.destroyed) { + util$g.destroy(socket.on('error', () => {}), new ClientDestroyedError()); + return + } + + client[kConnecting] = false; + + assert$5(socket); + + const isH2 = socket.alpnProtocol === 'h2'; + if (isH2) { + if (!h2ExperimentalWarned) { + h2ExperimentalWarned = true; + browser$1$1.emitWarning('H2 support is experimental, expect them to change at any time.', { + code: 'UNDICI-H2' + }); + } + + const session = http2.connect(client[kUrl$3], { + createConnection: () => socket, + peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams + }); + + client[kHTTPConnVersion] = 'h2'; + session[kClient$1] = client; + session[kSocket] = socket; + session.on('error', onHttp2SessionError); + session.on('frameError', onHttp2FrameError); + session.on('end', onHttp2SessionEnd); + session.on('goaway', onHTTP2GoAway); + session.on('close', onSocketClose); + session.unref(); + + client[kHTTP2Session] = session; + socket[kHTTP2Session] = session; + } else { + if (!llhttpInstance) { + llhttpInstance = await llhttpPromise; + llhttpPromise = null; + } + + socket[kNoRef] = false; + socket[kWriting] = false; + socket[kReset] = false; + socket[kBlocking] = false; + socket[kParser] = new Parser(client, socket, llhttpInstance); + } + + socket[kCounter] = 0; + socket[kMaxRequests] = client[kMaxRequests]; + socket[kClient$1] = client; + socket[kError] = null; + + socket + .on('error', onSocketError) + .on('readable', onSocketReadable) + .on('end', onSocketEnd) + .on('close', onSocketClose); + + client[kSocket] = socket; + + if (channels.connected.hasSubscribers) { + channels.connected.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + socket + }); + } + client.emit('connect', client[kUrl$3], [client]); + } catch (err) { + if (client.destroyed) { + return + } + + client[kConnecting] = false; + + if (channels.connectError.hasSubscribers) { + channels.connectError.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + error: err + }); + } + + if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + assert$5(client[kRunning$3] === 0); + while (client[kPending$2] > 0 && client[kQueue$1][client[kPendingIdx]].servername === client[kServerName]) { + const request = client[kQueue$1][client[kPendingIdx]++]; + errorRequest(client, request, err); + } + } else { + onError(client, err); + } + + client.emit('connectionError', client[kUrl$3], [client], err); + } + + resume(client); + } + + function emitDrain (client) { + client[kNeedDrain$3] = 0; + client.emit('drain', client[kUrl$3], [client]); + } + + function resume (client, sync) { + if (client[kResuming] === 2) { + return + } + + client[kResuming] = 2; + + _resume(client, sync); + client[kResuming] = 0; + + if (client[kRunningIdx] > 256) { + client[kQueue$1].splice(0, client[kRunningIdx]); + client[kPendingIdx] -= client[kRunningIdx]; + client[kRunningIdx] = 0; + } + } + + function _resume (client, sync) { + while (true) { + if (client.destroyed) { + assert$5(client[kPending$2] === 0); + return + } + + if (client[kClosedResolve$1] && !client[kSize$4]) { + client[kClosedResolve$1](); + client[kClosedResolve$1] = null; + return + } + + const socket = client[kSocket]; + + if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') { + if (client[kSize$4] === 0) { + if (!socket[kNoRef] && socket.unref) { + socket.unref(); + socket[kNoRef] = true; + } + } else if (socket[kNoRef] && socket.ref) { + socket.ref(); + socket[kNoRef] = false; + } + + if (client[kSize$4] === 0) { + if (socket[kParser].timeoutType !== TIMEOUT_IDLE) { + socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE); + } + } else if (client[kRunning$3] > 0 && socket[kParser].statusCode < 200) { + if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { + const request = client[kQueue$1][client[kRunningIdx]]; + const headersTimeout = request.headersTimeout != null + ? request.headersTimeout + : client[kHeadersTimeout]; + socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS); + } + } + } + + if (client[kBusy$1]) { + client[kNeedDrain$3] = 2; + } else if (client[kNeedDrain$3] === 2) { + if (sync) { + client[kNeedDrain$3] = 1; + browser$1$1.nextTick(emitDrain, client); + } else { + emitDrain(client); + } + continue + } + + if (client[kPending$2] === 0) { + return + } + + if (client[kRunning$3] >= (client[kPipelining] || 1)) { + return + } + + const request = client[kQueue$1][client[kPendingIdx]]; + + if (client[kUrl$3].protocol === 'https:' && client[kServerName] !== request.servername) { + if (client[kRunning$3] > 0) { + return + } + + client[kServerName] = request.servername; + + if (socket && socket.servername !== request.servername) { + util$g.destroy(socket, new InformationalError('servername changed')); + return + } + } + + if (client[kConnecting]) { + return + } + + if (!socket && !client[kHTTP2Session]) { + connect$1(client); + return + } + + if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { + return + } + + if (client[kRunning$3] > 0 && !request.idempotent) { + // Non-idempotent request cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } + + if (client[kRunning$3] > 0 && (request.upgrade || request.method === 'CONNECT')) { + // Don't dispatch an upgrade until all preceding requests have completed. + // A misbehaving server might upgrade the connection before all pipelined + // request has completed. + return + } + + if (util$g.isStream(request.body) && util$g.bodyLength(request.body) === 0) { + request.body + .on('data', /* istanbul ignore next */ function () { + /* istanbul ignore next */ + assert$5(false); + }) + .on('error', function (err) { + errorRequest(client, request, err); + }) + .on('end', function () { + util$g.destroy(this); + }); + + request.body = null; + } + + if (client[kRunning$3] > 0 && + (util$g.isStream(request.body) || util$g.isAsyncIterable(request.body))) { + // Request with stream or iterator body can error while other requests + // are inflight and indirectly error those as well. + // Ensure this doesn't happen by waiting for inflight + // to complete before dispatching. + + // Request with stream or iterator body cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } + + if (!request.aborted && write(client, request)) { + client[kPendingIdx]++; + } else { + client[kQueue$1].splice(client[kPendingIdx], 1); + } + } + } + + function write (client, request) { + if (client[kHTTPConnVersion] === 'h2') { + writeH2(client, client[kHTTP2Session], request); + return + } + + const { body, method, path, host, upgrade, headers, blocking, reset } = request; + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ); + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0); + } + + let contentLength = util$g.bodyLength(body); + + if (contentLength === null) { + contentLength = request.contentLength; + } + + if (contentLength === 0 && !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null; + } + + if (request.contentLength !== null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + errorRequest(client, request, new RequestContentLengthMismatchError()); + return false + } + + browser$1$1.emitWarning(new RequestContentLengthMismatchError()); + } + + const socket = client[kSocket]; + + try { + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } + + errorRequest(client, request, err || new RequestAbortedError$8()); + + util$g.destroy(socket, new InformationalError('aborted')); + }); + } catch (err) { + errorRequest(client, request, err); + } + + if (request.aborted) { + return false + } + + if (method === 'HEAD') { + // https://github.com/mcollina/undici/issues/258 + // Close after a HEAD request to interop with misbehaving servers + // that may send a body in the response. + + socket[kReset] = true; + } + + if (upgrade || method === 'CONNECT') { + // On CONNECT or upgrade, block pipeline from dispatching further + // requests on this connection. + + socket[kReset] = true; + } + + if (reset != null) { + socket[kReset] = reset; + } + + if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { + socket[kReset] = true; + } + + if (blocking) { + socket[kBlocking] = true; + } + + let header = `${method} ${path} HTTP/1.1\r\n`; + + if (typeof host === 'string') { + header += `host: ${host}\r\n`; + } else { + header += client[kHostHeader]; + } + + if (upgrade) { + header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n`; + } else if (client[kPipelining] && !socket[kReset]) { + header += 'connection: keep-alive\r\n'; + } else { + header += 'connection: close\r\n'; + } + + if (headers) { + header += headers; + } + + if (channels.sendHeaders.hasSubscribers) { + channels.sendHeaders.publish({ request, headers: header, socket }); + } + + /* istanbul ignore else: assertion */ + if (!body) { + if (contentLength === 0) { + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1'); + } else { + assert$5(contentLength === null, 'no body must not have content length'); + socket.write(`${header}\r\n`, 'latin1'); + } + request.onRequestSent(); + } else if (util$g.isBuffer(body)) { + assert$5(contentLength === body.byteLength, 'buffer body must have content length'); + + socket.cork(); + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1'); + socket.write(body); + socket.uncork(); + request.onBodySent(body); + request.onRequestSent(); + if (!expectsPayload) { + socket[kReset] = true; + } + } else if (util$g.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload }); + } else { + writeBlob({ body, client, request, socket, contentLength, header, expectsPayload }); + } + } else if (util$g.isStream(body)) { + writeStream({ body, client, request, socket, contentLength, header, expectsPayload }); + } else if (util$g.isIterable(body)) { + writeIterable({ body, client, request, socket, contentLength, header, expectsPayload }); + } else { + assert$5(false); + } + + return true + } + + function writeH2 (client, session, request) { + const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request; + + let headers; + if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim()); + else headers = reqHeaders; + + if (upgrade) { + errorRequest(client, request, new Error('Upgrade not supported for H2')); + return false + } + + try { + // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } + + errorRequest(client, request, err || new RequestAbortedError$8()); + }); + } catch (err) { + errorRequest(client, request, err); + } + + if (request.aborted) { + return false + } + + let stream; + const h2State = client[kHTTP2SessionState]; + + headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost]; + headers[HTTP2_HEADER_METHOD] = method; + + if (method === 'CONNECT') { + session.ref(); + // we are already connected, streams are pending, first request + // will create a new stream. We trigger a request to create the stream and wait until + // `ready` event is triggered + // We disabled endStream to allow the user to write to the stream + stream = session.request(headers, { endStream: false, signal }); + + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream); + ++h2State.openStreams; + } else { + stream.once('ready', () => { + request.onUpgrade(null, null, stream); + ++h2State.openStreams; + }); + } + + stream.once('close', () => { + h2State.openStreams -= 1; + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) session.unref(); + }); + + return true + } + + // https://tools.ietf.org/html/rfc7540#section-8.3 + // :path and :scheme headers must be omited when sending CONNECT + + headers[HTTP2_HEADER_PATH] = path; + headers[HTTP2_HEADER_SCHEME] = 'https'; + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ); + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0); + } + + let contentLength = util$g.bodyLength(body); + + if (contentLength == null) { + contentLength = request.contentLength; + } + + if (contentLength === 0 || !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null; + } + + if (request.contentLength != null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + errorRequest(client, request, new RequestContentLengthMismatchError()); + return false + } + + browser$1$1.emitWarning(new RequestContentLengthMismatchError()); + } + + if (contentLength != null) { + assert$5(body, 'no body must not have content length'); + headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}`; + } + + session.ref(); + + const shouldEndStream = method === 'GET' || method === 'HEAD'; + if (expectContinue) { + headers[HTTP2_HEADER_EXPECT] = '100-continue'; + /** + * @type {import('node:http2').ClientHttp2Stream} + */ + stream = session.request(headers, { endStream: shouldEndStream, signal }); + + stream.once('continue', writeBodyH2); + } else { + /** @type {import('node:http2').ClientHttp2Stream} */ + stream = session.request(headers, { + endStream: shouldEndStream, + signal + }); + writeBodyH2(); + } + + // Increment counter as we have new several streams open + ++h2State.openStreams; + + stream.once('response', headers => { + if (request.onHeaders(Number(headers[HTTP2_HEADER_STATUS]), headers, stream.resume.bind(stream), '') === false) { + stream.pause(); + } + }); + + stream.once('end', () => { + request.onComplete([]); + }); + + stream.on('data', (chunk) => { + if (request.onData(chunk) === false) stream.pause(); + }); + + stream.once('close', () => { + h2State.openStreams -= 1; + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) session.unref(); + }); + + stream.once('error', function (err) { + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1; + util$g.destroy(stream, err); + } + }); + + stream.once('frameError', (type, code) => { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`); + errorRequest(client, request, err); + + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1; + util$g.destroy(stream, err); + } + }); + + // stream.on('aborted', () => { + // // TODO(HTTP/2): Support aborted + // }) + + // stream.on('timeout', () => { + // // TODO(HTTP/2): Support timeout + // }) + + // stream.on('push', headers => { + // // TODO(HTTP/2): Suppor push + // }) + + // stream.on('trailers', headers => { + // // TODO(HTTP/2): Support trailers + // }) + + return true + + function writeBodyH2 () { + /* istanbul ignore else: assertion */ + if (!body) { + request.onRequestSent(); + } else if (util$g.isBuffer(body)) { + assert$5(contentLength === body.byteLength, 'buffer body must have content length'); + stream.cork(); + stream.write(body); + stream.uncork(); + stream.end(); + request.onBodySent(body); + request.onRequestSent(); + } else if (util$g.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable({ + client, + request, + contentLength, + h2stream: stream, + expectsPayload, + body: body.stream(), + socket: client[kSocket], + header: '' + }); + } else { + writeBlob({ + body, + client, + request, + contentLength, + expectsPayload, + h2stream: stream, + header: '', + socket: client[kSocket] + }); + } + } else if (util$g.isStream(body)) { + writeStream({ + body, + client, + request, + contentLength, + expectsPayload, + socket: client[kSocket], + h2stream: stream, + header: '' + }); + } else if (util$g.isIterable(body)) { + writeIterable({ + body, + client, + request, + contentLength, + expectsPayload, + header: '', + h2stream: stream, + socket: client[kSocket] + }); + } else { + assert$5(false); + } + } + } + + function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert$5(contentLength !== 0 || client[kRunning$3] === 0, 'stream body cannot be pipelined'); + + if (client[kHTTPConnVersion] === 'h2') { + // For HTTP/2, is enough to pipe the stream + const pipe = pipeline$1( + body, + h2stream, + (err) => { + if (err) { + util$g.destroy(body, err); + util$g.destroy(h2stream, err); + } else { + request.onRequestSent(); + } + } + ); + + pipe.on('data', onPipeData); + pipe.once('end', () => { + pipe.removeListener('data', onPipeData); + util$g.destroy(pipe); + }); + + function onPipeData (chunk) { + request.onBodySent(chunk); + } + + return + } + + let finished = false; + + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }); + + const onData = function (chunk) { + if (finished) { + return + } + + try { + if (!writer.write(chunk) && this.pause) { + this.pause(); + } + } catch (err) { + util$g.destroy(this, err); + } + }; + const onDrain = function () { + if (finished) { + return + } + + if (body.resume) { + body.resume(); + } + }; + const onAbort = function () { + onFinished(new RequestAbortedError$8()); + }; + const onFinished = function (err) { + if (finished) { + return + } + + finished = true; + + assert$5(socket.destroyed || (socket[kWriting] && client[kRunning$3] <= 1)); + + socket + .off('drain', onDrain) + .off('error', onFinished); + + body + .removeListener('data', onData) + .removeListener('end', onFinished) + .removeListener('error', onFinished) + .removeListener('close', onAbort); + + if (!err) { + try { + writer.end(); + } catch (er) { + err = er; + } + } + + writer.destroy(err); + + if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { + util$g.destroy(body, err); + } else { + util$g.destroy(body); + } + }; + + body + .on('data', onData) + .on('end', onFinished) + .on('error', onFinished) + .on('close', onAbort); + + if (body.resume) { + body.resume(); + } + + socket + .on('drain', onDrain) + .on('error', onFinished); + } + + async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert$5(contentLength === body.size, 'blob body must have content length'); + + const isH2 = client[kHTTPConnVersion] === 'h2'; + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } + + const buffer = Buffer.from(await body.arrayBuffer()); + + if (isH2) { + h2stream.cork(); + h2stream.write(buffer); + h2stream.uncork(); + } else { + socket.cork(); + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1'); + socket.write(buffer); + socket.uncork(); + } + + request.onBodySent(buffer); + request.onRequestSent(); + + if (!expectsPayload) { + socket[kReset] = true; + } + + resume(client); + } catch (err) { + util$g.destroy(isH2 ? h2stream : socket, err); + } + } + + async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert$5(contentLength !== 0 || client[kRunning$3] === 0, 'iterator body cannot be pipelined'); + + let callback = null; + function onDrain () { + if (callback) { + const cb = callback; + callback = null; + cb(); + } + } + + const waitForDrain = () => new Promise((resolve, reject) => { + assert$5(callback === null); + + if (socket[kError]) { + reject(socket[kError]); + } else { + callback = resolve; + } + }); + + if (client[kHTTPConnVersion] === 'h2') { + h2stream + .on('close', onDrain) + .on('drain', onDrain); + + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + const res = h2stream.write(chunk); + request.onBodySent(chunk); + if (!res) { + await waitForDrain(); + } + } + } catch (err) { + h2stream.destroy(err); + } finally { + request.onRequestSent(); + h2stream.end(); + h2stream + .off('close', onDrain) + .off('drain', onDrain); + } + + return + } + + socket + .on('close', onDrain) + .on('drain', onDrain); + + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }); + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + if (!writer.write(chunk)) { + await waitForDrain(); + } + } + + writer.end(); + } catch (err) { + writer.destroy(err); + } finally { + socket + .off('close', onDrain) + .off('drain', onDrain); + } + } + + class AsyncWriter { + constructor ({ socket, request, contentLength, client, expectsPayload, header }) { + this.socket = socket; + this.request = request; + this.contentLength = contentLength; + this.client = client; + this.bytesWritten = 0; + this.expectsPayload = expectsPayload; + this.header = header; + + socket[kWriting] = true; + } + + write (chunk) { + const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this; + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return false + } + + const len = Buffer.byteLength(chunk); + if (!len) { + return true + } + + // We should defer writing chunks. + if (contentLength !== null && bytesWritten + len > contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } + + browser$1$1.emitWarning(new RequestContentLengthMismatchError()); + } + + socket.cork(); + + if (bytesWritten === 0) { + if (!expectsPayload) { + socket[kReset] = true; + } + + if (contentLength === null) { + socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1'); + } else { + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1'); + } + } + + if (contentLength === null) { + socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1'); + } + + this.bytesWritten += len; + + const ret = socket.write(chunk); + + socket.uncork(); + + request.onBodySent(chunk); + + if (!ret) { + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh(); + } + } + } + + return ret + } + + end () { + const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this; + request.onRequestSent(); + + socket[kWriting] = false; + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return + } + + if (bytesWritten === 0) { + if (expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. + + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1'); + } else { + socket.write(`${header}\r\n`, 'latin1'); + } + } else if (contentLength === null) { + socket.write('\r\n0\r\n\r\n', 'latin1'); + } + + if (contentLength !== null && bytesWritten !== contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } else { + browser$1$1.emitWarning(new RequestContentLengthMismatchError()); + } + } + + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh(); + } + } + + resume(client); + } + + destroy (err) { + const { socket, client } = this; + + socket[kWriting] = false; + + if (err) { + assert$5(client[kRunning$3] <= 1, 'pipeline should only contain this request'); + util$g.destroy(socket, err); + } + } + } + + function errorRequest (client, request, err) { + try { + request.onError(err); + assert$5(request.aborted); + } catch (err) { + client.emit('error', err); + } + } + + var client = Client$4; + + /* eslint-disable */ + + // Extracted from node/lib/internal/fixed_queue.js + + // Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. + const kSize$3 = 2048; + const kMask = kSize$3 - 1; + + // The FixedQueue is implemented as a singly-linked list of fixed-size + // circular buffers. It looks something like this: + // + // head tail + // | | + // v v + // +-----------+ <-----\ +-----------+ <------\ +-----------+ + // | [null] | \----- | next | \------- | next | + // +-----------+ +-----------+ +-----------+ + // | item | <-- bottom | item | <-- bottom | [empty] | + // | item | | item | | [empty] | + // | item | | item | | [empty] | + // | item | | item | | [empty] | + // | item | | item | bottom --> | item | + // | item | | item | | item | + // | ... | | ... | | ... | + // | item | | item | | item | + // | item | | item | | item | + // | [empty] | <-- top | item | | item | + // | [empty] | | item | | item | + // | [empty] | | [empty] | <-- top top --> | [empty] | + // +-----------+ +-----------+ +-----------+ + // + // Or, if there is only one circular buffer, it looks something + // like either of these: + // + // head tail head tail + // | | | | + // v v v v + // +-----------+ +-----------+ + // | [null] | | [null] | + // +-----------+ +-----------+ + // | [empty] | | item | + // | [empty] | | item | + // | item | <-- bottom top --> | [empty] | + // | item | | [empty] | + // | [empty] | <-- top bottom --> | item | + // | [empty] | | item | + // +-----------+ +-----------+ + // + // Adding a value means moving `top` forward by one, removing means + // moving `bottom` forward by one. After reaching the end, the queue + // wraps around. + // + // When `top === bottom` the current queue is empty and when + // `top + 1 === bottom` it's full. This wastes a single space of storage + // but allows much quicker checks. + + class FixedCircularBuffer { + constructor() { + this.bottom = 0; + this.top = 0; + this.list = new Array(kSize$3); + this.next = null; + } + + isEmpty() { + return this.top === this.bottom; + } + + isFull() { + return ((this.top + 1) & kMask) === this.bottom; + } + + push(data) { + this.list[this.top] = data; + this.top = (this.top + 1) & kMask; + } + + shift() { + const nextItem = this.list[this.bottom]; + if (nextItem === undefined) + return null; + this.list[this.bottom] = undefined; + this.bottom = (this.bottom + 1) & kMask; + return nextItem; + } + } + + var fixedQueue = class FixedQueue { + constructor() { + this.head = this.tail = new FixedCircularBuffer(); + } + + isEmpty() { + return this.head.isEmpty(); + } + + push(data) { + if (this.head.isFull()) { + // Head is full: Creates a new queue, sets the old queue's `.next` to it, + // and sets it as the new main queue. + this.head = this.head.next = new FixedCircularBuffer(); + } + this.head.push(data); + } + + shift() { + const tail = this.tail; + const next = tail.shift(); + if (tail.isEmpty() && tail.next !== null) { + // If there is another queue, it forms the new tail. + this.tail = tail.next; + } + return next; + } + }; + + const { kFree: kFree$1, kConnected: kConnected$4, kPending: kPending$1, kQueued: kQueued$1, kRunning: kRunning$2, kSize: kSize$2 } = symbols$4; + const kPool = Symbol('pool'); + + let PoolStats$1 = class PoolStats { + constructor (pool) { + this[kPool] = pool; + } + + get connected () { + return this[kPool][kConnected$4] + } + + get free () { + return this[kPool][kFree$1] + } + + get pending () { + return this[kPool][kPending$1] + } + + get queued () { + return this[kPool][kQueued$1] + } + + get running () { + return this[kPool][kRunning$2] + } + + get size () { + return this[kPool][kSize$2] + } + }; + + var poolStats = PoolStats$1; + + const DispatcherBase$2 = dispatcherBase; + const FixedQueue = fixedQueue; + const { kConnected: kConnected$3, kSize: kSize$1, kRunning: kRunning$1, kPending, kQueued, kBusy, kFree, kUrl: kUrl$2, kClose: kClose$4, kDestroy: kDestroy$2, kDispatch: kDispatch$1 } = symbols$4; + const PoolStats = poolStats; + + const kClients$4 = Symbol('clients'); + const kNeedDrain$2 = Symbol('needDrain'); + const kQueue = Symbol('queue'); + const kClosedResolve = Symbol('closed resolve'); + const kOnDrain$1 = Symbol('onDrain'); + const kOnConnect$1 = Symbol('onConnect'); + const kOnDisconnect$1 = Symbol('onDisconnect'); + const kOnConnectionError$1 = Symbol('onConnectionError'); + const kGetDispatcher$2 = Symbol('get dispatcher'); + const kAddClient$2 = Symbol('add client'); + const kRemoveClient$1 = Symbol('remove client'); + const kStats = Symbol('stats'); + + let PoolBase$2 = class PoolBase extends DispatcherBase$2 { + constructor () { + super(); + + this[kQueue] = new FixedQueue(); + this[kClients$4] = []; + this[kQueued] = 0; + + const pool = this; + + this[kOnDrain$1] = function onDrain (origin, targets) { + const queue = pool[kQueue]; + + let needDrain = false; + + while (!needDrain) { + const item = queue.shift(); + if (!item) { + break + } + pool[kQueued]--; + needDrain = !this.dispatch(item.opts, item.handler); + } + + this[kNeedDrain$2] = needDrain; + + if (!this[kNeedDrain$2] && pool[kNeedDrain$2]) { + pool[kNeedDrain$2] = false; + pool.emit('drain', origin, [pool, ...targets]); + } + + if (pool[kClosedResolve] && queue.isEmpty()) { + Promise + .all(pool[kClients$4].map(c => c.close())) + .then(pool[kClosedResolve]); + } + }; + + this[kOnConnect$1] = (origin, targets) => { + pool.emit('connect', origin, [pool, ...targets]); + }; + + this[kOnDisconnect$1] = (origin, targets, err) => { + pool.emit('disconnect', origin, [pool, ...targets], err); + }; + + this[kOnConnectionError$1] = (origin, targets, err) => { + pool.emit('connectionError', origin, [pool, ...targets], err); + }; + + this[kStats] = new PoolStats(this); + } + + get [kBusy] () { + return this[kNeedDrain$2] + } + + get [kConnected$3] () { + return this[kClients$4].filter(client => client[kConnected$3]).length + } + + get [kFree] () { + return this[kClients$4].filter(client => client[kConnected$3] && !client[kNeedDrain$2]).length + } + + get [kPending] () { + let ret = this[kQueued]; + for (const { [kPending]: pending } of this[kClients$4]) { + ret += pending; + } + return ret + } + + get [kRunning$1] () { + let ret = 0; + for (const { [kRunning$1]: running } of this[kClients$4]) { + ret += running; + } + return ret + } + + get [kSize$1] () { + let ret = this[kQueued]; + for (const { [kSize$1]: size } of this[kClients$4]) { + ret += size; + } + return ret + } + + get stats () { + return this[kStats] + } + + async [kClose$4] () { + if (this[kQueue].isEmpty()) { + return Promise.all(this[kClients$4].map(c => c.close())) + } else { + return new Promise((resolve) => { + this[kClosedResolve] = resolve; + }) + } + } + + async [kDestroy$2] (err) { + while (true) { + const item = this[kQueue].shift(); + if (!item) { + break + } + item.handler.onError(err); + } + + return Promise.all(this[kClients$4].map(c => c.destroy(err))) + } + + [kDispatch$1] (opts, handler) { + const dispatcher = this[kGetDispatcher$2](); + + if (!dispatcher) { + this[kNeedDrain$2] = true; + this[kQueue].push({ opts, handler }); + this[kQueued]++; + } else if (!dispatcher.dispatch(opts, handler)) { + dispatcher[kNeedDrain$2] = true; + this[kNeedDrain$2] = !this[kGetDispatcher$2](); + } + + return !this[kNeedDrain$2] + } + + [kAddClient$2] (client) { + client + .on('drain', this[kOnDrain$1]) + .on('connect', this[kOnConnect$1]) + .on('disconnect', this[kOnDisconnect$1]) + .on('connectionError', this[kOnConnectionError$1]); + + this[kClients$4].push(client); + + if (this[kNeedDrain$2]) { + browser$1$1.nextTick(() => { + if (this[kNeedDrain$2]) { + this[kOnDrain$1](client[kUrl$2], [this, client]); + } + }); + } + + return this + } + + [kRemoveClient$1] (client) { + client.close(() => { + const idx = this[kClients$4].indexOf(client); + if (idx !== -1) { + this[kClients$4].splice(idx, 1); + } + }); + + this[kNeedDrain$2] = this[kClients$4].some(dispatcher => ( + !dispatcher[kNeedDrain$2] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )); + } + }; + + var poolBase = { + PoolBase: PoolBase$2, + kClients: kClients$4, + kNeedDrain: kNeedDrain$2, + kAddClient: kAddClient$2, + kRemoveClient: kRemoveClient$1, + kGetDispatcher: kGetDispatcher$2 + }; + + const { + PoolBase: PoolBase$1, + kClients: kClients$3, + kNeedDrain: kNeedDrain$1, + kAddClient: kAddClient$1, + kGetDispatcher: kGetDispatcher$1 + } = poolBase; + const Client$3 = client; + const { + InvalidArgumentError: InvalidArgumentError$f + } = errors$1; + const util$f = util$l; + const { kUrl: kUrl$1, kInterceptors: kInterceptors$3 } = symbols$4; + const buildConnector$2 = connect$2; + + const kOptions$3 = Symbol('options'); + const kConnections = Symbol('connections'); + const kFactory$3 = Symbol('factory'); + + function defaultFactory$3 (origin, opts) { + return new Client$3(origin, opts) + } + + let Pool$5 = class Pool extends PoolBase$1 { + constructor (origin, { + connections, + factory = defaultFactory$3, + connect, + connectTimeout, + tls, + maxCachedSessions, + socketPath, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + allowH2, + ...options + } = {}) { + super(); + + if (connections != null && (!Number.isFinite(connections) || connections < 0)) { + throw new InvalidArgumentError$f('invalid connections') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError$f('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError$f('connect must be a function or an object') + } + + if (typeof connect !== 'function') { + connect = buildConnector$2({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout == null ? 10e3 : connectTimeout, + ...(util$f.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }); + } + + this[kInterceptors$3] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool) + ? options.interceptors.Pool + : []; + this[kConnections] = connections || null; + this[kUrl$1] = util$f.parseOrigin(origin); + this[kOptions$3] = { ...util$f.deepClone(options), connect, allowH2 }; + this[kOptions$3].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined; + this[kFactory$3] = factory; + } + + [kGetDispatcher$1] () { + let dispatcher = this[kClients$3].find(dispatcher => !dispatcher[kNeedDrain$1]); + + if (dispatcher) { + return dispatcher + } + + if (!this[kConnections] || this[kClients$3].length < this[kConnections]) { + dispatcher = this[kFactory$3](this[kUrl$1], this[kOptions$3]); + this[kAddClient$1](dispatcher); + } + + return dispatcher + } + }; + + var pool = Pool$5; + + const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError: InvalidArgumentError$e + } = errors$1; + const { + PoolBase, + kClients: kClients$2, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher + } = poolBase; + const Pool$4 = pool; + const { kUrl, kInterceptors: kInterceptors$2 } = symbols$4; + const { parseOrigin } = util$l; + const kFactory$2 = Symbol('factory'); + + const kOptions$2 = Symbol('options'); + const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor'); + const kCurrentWeight = Symbol('kCurrentWeight'); + const kIndex = Symbol('kIndex'); + const kWeight = Symbol('kWeight'); + const kMaxWeightPerServer = Symbol('kMaxWeightPerServer'); + const kErrorPenalty = Symbol('kErrorPenalty'); + + function getGreatestCommonDivisor (a, b) { + if (b === 0) return a + return getGreatestCommonDivisor(b, a % b) + } + + function defaultFactory$2 (origin, opts) { + return new Pool$4(origin, opts) + } + + let BalancedPool$1 = class BalancedPool extends PoolBase { + constructor (upstreams = [], { factory = defaultFactory$2, ...opts } = {}) { + super(); + + this[kOptions$2] = opts; + this[kIndex] = -1; + this[kCurrentWeight] = 0; + + this[kMaxWeightPerServer] = this[kOptions$2].maxWeightPerServer || 100; + this[kErrorPenalty] = this[kOptions$2].errorPenalty || 15; + + if (!Array.isArray(upstreams)) { + upstreams = [upstreams]; + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError$e('factory must be a function.') + } + + this[kInterceptors$2] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) + ? opts.interceptors.BalancedPool + : []; + this[kFactory$2] = factory; + + for (const upstream of upstreams) { + this.addUpstream(upstream); + } + this._updateBalancedPoolStats(); + } + + addUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin; + + if (this[kClients$2].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + ))) { + return this + } + const pool = this[kFactory$2](upstreamOrigin, Object.assign({}, this[kOptions$2])); + + this[kAddClient](pool); + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]); + }); + + pool.on('connectionError', () => { + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]); + this._updateBalancedPoolStats(); + }); + + pool.on('disconnect', (...args) => { + const err = args[2]; + if (err && err.code === 'UND_ERR_SOCKET') { + // decrease the weight of the pool. + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]); + this._updateBalancedPoolStats(); + } + }); + + for (const client of this[kClients$2]) { + client[kWeight] = this[kMaxWeightPerServer]; + } + + this._updateBalancedPoolStats(); + + return this + } + + _updateBalancedPoolStats () { + this[kGreatestCommonDivisor] = this[kClients$2].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0); + } + + removeUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin; + + const pool = this[kClients$2].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )); + + if (pool) { + this[kRemoveClient](pool); + } + + return this + } + + get upstreams () { + return this[kClients$2] + .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) + .map((p) => p[kUrl].origin) + } + + [kGetDispatcher] () { + // We validate that pools is greater than 0, + // otherwise we would have to wait until an upstream + // is added, which might never happen. + if (this[kClients$2].length === 0) { + throw new BalancedPoolMissingUpstreamError() + } + + const dispatcher = this[kClients$2].find(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )); + + if (!dispatcher) { + return + } + + const allClientsBusy = this[kClients$2].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true); + + if (allClientsBusy) { + return + } + + let counter = 0; + + let maxWeightIndex = this[kClients$2].findIndex(pool => !pool[kNeedDrain]); + + while (counter++ < this[kClients$2].length) { + this[kIndex] = (this[kIndex] + 1) % this[kClients$2].length; + const pool = this[kClients$2][this[kIndex]]; + + // find pool index with the largest weight + if (pool[kWeight] > this[kClients$2][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { + maxWeightIndex = this[kIndex]; + } + + // decrease the current weight every `this[kClients].length`. + if (this[kIndex] === 0) { + // Set the current weight to the next lower weight. + this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor]; + + if (this[kCurrentWeight] <= 0) { + this[kCurrentWeight] = this[kMaxWeightPerServer]; + } + } + if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { + return pool + } + } + + this[kCurrentWeight] = this[kClients$2][maxWeightIndex][kWeight]; + this[kIndex] = maxWeightIndex; + return this[kClients$2][maxWeightIndex] + } + }; + + var balancedPool = BalancedPool$1; + + /* istanbul ignore file: only for Node 12 */ + + const { kConnected: kConnected$2, kSize } = symbols$4; + + class CompatWeakRef { + constructor (value) { + this.value = value; + } + + deref () { + return this.value[kConnected$2] === 0 && this.value[kSize] === 0 + ? undefined + : this.value + } + } + + class CompatFinalizer { + constructor (finalizer) { + this.finalizer = finalizer; + } + + register (dispatcher, key) { + if (dispatcher.on) { + dispatcher.on('disconnect', () => { + if (dispatcher[kConnected$2] === 0 && dispatcher[kSize] === 0) { + this.finalizer(key); + } + }); + } + } + } + + var dispatcherWeakref = function () { + // FIXME: remove workaround when the Node bug is fixed + // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 + if (browser$1$1.env.NODE_V8_COVERAGE) { + return { + WeakRef: CompatWeakRef, + FinalizationRegistry: CompatFinalizer + } + } + return { + WeakRef: commonjsGlobal.WeakRef || CompatWeakRef, + FinalizationRegistry: commonjsGlobal.FinalizationRegistry || CompatFinalizer + } + }; + + const { InvalidArgumentError: InvalidArgumentError$d } = errors$1; + const { kClients: kClients$1, kRunning, kClose: kClose$3, kDestroy: kDestroy$1, kDispatch, kInterceptors: kInterceptors$1 } = symbols$4; + const DispatcherBase$1 = dispatcherBase; + const Pool$3 = pool; + const Client$2 = client; + const util$e = util$l; + const createRedirectInterceptor$1 = redirectInterceptor; + const { WeakRef: WeakRef$1, FinalizationRegistry } = dispatcherWeakref(); + + const kOnConnect = Symbol('onConnect'); + const kOnDisconnect = Symbol('onDisconnect'); + const kOnConnectionError = Symbol('onConnectionError'); + const kMaxRedirections = Symbol('maxRedirections'); + const kOnDrain = Symbol('onDrain'); + const kFactory$1 = Symbol('factory'); + const kFinalizer = Symbol('finalizer'); + const kOptions$1 = Symbol('options'); + + function defaultFactory$1 (origin, opts) { + return opts && opts.connections === 1 + ? new Client$2(origin, opts) + : new Pool$3(origin, opts) + } + + let Agent$4 = class Agent extends DispatcherBase$1 { + constructor ({ factory = defaultFactory$1, maxRedirections = 0, connect, ...options } = {}) { + super(); + + if (typeof factory !== 'function') { + throw new InvalidArgumentError$d('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError$d('connect must be a function or an object') + } + + if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { + throw new InvalidArgumentError$d('maxRedirections must be a positive number') + } + + if (connect && typeof connect !== 'function') { + connect = { ...connect }; + } + + this[kInterceptors$1] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) + ? options.interceptors.Agent + : [createRedirectInterceptor$1({ maxRedirections })]; + + this[kOptions$1] = { ...util$e.deepClone(options), connect }; + this[kOptions$1].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined; + this[kMaxRedirections] = maxRedirections; + this[kFactory$1] = factory; + this[kClients$1] = new Map(); + this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => { + const ref = this[kClients$1].get(key); + if (ref !== undefined && ref.deref() === undefined) { + this[kClients$1].delete(key); + } + }); + + const agent = this; + + this[kOnDrain] = (origin, targets) => { + agent.emit('drain', origin, [agent, ...targets]); + }; + + this[kOnConnect] = (origin, targets) => { + agent.emit('connect', origin, [agent, ...targets]); + }; + + this[kOnDisconnect] = (origin, targets, err) => { + agent.emit('disconnect', origin, [agent, ...targets], err); + }; + + this[kOnConnectionError] = (origin, targets, err) => { + agent.emit('connectionError', origin, [agent, ...targets], err); + }; + } + + get [kRunning] () { + let ret = 0; + for (const ref of this[kClients$1].values()) { + const client = ref.deref(); + /* istanbul ignore next: gc is undeterministic */ + if (client) { + ret += client[kRunning]; + } + } + return ret + } + + [kDispatch] (opts, handler) { + let key; + if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { + key = String(opts.origin); + } else { + throw new InvalidArgumentError$d('opts.origin must be a non-empty string or URL.') + } + + const ref = this[kClients$1].get(key); + + let dispatcher = ref ? ref.deref() : null; + if (!dispatcher) { + dispatcher = this[kFactory$1](opts.origin, this[kOptions$1]) + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]); + + this[kClients$1].set(key, new WeakRef$1(dispatcher)); + this[kFinalizer].register(dispatcher, key); + } + + return dispatcher.dispatch(opts, handler) + } + + async [kClose$3] () { + const closePromises = []; + for (const ref of this[kClients$1].values()) { + const client = ref.deref(); + /* istanbul ignore else: gc is undeterministic */ + if (client) { + closePromises.push(client.close()); + } + } + + await Promise.all(closePromises); + } + + async [kDestroy$1] (err) { + const destroyPromises = []; + for (const ref of this[kClients$1].values()) { + const client = ref.deref(); + /* istanbul ignore else: gc is undeterministic */ + if (client) { + destroyPromises.push(client.destroy(err)); + } + } + + await Promise.all(destroyPromises); + } + }; + + var agent = Agent$4; + + var api$1 = {}; + + const assert$4 = require$$3$1; + const { Readable: Readable$2 } = require$$0$1; + const { RequestAbortedError: RequestAbortedError$7, NotSupportedError, InvalidArgumentError: InvalidArgumentError$c } = errors$1; + const util$d = util$l; + const { ReadableStreamFrom, toUSVString: toUSVString$1 } = util$l; + + let Blob$1; + + const kConsume = Symbol('kConsume'); + const kReading = Symbol('kReading'); + const kBody = Symbol('kBody'); + const kAbort = Symbol('abort'); + const kContentType = Symbol('kContentType'); + + var readable = class BodyReadable extends Readable$2 { + constructor ({ + resume, + abort, + contentType = '', + highWaterMark = 64 * 1024 // Same as nodejs fs streams. + }) { + super({ + autoDestroy: true, + read: resume, + highWaterMark + }); + + this._readableState.dataEmitted = false; + + this[kAbort] = abort; + this[kConsume] = null; + this[kBody] = null; + this[kContentType] = contentType; + + // Is stream being consumed through Readable API? + // This is an optimization so that we avoid checking + // for 'data' and 'readable' listeners in the hot path + // inside push(). + this[kReading] = false; + } + + destroy (err) { + if (this.destroyed) { + // Node < 16 + return this + } + + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError$7(); + } + + if (err) { + this[kAbort](); + } + + return super.destroy(err) + } + + emit (ev, ...args) { + if (ev === 'data') { + // Node < 16.7 + this._readableState.dataEmitted = true; + } else if (ev === 'error') { + // Node < 16 + this._readableState.errorEmitted = true; + } + return super.emit(ev, ...args) + } + + on (ev, ...args) { + if (ev === 'data' || ev === 'readable') { + this[kReading] = true; + } + return super.on(ev, ...args) + } + + addListener (ev, ...args) { + return this.on(ev, ...args) + } + + off (ev, ...args) { + const ret = super.off(ev, ...args); + if (ev === 'data' || ev === 'readable') { + this[kReading] = ( + this.listenerCount('data') > 0 || + this.listenerCount('readable') > 0 + ); + } + return ret + } + + removeListener (ev, ...args) { + return this.off(ev, ...args) + } + + push (chunk) { + if (this[kConsume] && chunk !== null && this.readableLength === 0) { + consumePush(this[kConsume], chunk); + return this[kReading] ? super.push(chunk) : true + } + return super.push(chunk) + } + + // https://fetch.spec.whatwg.org/#dom-body-text + async text () { + return consume(this, 'text') + } + + // https://fetch.spec.whatwg.org/#dom-body-json + async json () { + return consume(this, 'json') + } + + // https://fetch.spec.whatwg.org/#dom-body-blob + async blob () { + return consume(this, 'blob') + } + + // https://fetch.spec.whatwg.org/#dom-body-arraybuffer + async arrayBuffer () { + return consume(this, 'arrayBuffer') + } + + // https://fetch.spec.whatwg.org/#dom-body-formdata + async formData () { + // TODO: Implement. + throw new NotSupportedError() + } + + // https://fetch.spec.whatwg.org/#dom-body-bodyused + get bodyUsed () { + return util$d.isDisturbed(this) + } + + // https://fetch.spec.whatwg.org/#dom-body-body + get body () { + if (!this[kBody]) { + this[kBody] = ReadableStreamFrom(this); + if (this[kConsume]) { + // TODO: Is this the best way to force a lock? + this[kBody].getReader(); // Ensure stream is locked. + assert$4(this[kBody].locked); + } + } + return this[kBody] + } + + async dump (opts) { + let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144; + const signal = opts && opts.signal; + const abortFn = () => { + this.destroy(); + }; + let signalListenerCleanup; + if (signal) { + if (typeof signal !== 'object' || !('aborted' in signal)) { + throw new InvalidArgumentError$c('signal must be an AbortSignal') + } + util$d.throwIfAborted(signal); + signalListenerCleanup = util$d.addAbortListener(signal, abortFn); + } + try { + for await (const chunk of this) { + util$d.throwIfAborted(signal); + limit -= Buffer.byteLength(chunk); + if (limit < 0) { + return + } + } + } catch { + util$d.throwIfAborted(signal); + } finally { + if (typeof signalListenerCleanup === 'function') { + signalListenerCleanup(); + } else if (signalListenerCleanup) { + signalListenerCleanup[Symbol.dispose](); + } + } + } + }; + + // https://streams.spec.whatwg.org/#readablestream-locked + function isLocked (self) { + // Consume is an implicit lock. + return (self[kBody] && self[kBody].locked === true) || self[kConsume] + } + + // https://fetch.spec.whatwg.org/#body-unusable + function isUnusable (self) { + return util$d.isDisturbed(self) || isLocked(self) + } + + async function consume (stream, type) { + if (isUnusable(stream)) { + throw new TypeError('unusable') + } + + assert$4(!stream[kConsume]); + + return new Promise((resolve, reject) => { + stream[kConsume] = { + type, + stream, + resolve, + reject, + length: 0, + body: [] + }; + + stream + .on('error', function (err) { + consumeFinish(this[kConsume], err); + }) + .on('close', function () { + if (this[kConsume].body !== null) { + consumeFinish(this[kConsume], new RequestAbortedError$7()); + } + }); + + browser$1$1.nextTick(consumeStart, stream[kConsume]); + }) + } + + function consumeStart (consume) { + if (consume.body === null) { + return + } + + const { _readableState: state } = consume.stream; + + for (const chunk of state.buffer) { + consumePush(consume, chunk); + } + + if (state.endEmitted) { + consumeEnd(this[kConsume]); + } else { + consume.stream.on('end', function () { + consumeEnd(this[kConsume]); + }); + } + + consume.stream.resume(); + + while (consume.stream.read() != null) { + // Loop + } + } + + function consumeEnd (consume) { + const { type, body, resolve, stream, length } = consume; + + try { + if (type === 'text') { + resolve(toUSVString$1(Buffer.concat(body))); + } else if (type === 'json') { + resolve(JSON.parse(Buffer.concat(body))); + } else if (type === 'arrayBuffer') { + const dst = new Uint8Array(length); + + let pos = 0; + for (const buf of body) { + dst.set(buf, pos); + pos += buf.byteLength; + } + + resolve(dst.buffer); + } else if (type === 'blob') { + if (!Blob$1) { + Blob$1 = require$$7.Blob; + } + resolve(new Blob$1(body, { type: stream[kContentType] })); + } + + consumeFinish(consume); + } catch (err) { + stream.destroy(err); + } + } + + function consumePush (consume, chunk) { + consume.length += chunk.length; + consume.body.push(chunk); + } + + function consumeFinish (consume, err) { + if (consume.body === null) { + return + } + + if (err) { + consume.reject(err); + } else { + consume.resolve(); + } + + consume.type = null; + consume.stream = null; + consume.resolve = null; + consume.reject = null; + consume.length = 0; + consume.body = null; + } + + const assert$3 = require$$3$1; + const { + ResponseStatusCodeError + } = errors$1; + const { toUSVString } = util$l; + + async function getResolveErrorBodyCallback$2 ({ callback, body, contentType, statusCode, statusMessage, headers }) { + assert$3(body); + + let chunks = []; + let limit = 0; + + for await (const chunk of body) { + chunks.push(chunk); + limit += chunk.length; + if (limit > 128 * 1024) { + chunks = null; + break + } + } + + if (statusCode === 204 || !contentType || !chunks) { + browser$1$1.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)); + return + } + + try { + if (contentType.startsWith('application/json')) { + const payload = JSON.parse(toUSVString(Buffer.concat(chunks))); + browser$1$1.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)); + return + } + + if (contentType.startsWith('text/')) { + const payload = toUSVString(Buffer.concat(chunks)); + browser$1$1.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)); + return + } + } catch (err) { + // Process in a fallback if error + } + + browser$1$1.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)); + } + + var util$c = { getResolveErrorBodyCallback: getResolveErrorBodyCallback$2 }; + + let AsyncResource$5 = class AsyncResource {}; + + var _polyfillNode_async_hooks = /*#__PURE__*/Object.freeze({ + __proto__: null, + AsyncResource: AsyncResource$5 + }); + + var require$$0 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_async_hooks); + + const { addAbortListener } = util$l; + const { RequestAbortedError: RequestAbortedError$6 } = errors$1; + + const kListener = Symbol('kListener'); + const kSignal = Symbol('kSignal'); + + function abort (self) { + if (self.abort) { + self.abort(); + } else { + self.onError(new RequestAbortedError$6()); + } + } + + function addSignal$5 (self, signal) { + self[kSignal] = null; + self[kListener] = null; + + if (!signal) { + return + } + + if (signal.aborted) { + abort(self); + return + } + + self[kSignal] = signal; + self[kListener] = () => { + abort(self); + }; + + addAbortListener(self[kSignal], self[kListener]); + } + + function removeSignal$5 (self) { + if (!self[kSignal]) { + return + } + + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]); + } else { + self[kSignal].removeListener('abort', self[kListener]); + } + + self[kSignal] = null; + self[kListener] = null; + } + + var abortSignal = { + addSignal: addSignal$5, + removeSignal: removeSignal$5 + }; + + const Readable$1 = readable; + const { + InvalidArgumentError: InvalidArgumentError$b, + RequestAbortedError: RequestAbortedError$5 + } = errors$1; + const util$b = util$l; + const { getResolveErrorBodyCallback: getResolveErrorBodyCallback$1 } = util$c; + const { AsyncResource: AsyncResource$4 } = require$$0; + const { addSignal: addSignal$4, removeSignal: removeSignal$4 } = abortSignal; + + class RequestHandler extends AsyncResource$4 { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError$b('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts; + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError$b('invalid callback') + } + + if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { + throw new InvalidArgumentError$b('invalid highWaterMark') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError$b('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError$b('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError$b('invalid onInfo callback') + } + + super('UNDICI_REQUEST'); + } catch (err) { + if (util$b.isStream(body)) { + util$b.destroy(body.on('error', util$b.nop), err); + } + throw err + } + + this.responseHeaders = responseHeaders || null; + this.opaque = opaque || null; + this.callback = callback; + this.res = null; + this.abort = null; + this.body = body; + this.trailers = {}; + this.context = null; + this.onInfo = onInfo || null; + this.throwOnError = throwOnError; + this.highWaterMark = highWaterMark; + + if (util$b.isStream(body)) { + body.on('error', (err) => { + this.onError(err); + }); + } + + addSignal$4(this, signal); + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError$5() + } + + this.abort = abort; + this.context = context; + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this; + + const headers = responseHeaders === 'raw' ? util$b.parseRawHeaders(rawHeaders) : util$b.parseHeaders(rawHeaders); + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }); + } + return + } + + const parsedHeaders = responseHeaders === 'raw' ? util$b.parseHeaders(rawHeaders) : headers; + const contentType = parsedHeaders['content-type']; + const body = new Readable$1({ resume, abort, contentType, highWaterMark }); + + this.callback = null; + this.res = body; + if (callback !== null) { + if (this.throwOnError && statusCode >= 400) { + this.runInAsyncScope(getResolveErrorBodyCallback$1, null, + { callback, body, contentType, statusCode, statusMessage, headers } + ); + } else { + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + trailers: this.trailers, + opaque, + body, + context + }); + } + } + } + + onData (chunk) { + const { res } = this; + return res.push(chunk) + } + + onComplete (trailers) { + const { res } = this; + + removeSignal$4(this); + + util$b.parseHeaders(trailers, this.trailers); + + res.push(null); + } + + onError (err) { + const { res, callback, body, opaque } = this; + + removeSignal$4(this); + + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null; + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }); + }); + } + + if (res) { + this.res = null; + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util$b.destroy(res, err); + }); + } + + if (body) { + this.body = null; + util$b.destroy(body, err); + } + } + } + + function request$1 (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request$1.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }); + }) + } + + try { + this.dispatch(opts, new RequestHandler(opts, callback)); + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque; + queueMicrotask(() => callback(err, { opaque })); + } + } + + var apiRequest = request$1; + + const { finished, PassThrough: PassThrough$1 } = require$$0$1; + const { + InvalidArgumentError: InvalidArgumentError$a, + InvalidReturnValueError: InvalidReturnValueError$1, + RequestAbortedError: RequestAbortedError$4 + } = errors$1; + const util$a = util$l; + const { getResolveErrorBodyCallback } = util$c; + const { AsyncResource: AsyncResource$3 } = require$$0; + const { addSignal: addSignal$3, removeSignal: removeSignal$3 } = abortSignal; + + class StreamHandler extends AsyncResource$3 { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError$a('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts; + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError$a('invalid callback') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError$a('invalid factory') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError$a('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError$a('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError$a('invalid onInfo callback') + } + + super('UNDICI_STREAM'); + } catch (err) { + if (util$a.isStream(body)) { + util$a.destroy(body.on('error', util$a.nop), err); + } + throw err + } + + this.responseHeaders = responseHeaders || null; + this.opaque = opaque || null; + this.factory = factory; + this.callback = callback; + this.res = null; + this.abort = null; + this.context = null; + this.trailers = null; + this.body = body; + this.onInfo = onInfo || null; + this.throwOnError = throwOnError || false; + + if (util$a.isStream(body)) { + body.on('error', (err) => { + this.onError(err); + }); + } + + addSignal$3(this, signal); + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError$4() + } + + this.abort = abort; + this.context = context; + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { factory, opaque, context, callback, responseHeaders } = this; + + const headers = responseHeaders === 'raw' ? util$a.parseRawHeaders(rawHeaders) : util$a.parseHeaders(rawHeaders); + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }); + } + return + } + + this.factory = null; + + let res; + + if (this.throwOnError && statusCode >= 400) { + const parsedHeaders = responseHeaders === 'raw' ? util$a.parseHeaders(rawHeaders) : headers; + const contentType = parsedHeaders['content-type']; + res = new PassThrough$1(); + + this.callback = null; + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body: res, contentType, statusCode, statusMessage, headers } + ); + } else { + if (factory === null) { + return + } + + res = this.runInAsyncScope(factory, null, { + statusCode, + headers, + opaque, + context + }); + + if ( + !res || + typeof res.write !== 'function' || + typeof res.end !== 'function' || + typeof res.on !== 'function' + ) { + throw new InvalidReturnValueError$1('expected Writable') + } + + // TODO: Avoid finished. It registers an unnecessary amount of listeners. + finished(res, { readable: false }, (err) => { + const { callback, res, opaque, trailers, abort } = this; + + this.res = null; + if (err || !res.readable) { + util$a.destroy(res, err); + } + + this.callback = null; + this.runInAsyncScope(callback, null, err || null, { opaque, trailers }); + + if (err) { + abort(); + } + }); + } + + res.on('drain', resume); + + this.res = res; + + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState && res._writableState.needDrain; + + return needDrain !== true + } + + onData (chunk) { + const { res } = this; + + return res ? res.write(chunk) : true + } + + onComplete (trailers) { + const { res } = this; + + removeSignal$3(this); + + if (!res) { + return + } + + this.trailers = util$a.parseHeaders(trailers); + + res.end(); + } + + onError (err) { + const { res, callback, opaque, body } = this; + + removeSignal$3(this); + + this.factory = null; + + if (res) { + this.res = null; + util$a.destroy(res, err); + } else if (callback) { + this.callback = null; + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }); + }); + } + + if (body) { + this.body = null; + util$a.destroy(body, err); + } + } + } + + function stream (opts, factory, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + stream.call(this, opts, factory, (err, data) => { + return err ? reject(err) : resolve(data) + }); + }) + } + + try { + this.dispatch(opts, new StreamHandler(opts, factory, callback)); + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque; + queueMicrotask(() => callback(err, { opaque })); + } + } + + var apiStream = stream; + + const { + Readable, + Duplex, + PassThrough + } = require$$0$1; + const { + InvalidArgumentError: InvalidArgumentError$9, + InvalidReturnValueError, + RequestAbortedError: RequestAbortedError$3 + } = errors$1; + const util$9 = util$l; + const { AsyncResource: AsyncResource$2 } = require$$0; + const { addSignal: addSignal$2, removeSignal: removeSignal$2 } = abortSignal; + const assert$2 = require$$3$1; + + const kResume = Symbol('resume'); + + class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }); + + this[kResume] = null; + } + + _read () { + const { [kResume]: resume } = this; + + if (resume) { + this[kResume] = null; + resume(); + } + } + + _destroy (err, callback) { + this._read(); + + callback(err); + } + } + + class PipelineResponse extends Readable { + constructor (resume) { + super({ autoDestroy: true }); + this[kResume] = resume; + } + + _read () { + this[kResume](); + } + + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError$3(); + } + + callback(err); + } + } + + class PipelineHandler extends AsyncResource$2 { + constructor (opts, handler) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError$9('invalid opts') + } + + if (typeof handler !== 'function') { + throw new InvalidArgumentError$9('invalid handler') + } + + const { signal, method, opaque, onInfo, responseHeaders } = opts; + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError$9('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError$9('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError$9('invalid onInfo callback') + } + + super('UNDICI_PIPELINE'); + + this.opaque = opaque || null; + this.responseHeaders = responseHeaders || null; + this.handler = handler; + this.abort = null; + this.context = null; + this.onInfo = onInfo || null; + + this.req = new PipelineRequest().on('error', util$9.nop); + + this.ret = new Duplex({ + readableObjectMode: opts.objectMode, + autoDestroy: true, + read: () => { + const { body } = this; + + if (body && body.resume) { + body.resume(); + } + }, + write: (chunk, encoding, callback) => { + const { req } = this; + + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback(); + } else { + req[kResume] = callback; + } + }, + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this; + + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError$3(); + } + + if (abort && err) { + abort(); + } + + util$9.destroy(body, err); + util$9.destroy(req, err); + util$9.destroy(res, err); + + removeSignal$2(this); + + callback(err); + } + }).on('prefinish', () => { + const { req } = this; + + // Node < 15 does not call _final in same tick. + req.push(null); + }); + + this.res = null; + + addSignal$2(this, signal); + } + + onConnect (abort, context) { + const { ret, res } = this; + + assert$2(!res, 'pipeline cannot be retried'); + + if (ret.destroyed) { + throw new RequestAbortedError$3() + } + + this.abort = abort; + this.context = context; + } + + onHeaders (statusCode, rawHeaders, resume) { + const { opaque, handler, context } = this; + + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util$9.parseRawHeaders(rawHeaders) : util$9.parseHeaders(rawHeaders); + this.onInfo({ statusCode, headers }); + } + return + } + + this.res = new PipelineResponse(resume); + + let body; + try { + this.handler = null; + const headers = this.responseHeaders === 'raw' ? util$9.parseRawHeaders(rawHeaders) : util$9.parseHeaders(rawHeaders); + body = this.runInAsyncScope(handler, null, { + statusCode, + headers, + opaque, + body: this.res, + context + }); + } catch (err) { + this.res.on('error', util$9.nop); + throw err + } + + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') + } + + body + .on('data', (chunk) => { + const { ret, body } = this; + + if (!ret.push(chunk) && body.pause) { + body.pause(); + } + }) + .on('error', (err) => { + const { ret } = this; + + util$9.destroy(ret, err); + }) + .on('end', () => { + const { ret } = this; + + ret.push(null); + }) + .on('close', () => { + const { ret } = this; + + if (!ret._readableState.ended) { + util$9.destroy(ret, new RequestAbortedError$3()); + } + }); + + this.body = body; + } + + onData (chunk) { + const { res } = this; + return res.push(chunk) + } + + onComplete (trailers) { + const { res } = this; + res.push(null); + } + + onError (err) { + const { ret } = this; + this.handler = null; + util$9.destroy(ret, err); + } + } + + function pipeline (opts, handler) { + try { + const pipelineHandler = new PipelineHandler(opts, handler); + this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler); + return pipelineHandler.ret + } catch (err) { + return new PassThrough().destroy(err) + } + } + + var apiPipeline = pipeline; + + const { InvalidArgumentError: InvalidArgumentError$8, RequestAbortedError: RequestAbortedError$2, SocketError: SocketError$1 } = errors$1; + const { AsyncResource: AsyncResource$1 } = require$$0; + const util$8 = util$l; + const { addSignal: addSignal$1, removeSignal: removeSignal$1 } = abortSignal; + const assert$1 = require$$3$1; + + class UpgradeHandler extends AsyncResource$1 { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError$8('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError$8('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts; + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError$8('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_UPGRADE'); + + this.responseHeaders = responseHeaders || null; + this.opaque = opaque || null; + this.callback = callback; + this.abort = null; + this.context = null; + + addSignal$1(this, signal); + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError$2() + } + + this.abort = abort; + this.context = null; + } + + onHeaders () { + throw new SocketError$1('bad upgrade', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this; + + assert$1.strictEqual(statusCode, 101); + + removeSignal$1(this); + + this.callback = null; + const headers = this.responseHeaders === 'raw' ? util$8.parseRawHeaders(rawHeaders) : util$8.parseHeaders(rawHeaders); + this.runInAsyncScope(callback, null, null, { + headers, + socket, + opaque, + context + }); + } + + onError (err) { + const { callback, opaque } = this; + + removeSignal$1(this); + + if (callback) { + this.callback = null; + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }); + }); + } + } + } + + function upgrade (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + upgrade.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }); + }) + } + + try { + const upgradeHandler = new UpgradeHandler(opts, callback); + this.dispatch({ + ...opts, + method: opts.method || 'GET', + upgrade: opts.protocol || 'Websocket' + }, upgradeHandler); + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque; + queueMicrotask(() => callback(err, { opaque })); + } + } + + var apiUpgrade = upgrade; + + const { AsyncResource } = require$$0; + const { InvalidArgumentError: InvalidArgumentError$7, RequestAbortedError: RequestAbortedError$1, SocketError } = errors$1; + const util$7 = util$l; + const { addSignal, removeSignal } = abortSignal; + + class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError$7('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError$7('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts; + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError$7('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_CONNECT'); + + this.opaque = opaque || null; + this.responseHeaders = responseHeaders || null; + this.callback = callback; + this.abort = null; + + addSignal(this, signal); + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError$1() + } + + this.abort = abort; + this.context = context; + } + + onHeaders () { + throw new SocketError('bad connect', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this; + + removeSignal(this); + + this.callback = null; + + let headers = rawHeaders; + // Indicates is an HTTP2Session + if (headers != null) { + headers = this.responseHeaders === 'raw' ? util$7.parseRawHeaders(rawHeaders) : util$7.parseHeaders(rawHeaders); + } + + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + socket, + opaque, + context + }); + } + + onError (err) { + const { callback, opaque } = this; + + removeSignal(this); + + if (callback) { + this.callback = null; + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }); + }); + } + } + } + + function connect (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + connect.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }); + }) + } + + try { + const connectHandler = new ConnectHandler(opts, callback); + this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler); + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque; + queueMicrotask(() => callback(err, { opaque })); + } + } + + var apiConnect = connect; + + api$1.request = apiRequest; + api$1.stream = apiStream; + api$1.pipeline = apiPipeline; + api$1.upgrade = apiUpgrade; + api$1.connect = apiConnect; + + const { UndiciError: UndiciError$1 } = errors$1; + + let MockNotMatchedError$1 = class MockNotMatchedError extends UndiciError$1 { + constructor (message) { + super(message); + Error.captureStackTrace(this, MockNotMatchedError); + this.name = 'MockNotMatchedError'; + this.message = message || 'The request does not match any registered mock dispatches'; + this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED'; + } + }; + + var mockErrors$1 = { + MockNotMatchedError: MockNotMatchedError$1 + }; + + var mockSymbols = { + kAgent: Symbol('agent'), + kOptions: Symbol('options'), + kFactory: Symbol('factory'), + kDispatches: Symbol('dispatches'), + kDispatchKey: Symbol('dispatch key'), + kDefaultHeaders: Symbol('default headers'), + kDefaultTrailers: Symbol('default trailers'), + kContentLength: Symbol('content length'), + kMockAgent: Symbol('mock agent'), + kMockAgentSet: Symbol('mock agent set'), + kMockAgentGet: Symbol('mock agent get'), + kMockDispatch: Symbol('mock dispatch'), + kClose: Symbol('close'), + kOriginalClose: Symbol('original agent close'), + kOrigin: Symbol('origin'), + kIsMockActive: Symbol('is mock active'), + kNetConnect: Symbol('net connect'), + kGetNetConnect: Symbol('get net connect'), + kConnected: Symbol('connected') + }; + + const { MockNotMatchedError } = mockErrors$1; + const { + kDispatches: kDispatches$4, + kMockAgent: kMockAgent$2, + kOriginalDispatch: kOriginalDispatch$2, + kOrigin: kOrigin$2, + kGetNetConnect: kGetNetConnect$1 + } = mockSymbols; + const { buildURL: buildURL$1, nop } = util$l; + const { STATUS_CODES } = require$$17; + const { + types: { + isPromise + } + } = require$$3$2; + + function matchValue$1 (match, value) { + if (typeof match === 'string') { + return match === value + } + if (match instanceof RegExp) { + return match.test(value) + } + if (typeof match === 'function') { + return match(value) === true + } + return false + } + + function lowerCaseEntries (headers) { + return Object.fromEntries( + Object.entries(headers).map(([headerName, headerValue]) => { + return [headerName.toLocaleLowerCase(), headerValue] + }) + ) + } + + /** + * @param {import('../../index').Headers|string[]|Record} headers + * @param {string} key + */ + function getHeaderByName (headers, key) { + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { + return headers[i + 1] + } + } + + return undefined + } else if (typeof headers.get === 'function') { + return headers.get(key) + } else { + return lowerCaseEntries(headers)[key.toLocaleLowerCase()] + } + } + + /** @param {string[]} headers */ + function buildHeadersFromArray (headers) { // fetch HeadersList + const clone = headers.slice(); + const entries = []; + for (let index = 0; index < clone.length; index += 2) { + entries.push([clone[index], clone[index + 1]]); + } + return Object.fromEntries(entries) + } + + function matchHeaders (mockDispatch, headers) { + if (typeof mockDispatch.headers === 'function') { + if (Array.isArray(headers)) { // fetch HeadersList + headers = buildHeadersFromArray(headers); + } + return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) + } + if (typeof mockDispatch.headers === 'undefined') { + return true + } + if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { + return false + } + + for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { + const headerValue = getHeaderByName(headers, matchHeaderName); + + if (!matchValue$1(matchHeaderValue, headerValue)) { + return false + } + } + return true + } + + function safeUrl (path) { + if (typeof path !== 'string') { + return path + } + + const pathSegments = path.split('?'); + + if (pathSegments.length !== 2) { + return path + } + + const qp = new URLSearchParams(pathSegments.pop()); + qp.sort(); + return [...pathSegments, qp.toString()].join('?') + } + + function matchKey (mockDispatch, { path, method, body, headers }) { + const pathMatch = matchValue$1(mockDispatch.path, path); + const methodMatch = matchValue$1(mockDispatch.method, method); + const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue$1(mockDispatch.body, body) : true; + const headersMatch = matchHeaders(mockDispatch, headers); + return pathMatch && methodMatch && bodyMatch && headersMatch + } + + function getResponseData$1 (data) { + if (Buffer.isBuffer(data)) { + return data + } else if (typeof data === 'object') { + return JSON.stringify(data) + } else { + return data.toString() + } + } + + function getMockDispatch (mockDispatches, key) { + const basePath = key.query ? buildURL$1(key.path, key.query) : key.path; + const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath; + + // Match path + let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue$1(safeUrl(path), resolvedPath)); + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) + } + + // Match method + matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue$1(method, key.method)); + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`) + } + + // Match body + matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue$1(body, key.body) : true); + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`) + } + + // Match headers + matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)); + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`) + } + + return matchedMockDispatches[0] + } + + function addMockDispatch$1 (mockDispatches, key, data) { + const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false }; + const replyData = typeof data === 'function' ? { callback: data } : { ...data }; + const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } }; + mockDispatches.push(newMockDispatch); + return newMockDispatch + } + + function deleteMockDispatch (mockDispatches, key) { + const index = mockDispatches.findIndex(dispatch => { + if (!dispatch.consumed) { + return false + } + return matchKey(dispatch, key) + }); + if (index !== -1) { + mockDispatches.splice(index, 1); + } + } + + function buildKey$1 (opts) { + const { path, method, body, headers, query } = opts; + return { + path, + method, + body, + headers, + query + } + } + + function generateKeyValues (data) { + return Object.entries(data).reduce((keyValuePairs, [key, value]) => [ + ...keyValuePairs, + Buffer.from(`${key}`), + Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`) + ], []) + } + + /** + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + * @param {number} statusCode + */ + function getStatusText (statusCode) { + return STATUS_CODES[statusCode] || 'unknown' + } + + async function getResponse (body) { + const buffers = []; + for await (const data of body) { + buffers.push(data); + } + return Buffer.concat(buffers).toString('utf8') + } + + /** + * Mock dispatch function used to simulate undici dispatches + */ + function mockDispatch (opts, handler) { + // Get mock dispatch from built key + const key = buildKey$1(opts); + const mockDispatch = getMockDispatch(this[kDispatches$4], key); + + mockDispatch.timesInvoked++; + + // Here's where we resolve a callback if a callback is present for the dispatch data. + if (mockDispatch.data.callback) { + mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) }; + } + + // Parse mockDispatch data + const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch; + const { timesInvoked, times } = mockDispatch; + + // If it's used up and not persistent, mark as consumed + mockDispatch.consumed = !persist && timesInvoked >= times; + mockDispatch.pending = timesInvoked < times; + + // If specified, trigger dispatch error + if (error !== null) { + deleteMockDispatch(this[kDispatches$4], key); + handler.onError(error); + return true + } + + // Handle the request with a delay if necessary + if (typeof delay === 'number' && delay > 0) { + setTimeout(() => { + handleReply(this[kDispatches$4]); + }, delay); + } else { + handleReply(this[kDispatches$4]); + } + + function handleReply (mockDispatches, _data = data) { + // fetch's HeadersList is a 1D string array + const optsHeaders = Array.isArray(opts.headers) + ? buildHeadersFromArray(opts.headers) + : opts.headers; + const body = typeof _data === 'function' + ? _data({ ...opts, headers: optsHeaders }) + : _data; + + // util.types.isPromise is likely needed for jest. + if (isPromise(body)) { + // If handleReply is asynchronous, throwing an error + // in the callback will reject the promise, rather than + // synchronously throw the error, which breaks some tests. + // Rather, we wait for the callback to resolve if it is a + // promise, and then re-run handleReply with the new body. + body.then((newData) => handleReply(mockDispatches, newData)); + return + } + + const responseData = getResponseData$1(body); + const responseHeaders = generateKeyValues(headers); + const responseTrailers = generateKeyValues(trailers); + + handler.abort = nop; + handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode)); + handler.onData(Buffer.from(responseData)); + handler.onComplete(responseTrailers); + deleteMockDispatch(mockDispatches, key); + } + + function resume () {} + + return true + } + + function buildMockDispatch$2 () { + const agent = this[kMockAgent$2]; + const origin = this[kOrigin$2]; + const originalDispatch = this[kOriginalDispatch$2]; + + return function dispatch (opts, handler) { + if (agent.isMockActive) { + try { + mockDispatch.call(this, opts, handler); + } catch (error) { + if (error instanceof MockNotMatchedError) { + const netConnect = agent[kGetNetConnect$1](); + if (netConnect === false) { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) + } + if (checkNetConnect(netConnect, origin)) { + originalDispatch.call(this, opts, handler); + } else { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) + } + } else { + throw error + } + } + } else { + originalDispatch.call(this, opts, handler); + } + } + } + + function checkNetConnect (netConnect, origin) { + const url = new URL(origin); + if (netConnect === true) { + return true + } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue$1(matcher, url.host))) { + return true + } + return false + } + + function buildMockOptions$1 (opts) { + if (opts) { + const { agent, ...mockOptions } = opts; + return mockOptions + } + } + + var mockUtils = { + getResponseData: getResponseData$1, + getMockDispatch, + addMockDispatch: addMockDispatch$1, + deleteMockDispatch, + buildKey: buildKey$1, + generateKeyValues, + matchValue: matchValue$1, + getResponse, + getStatusText, + mockDispatch, + buildMockDispatch: buildMockDispatch$2, + checkNetConnect, + buildMockOptions: buildMockOptions$1, + getHeaderByName + }; + + var mockInterceptor = {}; + + const {getResponseData, buildKey, addMockDispatch} = mockUtils; + const {kDispatches: kDispatches$3, kDispatchKey, kDefaultHeaders, kDefaultTrailers, kContentLength, kMockDispatch} = mockSymbols; + const {InvalidArgumentError: InvalidArgumentError$6} = errors$1; + const {buildURL} = util$l; + class MockScope { + constructor(mockDispatch) { + this[kMockDispatch] = mockDispatch; + } + delay(waitInMs) { + if (typeof waitInMs !== "number" || !Number.isInteger(waitInMs) || waitInMs <= 0) { + throw new InvalidArgumentError$6("waitInMs must be a valid integer > 0"); + } + this[kMockDispatch].delay = waitInMs; + return this; + } + persist() { + this[kMockDispatch].persist = true; + return this; + } + times(repeatTimes) { + if (typeof repeatTimes !== "number" || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { + throw new InvalidArgumentError$6("repeatTimes must be a valid integer > 0"); + } + this[kMockDispatch].times = repeatTimes; + return this; + } + } + let MockInterceptor$2 = class MockInterceptor { + constructor(opts, mockDispatches) { + if (typeof opts !== "object") { + throw new InvalidArgumentError$6("opts must be an object"); + } + if (typeof opts.path === "undefined") { + throw new InvalidArgumentError$6("opts.path must be defined"); + } + if (typeof opts.method === "undefined") { + opts.method = "GET"; + } + if (typeof opts.path === "string") { + if (opts.query) { + opts.path = buildURL(opts.path, opts.query); + } else { + const parsedURL = new URL(opts.path, "data://"); + opts.path = parsedURL.pathname + parsedURL.search; + } + } + if (typeof opts.method === "string") { + opts.method = opts.method.toUpperCase(); + } + this[kDispatchKey] = buildKey(opts); + this[kDispatches$3] = mockDispatches; + this[kDefaultHeaders] = {}; + this[kDefaultTrailers] = {}; + this[kContentLength] = false; + } + createMockScopeDispatchData(statusCode, data, responseOptions = {}) { + const responseData = getResponseData(data); + const contentLength = this[kContentLength] ? { + "content-length": responseData.length + } : {}; + const headers = { + ...this[kDefaultHeaders], + ...contentLength, + ...responseOptions.headers + }; + const trailers = { + ...this[kDefaultTrailers], + ...responseOptions.trailers + }; + return { + statusCode, + data, + headers, + trailers + }; + } + validateReplyParameters(statusCode, data, responseOptions) { + if (typeof statusCode === "undefined") { + throw new InvalidArgumentError$6("statusCode must be defined"); + } + if (typeof data === "undefined") { + throw new InvalidArgumentError$6("data must be defined"); + } + if (typeof responseOptions !== "object") { + throw new InvalidArgumentError$6("responseOptions must be an object"); + } + } + reply(replyData) { + if (typeof replyData === "function") { + const wrappedDefaultsCallback = opts => { + const resolvedData = replyData(opts); + if (typeof resolvedData !== "object") { + throw new InvalidArgumentError$6("reply options callback must return an object"); + } + const {statusCode, data = "", responseOptions = {}} = resolvedData; + this.validateReplyParameters(statusCode, data, responseOptions); + return { + ...this.createMockScopeDispatchData(statusCode, data, responseOptions) + }; + }; + const newMockDispatch = addMockDispatch(this[kDispatches$3], this[kDispatchKey], wrappedDefaultsCallback); + return new MockScope(newMockDispatch); + } + const [statusCode, data = "", responseOptions = {}] = [...arguments]; + this.validateReplyParameters(statusCode, data, responseOptions); + const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions); + const newMockDispatch = addMockDispatch(this[kDispatches$3], this[kDispatchKey], dispatchData); + return new MockScope(newMockDispatch); + } + replyWithError(error) { + if (typeof error === "undefined") { + throw new InvalidArgumentError$6("error must be defined"); + } + const newMockDispatch = addMockDispatch(this[kDispatches$3], this[kDispatchKey], { + error + }); + return new MockScope(newMockDispatch); + } + defaultReplyHeaders(headers) { + if (typeof headers === "undefined") { + throw new InvalidArgumentError$6("headers must be defined"); + } + this[kDefaultHeaders] = headers; + return this; + } + defaultReplyTrailers(trailers) { + if (typeof trailers === "undefined") { + throw new InvalidArgumentError$6("trailers must be defined"); + } + this[kDefaultTrailers] = trailers; + return this; + } + replyContentLength() { + this[kContentLength] = true; + return this; + } + }; + mockInterceptor.MockInterceptor = MockInterceptor$2; + mockInterceptor.MockScope = MockScope; + + const { promisify: promisify$1 } = require$$3$2; + const Client$1 = client; + const { buildMockDispatch: buildMockDispatch$1 } = mockUtils; + const { + kDispatches: kDispatches$2, + kMockAgent: kMockAgent$1, + kClose: kClose$2, + kOriginalClose: kOriginalClose$1, + kOrigin: kOrigin$1, + kOriginalDispatch: kOriginalDispatch$1, + kConnected: kConnected$1 + } = mockSymbols; + const { MockInterceptor: MockInterceptor$1 } = mockInterceptor; + const Symbols$1 = symbols$4; + const { InvalidArgumentError: InvalidArgumentError$5 } = errors$1; + + /** + * MockClient provides an API that extends the Client to influence the mockDispatches. + */ + let MockClient$2 = class MockClient extends Client$1 { + constructor (origin, opts) { + super(origin, opts); + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError$5('Argument opts.agent must implement Agent') + } + + this[kMockAgent$1] = opts.agent; + this[kOrigin$1] = origin; + this[kDispatches$2] = []; + this[kConnected$1] = 1; + this[kOriginalDispatch$1] = this.dispatch; + this[kOriginalClose$1] = this.close.bind(this); + + this.dispatch = buildMockDispatch$1.call(this); + this.close = this[kClose$2]; + } + + get [Symbols$1.kConnected] () { + return this[kConnected$1] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor$1(opts, this[kDispatches$2]) + } + + async [kClose$2] () { + await promisify$1(this[kOriginalClose$1])(); + this[kConnected$1] = 0; + this[kMockAgent$1][Symbols$1.kClients].delete(this[kOrigin$1]); + } + }; + + var mockClient = MockClient$2; + + const { promisify } = require$$3$2; + const Pool$2 = pool; + const { buildMockDispatch } = mockUtils; + const { + kDispatches: kDispatches$1, + kMockAgent, + kClose: kClose$1, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected + } = mockSymbols; + const { MockInterceptor } = mockInterceptor; + const Symbols = symbols$4; + const { InvalidArgumentError: InvalidArgumentError$4 } = errors$1; + + /** + * MockPool provides an API that extends the Pool to influence the mockDispatches. + */ + let MockPool$2 = class MockPool extends Pool$2 { + constructor (origin, opts) { + super(origin, opts); + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError$4('Argument opts.agent must implement Agent') + } + + this[kMockAgent] = opts.agent; + this[kOrigin] = origin; + this[kDispatches$1] = []; + this[kConnected] = 1; + this[kOriginalDispatch] = this.dispatch; + this[kOriginalClose] = this.close.bind(this); + + this.dispatch = buildMockDispatch.call(this); + this.close = this[kClose$1]; + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches$1]) + } + + async [kClose$1] () { + await promisify(this[kOriginalClose])(); + this[kConnected] = 0; + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]); + } + }; + + var mockPool = MockPool$2; + + const singulars = { + pronoun: 'it', + is: 'is', + was: 'was', + this: 'this' + }; + + const plurals = { + pronoun: 'they', + is: 'are', + was: 'were', + this: 'these' + }; + + var pluralizer = class Pluralizer { + constructor (singular, plural) { + this.singular = singular; + this.plural = plural; + } + + pluralize (count) { + const one = count === 1; + const keys = one ? singulars : plurals; + const noun = one ? this.singular : this.plural; + return { ...keys, count, noun } + } + }; + + function noop(){} + + var _polyfillNode_console = global$3.console ? global$3.console : { + log: noop, + info: noop, + warn: noop, + error: noop, + dir: noop, + assert: noop, + time: noop, + timeEnd: noop, + trace: noop + }; + + var _polyfillNode_console$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + default: _polyfillNode_console + }); + + var require$$1$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_console$1); + + const { Transform } = require$$0$1; + const { Console } = require$$1$1; + + /** + * Gets the output of `console.table(…)` as a string. + */ + var pendingInterceptorsFormatter = class PendingInterceptorsFormatter { + constructor ({ disableColors } = {}) { + this.transform = new Transform({ + transform (chunk, _enc, cb) { + cb(null, chunk); + } + }); + + this.logger = new Console({ + stdout: this.transform, + inspectOptions: { + colors: !disableColors && !browser$1$1.env.CI + } + }); + } + + format (pendingInterceptors) { + const withPrettyHeaders = pendingInterceptors.map( + ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ + Method: method, + Origin: origin, + Path: path, + 'Status code': statusCode, + Persistent: persist ? '✅' : '❌', + Invocations: timesInvoked, + Remaining: persist ? Infinity : times - timesInvoked + })); + + this.logger.table(withPrettyHeaders); + return this.transform.read().toString() + } + }; + + const { kClients } = symbols$4; + const Agent$3 = agent; + const { + kAgent: kAgent$1, + kMockAgentSet, + kMockAgentGet, + kDispatches, + kIsMockActive, + kNetConnect, + kGetNetConnect, + kOptions, + kFactory + } = mockSymbols; + const MockClient$1 = mockClient; + const MockPool$1 = mockPool; + const { matchValue, buildMockOptions } = mockUtils; + const { InvalidArgumentError: InvalidArgumentError$3, UndiciError } = errors$1; + const Dispatcher$1 = dispatcher; + const Pluralizer = pluralizer; + const PendingInterceptorsFormatter = pendingInterceptorsFormatter; + + class FakeWeakRef { + constructor (value) { + this.value = value; + } + + deref () { + return this.value + } + } + + let MockAgent$1 = class MockAgent extends Dispatcher$1 { + constructor (opts) { + super(opts); + + this[kNetConnect] = true; + this[kIsMockActive] = true; + + // Instantiate Agent and encapsulate + if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) { + throw new InvalidArgumentError$3('Argument opts.agent must implement Agent') + } + const agent = opts && opts.agent ? opts.agent : new Agent$3(opts); + this[kAgent$1] = agent; + + this[kClients] = agent[kClients]; + this[kOptions] = buildMockOptions(opts); + } + + get (origin) { + let dispatcher = this[kMockAgentGet](origin); + + if (!dispatcher) { + dispatcher = this[kFactory](origin); + this[kMockAgentSet](origin, dispatcher); + } + return dispatcher + } + + dispatch (opts, handler) { + // Call MockAgent.get to perform additional setup before dispatching as normal + this.get(opts.origin); + return this[kAgent$1].dispatch(opts, handler) + } + + async close () { + await this[kAgent$1].close(); + this[kClients].clear(); + } + + deactivate () { + this[kIsMockActive] = false; + } + + activate () { + this[kIsMockActive] = true; + } + + enableNetConnect (matcher) { + if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { + if (Array.isArray(this[kNetConnect])) { + this[kNetConnect].push(matcher); + } else { + this[kNetConnect] = [matcher]; + } + } else if (typeof matcher === 'undefined') { + this[kNetConnect] = true; + } else { + throw new InvalidArgumentError$3('Unsupported matcher. Must be one of String|Function|RegExp.') + } + } + + disableNetConnect () { + this[kNetConnect] = false; + } + + // This is required to bypass issues caused by using global symbols - see: + // https://github.com/nodejs/undici/issues/1447 + get isMockActive () { + return this[kIsMockActive] + } + + [kMockAgentSet] (origin, dispatcher) { + this[kClients].set(origin, new FakeWeakRef(dispatcher)); + } + + [kFactory] (origin) { + const mockOptions = Object.assign({ agent: this }, this[kOptions]); + return this[kOptions] && this[kOptions].connections === 1 + ? new MockClient$1(origin, mockOptions) + : new MockPool$1(origin, mockOptions) + } + + [kMockAgentGet] (origin) { + // First check if we can immediately find it + const ref = this[kClients].get(origin); + if (ref) { + return ref.deref() + } + + // If the origin is not a string create a dummy parent pool and return to user + if (typeof origin !== 'string') { + const dispatcher = this[kFactory]('http://localhost:9999'); + this[kMockAgentSet](origin, dispatcher); + return dispatcher + } + + // If we match, create a pool and assign the same dispatches + for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) { + const nonExplicitDispatcher = nonExplicitRef.deref(); + if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { + const dispatcher = this[kFactory](origin); + this[kMockAgentSet](origin, dispatcher); + dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches]; + return dispatcher + } + } + } + + [kGetNetConnect] () { + return this[kNetConnect] + } + + pendingInterceptors () { + const mockAgentClients = this[kClients]; + + return Array.from(mockAgentClients.entries()) + .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin }))) + .filter(({ pending }) => pending) + } + + assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { + const pending = this.pendingInterceptors(); + + if (pending.length === 0) { + return + } + + const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length); + + throw new UndiciError(` +${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: + +${pendingInterceptorsFormatter.format(pending)} +`.trim()) + } + }; + + var mockAgent = MockAgent$1; + + var require$$1 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_url$1); + + const { kProxy, kClose, kDestroy, kInterceptors } = symbols$4; + const { URL: URL$1 } = require$$1; + const Agent$2 = agent; + const Pool$1 = pool; + const DispatcherBase = dispatcherBase; + const { InvalidArgumentError: InvalidArgumentError$2, RequestAbortedError } = errors$1; + const buildConnector$1 = connect$2; + + const kAgent = Symbol('proxy agent'); + const kClient = Symbol('proxy client'); + const kProxyHeaders = Symbol('proxy headers'); + const kRequestTls = Symbol('request tls settings'); + const kProxyTls = Symbol('proxy tls settings'); + const kConnectEndpoint = Symbol('connect endpoint function'); + + function defaultProtocolPort (protocol) { + return protocol === 'https:' ? 443 : 80 + } + + function buildProxyOptions (opts) { + if (typeof opts === 'string') { + opts = { uri: opts }; + } + + if (!opts || !opts.uri) { + throw new InvalidArgumentError$2('Proxy opts.uri is mandatory') + } + + return { + uri: opts.uri, + protocol: opts.protocol || 'https' + } + } + + function defaultFactory (origin, opts) { + return new Pool$1(origin, opts) + } + + let ProxyAgent$1 = class ProxyAgent extends DispatcherBase { + constructor (opts) { + super(opts); + this[kProxy] = buildProxyOptions(opts); + this[kAgent] = new Agent$2(opts); + this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) + ? opts.interceptors.ProxyAgent + : []; + + if (typeof opts === 'string') { + opts = { uri: opts }; + } + + if (!opts || !opts.uri) { + throw new InvalidArgumentError$2('Proxy opts.uri is mandatory') + } + + const { clientFactory = defaultFactory } = opts; + + if (typeof clientFactory !== 'function') { + throw new InvalidArgumentError$2('Proxy opts.clientFactory must be a function.') + } + + this[kRequestTls] = opts.requestTls; + this[kProxyTls] = opts.proxyTls; + this[kProxyHeaders] = opts.headers || {}; + + if (opts.auth && opts.token) { + throw new InvalidArgumentError$2('opts.auth cannot be used in combination with opts.token') + } else if (opts.auth) { + /* @deprecated in favour of opts.token */ + this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}`; + } else if (opts.token) { + this[kProxyHeaders]['proxy-authorization'] = opts.token; + } + + const resolvedUrl = new URL$1(opts.uri); + const { origin, port, host } = resolvedUrl; + + const connect = buildConnector$1({ ...opts.proxyTls }); + this[kConnectEndpoint] = buildConnector$1({ ...opts.requestTls }); + this[kClient] = clientFactory(resolvedUrl, { connect }); + this[kAgent] = new Agent$2({ + ...opts, + connect: async (opts, callback) => { + let requestedHost = opts.host; + if (!opts.port) { + requestedHost += `:${defaultProtocolPort(opts.protocol)}`; + } + try { + const { socket, statusCode } = await this[kClient].connect({ + origin, + port, + path: requestedHost, + signal: opts.signal, + headers: { + ...this[kProxyHeaders], + host + } + }); + if (statusCode !== 200) { + socket.on('error', () => {}).destroy(); + callback(new RequestAbortedError('Proxy response !== 200 when HTTP Tunneling')); + } + if (opts.protocol !== 'https:') { + callback(null, socket); + return + } + let servername; + if (this[kRequestTls]) { + servername = this[kRequestTls].servername; + } else { + servername = opts.servername; + } + this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback); + } catch (err) { + callback(err); + } + } + }); + } + + dispatch (opts, handler) { + const { host } = new URL$1(opts.origin); + const headers = buildHeaders(opts.headers); + throwIfProxyAuthIsSent(headers); + return this[kAgent].dispatch( + { + ...opts, + headers: { + ...headers, + host + } + }, + handler + ) + } + + async [kClose] () { + await this[kAgent].close(); + await this[kClient].close(); + } + + async [kDestroy] () { + await this[kAgent].destroy(); + await this[kClient].destroy(); + } + }; + + /** + * @param {string[] | Record} headers + * @returns {Record} + */ + function buildHeaders (headers) { + // When using undici.fetch, the headers list is stored + // as an array. + if (Array.isArray(headers)) { + /** @type {Record} */ + const headersPair = {}; + + for (let i = 0; i < headers.length; i += 2) { + headersPair[headers[i]] = headers[i + 1]; + } + + return headersPair + } + + return headers + } + + /** + * @param {Record} headers + * + * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers + * Nevertheless, it was changed and to avoid a security vulnerability by end users + * this check was created. + * It should be removed in the next major version for performance reasons + */ + function throwIfProxyAuthIsSent (headers) { + const existProxyAuth = headers && Object.keys(headers) + .find((key) => key.toLowerCase() === 'proxy-authorization'); + if (existProxyAuth) { + throw new InvalidArgumentError$2('Proxy-Authorization should be sent in ProxyAgent constructor') + } + } + + var proxyAgent = ProxyAgent$1; + + // We include a version number for the Dispatcher API. In case of breaking changes, + // this version number must be increased to avoid conflicts. + const globalDispatcher = Symbol.for('undici.globalDispatcher.1'); + const { InvalidArgumentError: InvalidArgumentError$1 } = errors$1; + const Agent$1 = agent; + + if (getGlobalDispatcher$1() === undefined) { + setGlobalDispatcher$1(new Agent$1()); + } + + function setGlobalDispatcher$1 (agent) { + if (!agent || typeof agent.dispatch !== 'function') { + throw new InvalidArgumentError$1('Argument agent must implement Agent') + } + Object.defineProperty(globalThis, globalDispatcher, { + value: agent, + writable: true, + enumerable: false, + configurable: false + }); + } + + function getGlobalDispatcher$1 () { + return globalThis[globalDispatcher] + } + + var global$1 = { + setGlobalDispatcher: setGlobalDispatcher$1, + getGlobalDispatcher: getGlobalDispatcher$1 + }; + + var DecoratorHandler_1 = class DecoratorHandler { + constructor (handler) { + this.handler = handler; + } + + onConnect (...args) { + return this.handler.onConnect(...args) + } + + onError (...args) { + return this.handler.onError(...args) + } + + onUpgrade (...args) { + return this.handler.onUpgrade(...args) + } + + onHeaders (...args) { + return this.handler.onHeaders(...args) + } + + onData (...args) { + return this.handler.onData(...args) + } + + onComplete (...args) { + return this.handler.onComplete(...args) + } + + onBodySent (...args) { + return this.handler.onBodySent(...args) + } + }; + + var headers; + var hasRequiredHeaders; + + function requireHeaders () { + if (hasRequiredHeaders) return headers; + hasRequiredHeaders = 1; + + const { kHeadersList } = symbols$4; + const { kGuard } = requireSymbols$3(); + const { kEnumerableProperty } = util$l; + const { + makeIterator, + isValidHeaderName, + isValidHeaderValue + } = requireUtil$4(); + const { webidl } = requireWebidl(); + const assert = require$$3$1; + + const kHeadersMap = Symbol('headers map'); + const kHeadersSortedMap = Symbol('headers map sorted'); + + /** + * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize + * @param {string} potentialValue + */ + function headerValueNormalize (potentialValue) { + // To normalize a byte sequence potentialValue, remove + // any leading and trailing HTTP whitespace bytes from + // potentialValue. + + // Trimming the end with `.replace()` and a RegExp is typically subject to + // ReDoS. This is safer and faster. + let i = potentialValue.length; + while (/[\r\n\t ]/.test(potentialValue.charAt(--i))); + return potentialValue.slice(0, i + 1).replace(/^[\r\n\t ]+/, '') + } + + function fill (headers, object) { + // To fill a Headers object headers with a given object object, run these steps: + + // 1. If object is a sequence, then for each header in object: + // Note: webidl conversion to array has already been done. + if (Array.isArray(object)) { + for (const header of object) { + // 1. If header does not contain exactly two items, then throw a TypeError. + if (header.length !== 2) { + throw webidl.errors.exception({ + header: 'Headers constructor', + message: `expected name/value pair to be length 2, found ${header.length}.` + }) + } + + // 2. Append (header’s first item, header’s second item) to headers. + headers.append(header[0], header[1]); + } + } else if (typeof object === 'object' && object !== null) { + // Note: null should throw + + // 2. Otherwise, object is a record, then for each key → value in object, + // append (key, value) to headers + for (const [key, value] of Object.entries(object)) { + headers.append(key, value); + } + } else { + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) + } + } + + class HeadersList { + /** @type {[string, string][]|null} */ + cookies = null + + constructor (init) { + if (init instanceof HeadersList) { + this[kHeadersMap] = new Map(init[kHeadersMap]); + this[kHeadersSortedMap] = init[kHeadersSortedMap]; + this.cookies = init.cookies; + } else { + this[kHeadersMap] = new Map(init); + this[kHeadersSortedMap] = null; + } + } + + // https://fetch.spec.whatwg.org/#header-list-contains + contains (name) { + // A header list list contains a header name name if list + // contains a header whose name is a byte-case-insensitive + // match for name. + name = name.toLowerCase(); + + return this[kHeadersMap].has(name) + } + + clear () { + this[kHeadersMap].clear(); + this[kHeadersSortedMap] = null; + this.cookies = null; + } + + // https://fetch.spec.whatwg.org/#concept-header-list-append + append (name, value) { + this[kHeadersSortedMap] = null; + + // 1. If list contains name, then set name to the first such + // header’s name. + const lowercaseName = name.toLowerCase(); + const exists = this[kHeadersMap].get(lowercaseName); + + // 2. Append (name, value) to list. + if (exists) { + const delimiter = lowercaseName === 'cookie' ? '; ' : ', '; + this[kHeadersMap].set(lowercaseName, { + name: exists.name, + value: `${exists.value}${delimiter}${value}` + }); + } else { + this[kHeadersMap].set(lowercaseName, { name, value }); + } + + if (lowercaseName === 'set-cookie') { + this.cookies ??= []; + this.cookies.push(value); + } + } + + // https://fetch.spec.whatwg.org/#concept-header-list-set + set (name, value) { + this[kHeadersSortedMap] = null; + const lowercaseName = name.toLowerCase(); + + if (lowercaseName === 'set-cookie') { + this.cookies = [value]; + } + + // 1. If list contains name, then set the value of + // the first such header to value and remove the + // others. + // 2. Otherwise, append header (name, value) to list. + return this[kHeadersMap].set(lowercaseName, { name, value }) + } + + // https://fetch.spec.whatwg.org/#concept-header-list-delete + delete (name) { + this[kHeadersSortedMap] = null; + + name = name.toLowerCase(); + + if (name === 'set-cookie') { + this.cookies = null; + } + + return this[kHeadersMap].delete(name) + } + + // https://fetch.spec.whatwg.org/#concept-header-list-get + get (name) { + // 1. If list does not contain name, then return null. + if (!this.contains(name)) { + return null + } + + // 2. Return the values of all headers in list whose name + // is a byte-case-insensitive match for name, + // separated from each other by 0x2C 0x20, in order. + return this[kHeadersMap].get(name.toLowerCase())?.value ?? null + } + + * [Symbol.iterator] () { + // use the lowercased name + for (const [name, { value }] of this[kHeadersMap]) { + yield [name, value]; + } + } + + get entries () { + const headers = {}; + + if (this[kHeadersMap].size) { + for (const { name, value } of this[kHeadersMap].values()) { + headers[name] = value; + } + } + + return headers + } + } + + // https://fetch.spec.whatwg.org/#headers-class + class Headers { + constructor (init = undefined) { + this[kHeadersList] = new HeadersList(); + + // The new Headers(init) constructor steps are: + + // 1. Set this’s guard to "none". + this[kGuard] = 'none'; + + // 2. If init is given, then fill this with init. + if (init !== undefined) { + init = webidl.converters.HeadersInit(init); + fill(this, init); + } + } + + // https://fetch.spec.whatwg.org/#dom-headers-append + append (name, value) { + webidl.brandCheck(this, Headers); + + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }); + + name = webidl.converters.ByteString(name); + value = webidl.converters.ByteString(value); + + // 1. Normalize value. + value = headerValueNormalize(value); + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value, + type: 'header value' + }) + } + + // 3. If headers’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if headers’s guard is "request" and name is a + // forbidden header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') ; + + // 6. Otherwise, if headers’s guard is "response" and name is a + // forbidden response-header name, return. + + // 7. Append (name, value) to headers’s header list. + // 8. If headers’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from headers + return this[kHeadersList].append(name, value) + } + + // https://fetch.spec.whatwg.org/#dom-headers-delete + delete (name) { + webidl.brandCheck(this, Headers); + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' }); + + name = webidl.converters.ByteString(name); + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.delete', + value: name, + type: 'header name' + }) + } + + // 2. If this’s guard is "immutable", then throw a TypeError. + // 3. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 4. Otherwise, if this’s guard is "request-no-cors", name + // is not a no-CORS-safelisted request-header name, and + // name is not a privileged no-CORS request-header name, + // return. + // 5. Otherwise, if this’s guard is "response" and name is + // a forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') ; + + // 6. If this’s header list does not contain name, then + // return. + if (!this[kHeadersList].contains(name)) { + return + } + + // 7. Delete name from this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this. + return this[kHeadersList].delete(name) + } + + // https://fetch.spec.whatwg.org/#dom-headers-get + get (name) { + webidl.brandCheck(this, Headers); + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }); + + name = webidl.converters.ByteString(name); + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.get', + value: name, + type: 'header name' + }) + } + + // 2. Return the result of getting name from this’s header + // list. + return this[kHeadersList].get(name) + } + + // https://fetch.spec.whatwg.org/#dom-headers-has + has (name) { + webidl.brandCheck(this, Headers); + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }); + + name = webidl.converters.ByteString(name); + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.has', + value: name, + type: 'header name' + }) + } + + // 2. Return true if this’s header list contains name; + // otherwise false. + return this[kHeadersList].contains(name) + } + + // https://fetch.spec.whatwg.org/#dom-headers-set + set (name, value) { + webidl.brandCheck(this, Headers); + + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }); + + name = webidl.converters.ByteString(name); + value = webidl.converters.ByteString(value); + + // 1. Normalize value. + value = headerValueNormalize(value); + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.set', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.set', + value, + type: 'header value' + }) + } + + // 3. If this’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 5. Otherwise, if this’s guard is "request-no-cors" and + // name/value is not a no-CORS-safelisted request-header, + // return. + // 6. Otherwise, if this’s guard is "response" and name is a + // forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') ; + + // 7. Set (name, value) in this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this + return this[kHeadersList].set(name, value) + } + + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie + getSetCookie () { + webidl.brandCheck(this, Headers); + + // 1. If this’s header list does not contain `Set-Cookie`, then return « ». + // 2. Return the values of all headers in this’s header list whose name is + // a byte-case-insensitive match for `Set-Cookie`, in order. + + const list = this[kHeadersList].cookies; + + if (list) { + return [...list] + } + + return [] + } + + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + get [kHeadersSortedMap] () { + if (this[kHeadersList][kHeadersSortedMap]) { + return this[kHeadersList][kHeadersSortedMap] + } + + // 1. Let headers be an empty list of headers with the key being the name + // and value the value. + const headers = []; + + // 2. Let names be the result of convert header names to a sorted-lowercase + // set with all the names of the headers in list. + const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1); + const cookies = this[kHeadersList].cookies; + + // 3. For each name of names: + for (const [name, value] of names) { + // 1. If name is `set-cookie`, then: + if (name === 'set-cookie') { + // 1. Let values be a list of all values of headers in list whose name + // is a byte-case-insensitive match for name, in order. + + // 2. For each value of values: + // 1. Append (name, value) to headers. + for (const value of cookies) { + headers.push([name, value]); + } + } else { + // 2. Otherwise: + + // 1. Let value be the result of getting name from list. + + // 2. Assert: value is non-null. + assert(value !== null); + + // 3. Append (name, value) to headers. + headers.push([name, value]); + } + } + + this[kHeadersList][kHeadersSortedMap] = headers; + + // 4. Return headers. + return headers + } + + keys () { + webidl.brandCheck(this, Headers); + + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key' + ) + } + + values () { + webidl.brandCheck(this, Headers); + + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'value' + ) + } + + entries () { + webidl.brandCheck(this, Headers); + + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key+value' + ) + } + + /** + * @param {(value: string, key: string, self: Headers) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, Headers); + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }); + + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." + ) + } + + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]); + } + } + + [Symbol.for('nodejs.util.inspect.custom')] () { + webidl.brandCheck(this, Headers); + + return this[kHeadersList] + } + } + + Headers.prototype[Symbol.iterator] = Headers.prototype.entries; + + Object.defineProperties(Headers.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + getSetCookie: kEnumerableProperty, + keys: kEnumerableProperty, + values: kEnumerableProperty, + entries: kEnumerableProperty, + forEach: kEnumerableProperty, + [Symbol.iterator]: { enumerable: false }, + [Symbol.toStringTag]: { + value: 'Headers', + configurable: true + } + }); + + webidl.converters.HeadersInit = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (V[Symbol.iterator]) { + return webidl.converters['sequence>'](V) + } + + return webidl.converters['record'](V) + } + + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) + }; + + headers = { + fill, + Headers, + HeadersList + }; + return headers; + } + + var response; + var hasRequiredResponse; + + function requireResponse () { + if (hasRequiredResponse) return response; + hasRequiredResponse = 1; + + const { Headers, HeadersList, fill } = requireHeaders(); + const { extractBody, cloneBody, mixinBody } = requireBody(); + const util = util$l; + const { kEnumerableProperty } = util; + const { + isValidReasonPhrase, + isCancelled, + isAborted, + isBlobLike, + serializeJavascriptValueToJSONString, + isErrorLike, + isomorphicEncode + } = requireUtil$4(); + const { + redirectStatus, + nullBodyStatus, + DOMException + } = requireConstants$3(); + const { kState, kHeaders, kGuard, kRealm } = requireSymbols$3(); + const { webidl } = requireWebidl(); + const { FormData } = requireFormdata(); + const { getGlobalOrigin } = requireGlobal(); + const { URLSerializer } = requireDataURL(); + const { kHeadersList } = symbols$4; + const assert = require$$3$1; + const { types } = require$$3$2; + + const ReadableStream = globalThis.ReadableStream || require$$14.ReadableStream; + + // https://fetch.spec.whatwg.org/#response-class + class Response { + // Creates network error Response. + static error () { + // TODO + const relevantRealm = { settingsObject: {} }; + + // The static error() method steps are to return the result of creating a + // Response object, given a new network error, "immutable", and this’s + // relevant Realm. + const responseObject = new Response(); + responseObject[kState] = makeNetworkError(); + responseObject[kRealm] = relevantRealm; + responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList; + responseObject[kHeaders][kGuard] = 'immutable'; + responseObject[kHeaders][kRealm] = relevantRealm; + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response-json + static json (data, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' }); + + if (init !== null) { + init = webidl.converters.ResponseInit(init); + } + + // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. + const bytes = new TextEncoder('utf-8').encode( + serializeJavascriptValueToJSONString(data) + ); + + // 2. Let body be the result of extracting bytes. + const body = extractBody(bytes); + + // 3. Let responseObject be the result of creating a Response object, given a new response, + // "response", and this’s relevant Realm. + const relevantRealm = { settingsObject: {} }; + const responseObject = new Response(); + responseObject[kRealm] = relevantRealm; + responseObject[kHeaders][kGuard] = 'response'; + responseObject[kHeaders][kRealm] = relevantRealm; + + // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). + initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }); + + // 5. Return responseObject. + return responseObject + } + + // Creates a redirect Response that redirects to url with status status. + static redirect (url, status = 302) { + const relevantRealm = { settingsObject: {} }; + + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' }); + + url = webidl.converters.USVString(url); + status = webidl.converters['unsigned short'](status); + + // 1. Let parsedURL be the result of parsing url with current settings + // object’s API base URL. + // 2. If parsedURL is failure, then throw a TypeError. + // TODO: base-URL? + let parsedURL; + try { + parsedURL = new URL(url, getGlobalOrigin()); + } catch (err) { + throw Object.assign(new TypeError('Failed to parse URL from ' + url), { + cause: err + }) + } + + // 3. If status is not a redirect status, then throw a RangeError. + if (!redirectStatus.includes(status)) { + throw new RangeError('Invalid status code ' + status) + } + + // 4. Let responseObject be the result of creating a Response object, + // given a new response, "immutable", and this’s relevant Realm. + const responseObject = new Response(); + responseObject[kRealm] = relevantRealm; + responseObject[kHeaders][kGuard] = 'immutable'; + responseObject[kHeaders][kRealm] = relevantRealm; + + // 5. Set responseObject’s response’s status to status. + responseObject[kState].status = status; + + // 6. Let value be parsedURL, serialized and isomorphic encoded. + const value = isomorphicEncode(URLSerializer(parsedURL)); + + // 7. Append `Location`/value to responseObject’s response’s header list. + responseObject[kState].headersList.append('location', value); + + // 8. Return responseObject. + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response + constructor (body = null, init = {}) { + if (body !== null) { + body = webidl.converters.BodyInit(body); + } + + init = webidl.converters.ResponseInit(init); + + // TODO + this[kRealm] = { settingsObject: {} }; + + // 1. Set this’s response to a new response. + this[kState] = makeResponse({}); + + // 2. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is this’s response’s header list and guard + // is "response". + this[kHeaders] = new Headers(); + this[kHeaders][kGuard] = 'response'; + this[kHeaders][kHeadersList] = this[kState].headersList; + this[kHeaders][kRealm] = this[kRealm]; + + // 3. Let bodyWithType be null. + let bodyWithType = null; + + // 4. If body is non-null, then set bodyWithType to the result of extracting body. + if (body != null) { + const [extractedBody, type] = extractBody(body); + bodyWithType = { body: extractedBody, type }; + } + + // 5. Perform initialize a response given this, init, and bodyWithType. + initializeResponse(this, init, bodyWithType); + } + + // Returns response’s type, e.g., "cors". + get type () { + webidl.brandCheck(this, Response); + + // The type getter steps are to return this’s response’s type. + return this[kState].type + } + + // Returns response’s URL, if it has one; otherwise the empty string. + get url () { + webidl.brandCheck(this, Response); + + const urlList = this[kState].urlList; + + // The url getter steps are to return the empty string if this’s + // response’s URL is null; otherwise this’s response’s URL, + // serialized with exclude fragment set to true. + const url = urlList[urlList.length - 1] ?? null; + + if (url === null) { + return '' + } + + return URLSerializer(url, true) + } + + // Returns whether response was obtained through a redirect. + get redirected () { + webidl.brandCheck(this, Response); + + // The redirected getter steps are to return true if this’s response’s URL + // list has more than one item; otherwise false. + return this[kState].urlList.length > 1 + } + + // Returns response’s status. + get status () { + webidl.brandCheck(this, Response); + + // The status getter steps are to return this’s response’s status. + return this[kState].status + } + + // Returns whether response’s status is an ok status. + get ok () { + webidl.brandCheck(this, Response); + + // The ok getter steps are to return true if this’s response’s status is an + // ok status; otherwise false. + return this[kState].status >= 200 && this[kState].status <= 299 + } + + // Returns response’s status message. + get statusText () { + webidl.brandCheck(this, Response); + + // The statusText getter steps are to return this’s response’s status + // message. + return this[kState].statusText + } + + // Returns response’s headers as Headers. + get headers () { + webidl.brandCheck(this, Response); + + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } + + get body () { + webidl.brandCheck(this, Response); + + return this[kState].body ? this[kState].body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Response); + + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + + // Returns a clone of response. + clone () { + webidl.brandCheck(this, Response); + + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || (this.body && this.body.locked)) { + throw webidl.errors.exception({ + header: 'Response.clone', + message: 'Body has already been consumed.' + }) + } + + // 2. Let clonedResponse be the result of cloning this’s response. + const clonedResponse = cloneResponse(this[kState]); + + // 3. Return the result of creating a Response object, given + // clonedResponse, this’s headers’s guard, and this’s relevant Realm. + const clonedResponseObject = new Response(); + clonedResponseObject[kState] = clonedResponse; + clonedResponseObject[kRealm] = this[kRealm]; + clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList; + clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard]; + clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm]; + + return clonedResponseObject + } + } + + mixinBody(Response); + + Object.defineProperties(Response.prototype, { + type: kEnumerableProperty, + url: kEnumerableProperty, + status: kEnumerableProperty, + ok: kEnumerableProperty, + redirected: kEnumerableProperty, + statusText: kEnumerableProperty, + headers: kEnumerableProperty, + clone: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Response', + configurable: true + } + }); + + Object.defineProperties(Response, { + json: kEnumerableProperty, + redirect: kEnumerableProperty, + error: kEnumerableProperty + }); + + // https://fetch.spec.whatwg.org/#concept-response-clone + function cloneResponse (response) { + // To clone a response response, run these steps: + + // 1. If response is a filtered response, then return a new identical + // filtered response whose internal response is a clone of response’s + // internal response. + if (response.internalResponse) { + return filterResponse( + cloneResponse(response.internalResponse), + response.type + ) + } + + // 2. Let newResponse be a copy of response, except for its body. + const newResponse = makeResponse({ ...response, body: null }); + + // 3. If response’s body is non-null, then set newResponse’s body to the + // result of cloning response’s body. + if (response.body != null) { + newResponse.body = cloneBody(response.body); + } + + // 4. Return newResponse. + return newResponse + } + + function makeResponse (init) { + return { + aborted: false, + rangeRequested: false, + timingAllowPassed: false, + requestIncludesCredentials: false, + type: 'default', + status: 200, + timingInfo: null, + cacheState: '', + statusText: '', + ...init, + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList(), + urlList: init.urlList ? [...init.urlList] : [] + } + } + + function makeNetworkError (reason) { + const isError = isErrorLike(reason); + return makeResponse({ + type: 'error', + status: 0, + error: isError + ? reason + : new Error(reason ? String(reason) : reason), + aborted: reason && reason.name === 'AbortError' + }) + } + + function makeFilteredResponse (response, state) { + state = { + internalResponse: response, + ...state + }; + + return new Proxy(response, { + get (target, p) { + return p in state ? state[p] : target[p] + }, + set (target, p, value) { + assert(!(p in state)); + target[p] = value; + return true + } + }) + } + + // https://fetch.spec.whatwg.org/#concept-filtered-response + function filterResponse (response, type) { + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (type === 'basic') { + // A basic filtered response is a filtered response whose type is "basic" + // and header list excludes any headers in internal response’s header list + // whose name is a forbidden response-header name. + + // Note: undici does not implement forbidden response-header names + return makeFilteredResponse(response, { + type: 'basic', + headersList: response.headersList + }) + } else if (type === 'cors') { + // A CORS filtered response is a filtered response whose type is "cors" + // and header list excludes any headers in internal response’s header + // list whose name is not a CORS-safelisted response-header name, given + // internal response’s CORS-exposed header-name list. + + // Note: undici does not implement CORS-safelisted response-header names + return makeFilteredResponse(response, { + type: 'cors', + headersList: response.headersList + }) + } else if (type === 'opaque') { + // An opaque filtered response is a filtered response whose type is + // "opaque", URL list is the empty list, status is 0, status message + // is the empty byte sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaque', + urlList: Object.freeze([]), + status: 0, + statusText: '', + body: null + }) + } else if (type === 'opaqueredirect') { + // An opaque-redirect filtered response is a filtered response whose type + // is "opaqueredirect", status is 0, status message is the empty byte + // sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaqueredirect', + status: 0, + statusText: '', + headersList: [], + body: null + }) + } else { + assert(false); + } + } + + // https://fetch.spec.whatwg.org/#appropriate-network-error + function makeAppropriateNetworkError (fetchParams, err = null) { + // 1. Assert: fetchParams is canceled. + assert(isCancelled(fetchParams)); + + // 2. Return an aborted network error if fetchParams is aborted; + // otherwise return a network error. + return isAborted(fetchParams) + ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) + : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) + } + + // https://whatpr.org/fetch/1392.html#initialize-a-response + function initializeResponse (response, init, body) { + // 1. If init["status"] is not in the range 200 to 599, inclusive, then + // throw a RangeError. + if (init.status !== null && (init.status < 200 || init.status > 599)) { + throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') + } + + // 2. If init["statusText"] does not match the reason-phrase token production, + // then throw a TypeError. + if ('statusText' in init && init.statusText != null) { + // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: + // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) + if (!isValidReasonPhrase(String(init.statusText))) { + throw new TypeError('Invalid statusText') + } + } + + // 3. Set response’s response’s status to init["status"]. + if ('status' in init && init.status != null) { + response[kState].status = init.status; + } + + // 4. Set response’s response’s status message to init["statusText"]. + if ('statusText' in init && init.statusText != null) { + response[kState].statusText = init.statusText; + } + + // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. + if ('headers' in init && init.headers != null) { + fill(response[kHeaders], init.headers); + } + + // 6. If body was given, then: + if (body) { + // 1. If response's status is a null body status, then throw a TypeError. + if (nullBodyStatus.includes(response.status)) { + throw webidl.errors.exception({ + header: 'Response constructor', + message: 'Invalid response status code ' + response.status + }) + } + + // 2. Set response's body to body's body. + response[kState].body = body.body; + + // 3. If body's type is non-null and response's header list does not contain + // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. + if (body.type != null && !response[kState].headersList.contains('Content-Type')) { + response[kState].headersList.append('content-type', body.type); + } + } + } + + webidl.converters.ReadableStream = webidl.interfaceConverter( + ReadableStream + ); + + webidl.converters.FormData = webidl.interfaceConverter( + FormData + ); + + webidl.converters.URLSearchParams = webidl.interfaceConverter( + URLSearchParams + ); + + // https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit + webidl.converters.XMLHttpRequestBodyInit = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } + + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if ( + types.isAnyArrayBuffer(V) || + types.isTypedArray(V) || + types.isDataView(V) + ) { + return webidl.converters.BufferSource(V) + } + + if (util.isFormDataLike(V)) { + return webidl.converters.FormData(V, { strict: false }) + } + + if (V instanceof URLSearchParams) { + return webidl.converters.URLSearchParams(V) + } + + return webidl.converters.DOMString(V) + }; + + // https://fetch.spec.whatwg.org/#bodyinit + webidl.converters.BodyInit = function (V) { + if (V instanceof ReadableStream) { + return webidl.converters.ReadableStream(V) + } + + // Note: the spec doesn't include async iterables, + // this is an undici extension. + if (V?.[Symbol.asyncIterator]) { + return V + } + + return webidl.converters.XMLHttpRequestBodyInit(V) + }; + + webidl.converters.ResponseInit = webidl.dictionaryConverter([ + { + key: 'status', + converter: webidl.converters['unsigned short'], + defaultValue: 200 + }, + { + key: 'statusText', + converter: webidl.converters.ByteString, + defaultValue: '' + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + } + ]); + + response = { + makeNetworkError, + makeResponse, + makeAppropriateNetworkError, + filterResponse, + Response, + cloneResponse + }; + return response; + } + + /* globals AbortController */ + + var request; + var hasRequiredRequest; + + function requireRequest () { + if (hasRequiredRequest) return request; + hasRequiredRequest = 1; + + const { extractBody, mixinBody, cloneBody } = requireBody(); + const { Headers, fill: fillHeaders, HeadersList } = requireHeaders(); + const { FinalizationRegistry } = dispatcherWeakref(); + const util = util$l; + const { + isValidHTTPToken, + sameOrigin, + normalizeMethod, + makePolicyContainer + } = requireUtil$4(); + const { + forbiddenMethods, + corsSafeListedMethods, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + requestDuplex + } = requireConstants$3(); + const { kEnumerableProperty } = util; + const { kHeaders, kSignal, kState, kGuard, kRealm } = requireSymbols$3(); + const { webidl } = requireWebidl(); + const { getGlobalOrigin } = requireGlobal(); + const { URLSerializer } = requireDataURL(); + const { kHeadersList } = symbols$4; + const assert = require$$3$1; + const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = require$$10$1; + + let TransformStream = globalThis.TransformStream; + + const kInit = Symbol('init'); + const kAbortController = Symbol('abortController'); + + const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { + signal.removeEventListener('abort', abort); + }); + + // https://fetch.spec.whatwg.org/#request-class + class Request { + // https://fetch.spec.whatwg.org/#dom-request + constructor (input, init = {}) { + if (input === kInit) { + return + } + + webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }); + + input = webidl.converters.RequestInfo(input); + init = webidl.converters.RequestInit(init); + + // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object + this[kRealm] = { + settingsObject: { + baseUrl: getGlobalOrigin(), + get origin () { + return this.baseUrl?.origin + }, + policyContainer: makePolicyContainer() + } + }; + + // 1. Let request be null. + let request = null; + + // 2. Let fallbackMode be null. + let fallbackMode = null; + + // 3. Let baseURL be this’s relevant settings object’s API base URL. + const baseUrl = this[kRealm].settingsObject.baseUrl; + + // 4. Let signal be null. + let signal = null; + + // 5. If input is a string, then: + if (typeof input === 'string') { + // 1. Let parsedURL be the result of parsing input with baseURL. + // 2. If parsedURL is failure, then throw a TypeError. + let parsedURL; + try { + parsedURL = new URL(input, baseUrl); + } catch (err) { + throw new TypeError('Failed to parse URL from ' + input, { cause: err }) + } + + // 3. If parsedURL includes credentials, then throw a TypeError. + if (parsedURL.username || parsedURL.password) { + throw new TypeError( + 'Request cannot be constructed from a URL that includes credentials: ' + + input + ) + } + + // 4. Set request to a new request whose URL is parsedURL. + request = makeRequest({ urlList: [parsedURL] }); + + // 5. Set fallbackMode to "cors". + fallbackMode = 'cors'; + } else { + // 6. Otherwise: + + // 7. Assert: input is a Request object. + assert(input instanceof Request); + + // 8. Set request to input’s request. + request = input[kState]; + + // 9. Set signal to input’s signal. + signal = input[kSignal]; + } + + // 7. Let origin be this’s relevant settings object’s origin. + const origin = this[kRealm].settingsObject.origin; + + // 8. Let window be "client". + let window = 'client'; + + // 9. If request’s window is an environment settings object and its origin + // is same origin with origin, then set window to request’s window. + if ( + request.window?.constructor?.name === 'EnvironmentSettingsObject' && + sameOrigin(request.window, origin) + ) { + window = request.window; + } + + // 10. If init["window"] exists and is non-null, then throw a TypeError. + if (init.window != null) { + throw new TypeError(`'window' option '${window}' must be null`) + } + + // 11. If init["window"] exists, then set window to "no-window". + if ('window' in init) { + window = 'no-window'; + } + + // 12. Set request to a new request with the following properties: + request = makeRequest({ + // URL request’s URL. + // undici implementation note: this is set as the first item in request's urlList in makeRequest + // method request’s method. + method: request.method, + // header list A copy of request’s header list. + // undici implementation note: headersList is cloned in makeRequest + headersList: request.headersList, + // unsafe-request flag Set. + unsafeRequest: request.unsafeRequest, + // client This’s relevant settings object. + client: this[kRealm].settingsObject, + // window window. + window, + // priority request’s priority. + priority: request.priority, + // origin request’s origin. The propagation of the origin is only significant for navigation requests + // being handled by a service worker. In this scenario a request can have an origin that is different + // from the current client. + origin: request.origin, + // referrer request’s referrer. + referrer: request.referrer, + // referrer policy request’s referrer policy. + referrerPolicy: request.referrerPolicy, + // mode request’s mode. + mode: request.mode, + // credentials mode request’s credentials mode. + credentials: request.credentials, + // cache mode request’s cache mode. + cache: request.cache, + // redirect mode request’s redirect mode. + redirect: request.redirect, + // integrity metadata request’s integrity metadata. + integrity: request.integrity, + // keepalive request’s keepalive. + keepalive: request.keepalive, + // reload-navigation flag request’s reload-navigation flag. + reloadNavigation: request.reloadNavigation, + // history-navigation flag request’s history-navigation flag. + historyNavigation: request.historyNavigation, + // URL list A clone of request’s URL list. + urlList: [...request.urlList] + }); + + // 13. If init is not empty, then: + if (Object.keys(init).length > 0) { + // 1. If request’s mode is "navigate", then set it to "same-origin". + if (request.mode === 'navigate') { + request.mode = 'same-origin'; + } + + // 2. Unset request’s reload-navigation flag. + request.reloadNavigation = false; + + // 3. Unset request’s history-navigation flag. + request.historyNavigation = false; + + // 4. Set request’s origin to "client". + request.origin = 'client'; + + // 5. Set request’s referrer to "client" + request.referrer = 'client'; + + // 6. Set request’s referrer policy to the empty string. + request.referrerPolicy = ''; + + // 7. Set request’s URL to request’s current URL. + request.url = request.urlList[request.urlList.length - 1]; + + // 8. Set request’s URL list to « request’s URL ». + request.urlList = [request.url]; + } + + // 14. If init["referrer"] exists, then: + if (init.referrer !== undefined) { + // 1. Let referrer be init["referrer"]. + const referrer = init.referrer; + + // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". + if (referrer === '') { + request.referrer = 'no-referrer'; + } else { + // 1. Let parsedReferrer be the result of parsing referrer with + // baseURL. + // 2. If parsedReferrer is failure, then throw a TypeError. + let parsedReferrer; + try { + parsedReferrer = new URL(referrer, baseUrl); + } catch (err) { + throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) + } + + // 3. If one of the following is true + // - parsedReferrer’s scheme is "about" and path is the string "client" + // - parsedReferrer’s origin is not same origin with origin + // then set request’s referrer to "client". + if ( + (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || + (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl)) + ) { + request.referrer = 'client'; + } else { + // 4. Otherwise, set request’s referrer to parsedReferrer. + request.referrer = parsedReferrer; + } + } + } + + // 15. If init["referrerPolicy"] exists, then set request’s referrer policy + // to it. + if (init.referrerPolicy !== undefined) { + request.referrerPolicy = init.referrerPolicy; + } + + // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. + let mode; + if (init.mode !== undefined) { + mode = init.mode; + } else { + mode = fallbackMode; + } + + // 17. If mode is "navigate", then throw a TypeError. + if (mode === 'navigate') { + throw webidl.errors.exception({ + header: 'Request constructor', + message: 'invalid request mode navigate.' + }) + } + + // 18. If mode is non-null, set request’s mode to mode. + if (mode != null) { + request.mode = mode; + } + + // 19. If init["credentials"] exists, then set request’s credentials mode + // to it. + if (init.credentials !== undefined) { + request.credentials = init.credentials; + } + + // 18. If init["cache"] exists, then set request’s cache mode to it. + if (init.cache !== undefined) { + request.cache = init.cache; + } + + // 21. If request’s cache mode is "only-if-cached" and request’s mode is + // not "same-origin", then throw a TypeError. + if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { + throw new TypeError( + "'only-if-cached' can be set only with 'same-origin' mode" + ) + } + + // 22. If init["redirect"] exists, then set request’s redirect mode to it. + if (init.redirect !== undefined) { + request.redirect = init.redirect; + } + + // 23. If init["integrity"] exists, then set request’s integrity metadata to it. + if (init.integrity !== undefined && init.integrity != null) { + request.integrity = String(init.integrity); + } + + // 24. If init["keepalive"] exists, then set request’s keepalive to it. + if (init.keepalive !== undefined) { + request.keepalive = Boolean(init.keepalive); + } + + // 25. If init["method"] exists, then: + if (init.method !== undefined) { + // 1. Let method be init["method"]. + let method = init.method; + + // 2. If method is not a method or method is a forbidden method, then + // throw a TypeError. + if (!isValidHTTPToken(init.method)) { + throw TypeError(`'${init.method}' is not a valid HTTP method.`) + } + + if (forbiddenMethods.indexOf(method.toUpperCase()) !== -1) { + throw TypeError(`'${init.method}' HTTP method is unsupported.`) + } + + // 3. Normalize method. + method = normalizeMethod(init.method); + + // 4. Set request’s method to method. + request.method = method; + } + + // 26. If init["signal"] exists, then set signal to it. + if (init.signal !== undefined) { + signal = init.signal; + } + + // 27. Set this’s request to request. + this[kState] = request; + + // 28. Set this’s signal to a new AbortSignal object with this’s relevant + // Realm. + // TODO: could this be simplified with AbortSignal.any + // (https://dom.spec.whatwg.org/#dom-abortsignal-any) + const ac = new AbortController(); + this[kSignal] = ac.signal; + this[kSignal][kRealm] = this[kRealm]; + + // 29. If signal is not null, then make this’s signal follow signal. + if (signal != null) { + if ( + !signal || + typeof signal.aborted !== 'boolean' || + typeof signal.addEventListener !== 'function' + ) { + throw new TypeError( + "Failed to construct 'Request': member signal is not of type AbortSignal." + ) + } + + if (signal.aborted) { + ac.abort(signal.reason); + } else { + // Keep a strong ref to ac while request object + // is alive. This is needed to prevent AbortController + // from being prematurely garbage collected. + // See, https://github.com/nodejs/undici/issues/1926. + this[kAbortController] = ac; + + const acRef = new WeakRef(ac); + const abort = function () { + const ac = acRef.deref(); + if (ac !== undefined) { + ac.abort(this.reason); + } + }; + + // Third-party AbortControllers may not work with these. + // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619. + try { + // If the max amount of listeners is equal to the default, increase it + // This is only available in node >= v19.9.0 + if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) { + setMaxListeners(100, signal); + } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) { + setMaxListeners(100, signal); + } + } catch {} + + util.addAbortListener(signal, abort); + requestFinalizer.register(ac, { signal, abort }); + } + } + + // 30. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is request’s header list and guard is + // "request". + this[kHeaders] = new Headers(); + this[kHeaders][kHeadersList] = request.headersList; + this[kHeaders][kGuard] = 'request'; + this[kHeaders][kRealm] = this[kRealm]; + + // 31. If this’s request’s mode is "no-cors", then: + if (mode === 'no-cors') { + // 1. If this’s request’s method is not a CORS-safelisted method, + // then throw a TypeError. + if (!corsSafeListedMethods.includes(request.method)) { + throw new TypeError( + `'${request.method} is unsupported in no-cors mode.` + ) + } + + // 2. Set this’s headers’s guard to "request-no-cors". + this[kHeaders][kGuard] = 'request-no-cors'; + } + + // 32. If init is not empty, then: + if (Object.keys(init).length !== 0) { + // 1. Let headers be a copy of this’s headers and its associated header + // list. + let headers = new Headers(this[kHeaders]); + + // 2. If init["headers"] exists, then set headers to init["headers"]. + if (init.headers !== undefined) { + headers = init.headers; + } + + // 3. Empty this’s headers’s header list. + this[kHeaders][kHeadersList].clear(); + + // 4. If headers is a Headers object, then for each header in its header + // list, append header’s name/header’s value to this’s headers. + if (headers.constructor.name === 'Headers') { + for (const [key, val] of headers) { + this[kHeaders].append(key, val); + } + } else { + // 5. Otherwise, fill this’s headers with headers. + fillHeaders(this[kHeaders], headers); + } + } + + // 33. Let inputBody be input’s request’s body if input is a Request + // object; otherwise null. + const inputBody = input instanceof Request ? input[kState].body : null; + + // 34. If either init["body"] exists and is non-null or inputBody is + // non-null, and request’s method is `GET` or `HEAD`, then throw a + // TypeError. + if ( + (init.body != null || inputBody != null) && + (request.method === 'GET' || request.method === 'HEAD') + ) { + throw new TypeError('Request with GET/HEAD method cannot have body.') + } + + // 35. Let initBody be null. + let initBody = null; + + // 36. If init["body"] exists and is non-null, then: + if (init.body != null) { + // 1. Let Content-Type be null. + // 2. Set initBody and Content-Type to the result of extracting + // init["body"], with keepalive set to request’s keepalive. + const [extractedBody, contentType] = extractBody( + init.body, + request.keepalive + ); + initBody = extractedBody; + + // 3, If Content-Type is non-null and this’s headers’s header list does + // not contain `Content-Type`, then append `Content-Type`/Content-Type to + // this’s headers. + if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) { + this[kHeaders].append('content-type', contentType); + } + } + + // 37. Let inputOrInitBody be initBody if it is non-null; otherwise + // inputBody. + const inputOrInitBody = initBody ?? inputBody; + + // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is + // null, then: + if (inputOrInitBody != null && inputOrInitBody.source == null) { + // 1. If initBody is non-null and init["duplex"] does not exist, + // then throw a TypeError. + if (initBody != null && init.duplex == null) { + throw new TypeError('RequestInit: duplex option is required when sending a body.') + } + + // 2. If this’s request’s mode is neither "same-origin" nor "cors", + // then throw a TypeError. + if (request.mode !== 'same-origin' && request.mode !== 'cors') { + throw new TypeError( + 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' + ) + } + + // 3. Set this’s request’s use-CORS-preflight flag. + request.useCORSPreflightFlag = true; + } + + // 39. Let finalBody be inputOrInitBody. + let finalBody = inputOrInitBody; + + // 40. If initBody is null and inputBody is non-null, then: + if (initBody == null && inputBody != null) { + // 1. If input is unusable, then throw a TypeError. + if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) { + throw new TypeError( + 'Cannot construct a Request with a Request object that has already been used.' + ) + } + + // 2. Set finalBody to the result of creating a proxy for inputBody. + if (!TransformStream) { + TransformStream = require$$14.TransformStream; + } + + // https://streams.spec.whatwg.org/#readablestream-create-a-proxy + const identityTransform = new TransformStream(); + inputBody.stream.pipeThrough(identityTransform); + finalBody = { + source: inputBody.source, + length: inputBody.length, + stream: identityTransform.readable + }; + } + + // 41. Set this’s request’s body to finalBody. + this[kState].body = finalBody; + } + + // Returns request’s HTTP method, which is "GET" by default. + get method () { + webidl.brandCheck(this, Request); + + // The method getter steps are to return this’s request’s method. + return this[kState].method + } + + // Returns the URL of request as a string. + get url () { + webidl.brandCheck(this, Request); + + // The url getter steps are to return this’s request’s URL, serialized. + return URLSerializer(this[kState].url) + } + + // Returns a Headers object consisting of the headers associated with request. + // Note that headers added in the network layer by the user agent will not + // be accounted for in this object, e.g., the "Host" header. + get headers () { + webidl.brandCheck(this, Request); + + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } + + // Returns the kind of resource requested by request, e.g., "document" + // or "script". + get destination () { + webidl.brandCheck(this, Request); + + // The destination getter are to return this’s request’s destination. + return this[kState].destination + } + + // Returns the referrer of request. Its value can be a same-origin URL if + // explicitly set in init, the empty string to indicate no referrer, and + // "about:client" when defaulting to the global’s default. This is used + // during fetching to determine the value of the `Referer` header of the + // request being made. + get referrer () { + webidl.brandCheck(this, Request); + + // 1. If this’s request’s referrer is "no-referrer", then return the + // empty string. + if (this[kState].referrer === 'no-referrer') { + return '' + } + + // 2. If this’s request’s referrer is "client", then return + // "about:client". + if (this[kState].referrer === 'client') { + return 'about:client' + } + + // Return this’s request’s referrer, serialized. + return this[kState].referrer.toString() + } + + // Returns the referrer policy associated with request. + // This is used during fetching to compute the value of the request’s + // referrer. + get referrerPolicy () { + webidl.brandCheck(this, Request); + + // The referrerPolicy getter steps are to return this’s request’s referrer policy. + return this[kState].referrerPolicy + } + + // Returns the mode associated with request, which is a string indicating + // whether the request will use CORS, or will be restricted to same-origin + // URLs. + get mode () { + webidl.brandCheck(this, Request); + + // The mode getter steps are to return this’s request’s mode. + return this[kState].mode + } + + // Returns the credentials mode associated with request, + // which is a string indicating whether credentials will be sent with the + // request always, never, or only when sent to a same-origin URL. + get credentials () { + // The credentials getter steps are to return this’s request’s credentials mode. + return this[kState].credentials + } + + // Returns the cache mode associated with request, + // which is a string indicating how the request will + // interact with the browser’s cache when fetching. + get cache () { + webidl.brandCheck(this, Request); + + // The cache getter steps are to return this’s request’s cache mode. + return this[kState].cache + } + + // Returns the redirect mode associated with request, + // which is a string indicating how redirects for the + // request will be handled during fetching. A request + // will follow redirects by default. + get redirect () { + webidl.brandCheck(this, Request); + + // The redirect getter steps are to return this’s request’s redirect mode. + return this[kState].redirect + } + + // Returns request’s subresource integrity metadata, which is a + // cryptographic hash of the resource being fetched. Its value + // consists of multiple hashes separated by whitespace. [SRI] + get integrity () { + webidl.brandCheck(this, Request); + + // The integrity getter steps are to return this’s request’s integrity + // metadata. + return this[kState].integrity + } + + // Returns a boolean indicating whether or not request can outlive the + // global in which it was created. + get keepalive () { + webidl.brandCheck(this, Request); + + // The keepalive getter steps are to return this’s request’s keepalive. + return this[kState].keepalive + } + + // Returns a boolean indicating whether or not request is for a reload + // navigation. + get isReloadNavigation () { + webidl.brandCheck(this, Request); + + // The isReloadNavigation getter steps are to return true if this’s + // request’s reload-navigation flag is set; otherwise false. + return this[kState].reloadNavigation + } + + // Returns a boolean indicating whether or not request is for a history + // navigation (a.k.a. back-foward navigation). + get isHistoryNavigation () { + webidl.brandCheck(this, Request); + + // The isHistoryNavigation getter steps are to return true if this’s request’s + // history-navigation flag is set; otherwise false. + return this[kState].historyNavigation + } + + // Returns the signal associated with request, which is an AbortSignal + // object indicating whether or not request has been aborted, and its + // abort event handler. + get signal () { + webidl.brandCheck(this, Request); + + // The signal getter steps are to return this’s signal. + return this[kSignal] + } + + get body () { + webidl.brandCheck(this, Request); + + return this[kState].body ? this[kState].body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Request); + + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + + get duplex () { + webidl.brandCheck(this, Request); + + return 'half' + } + + // Returns a clone of request. + clone () { + webidl.brandCheck(this, Request); + + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || this.body?.locked) { + throw new TypeError('unusable') + } + + // 2. Let clonedRequest be the result of cloning this’s request. + const clonedRequest = cloneRequest(this[kState]); + + // 3. Let clonedRequestObject be the result of creating a Request object, + // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. + const clonedRequestObject = new Request(kInit); + clonedRequestObject[kState] = clonedRequest; + clonedRequestObject[kRealm] = this[kRealm]; + clonedRequestObject[kHeaders] = new Headers(); + clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList; + clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard]; + clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm]; + + // 4. Make clonedRequestObject’s signal follow this’s signal. + const ac = new AbortController(); + if (this.signal.aborted) { + ac.abort(this.signal.reason); + } else { + util.addAbortListener( + this.signal, + () => { + ac.abort(this.signal.reason); + } + ); + } + clonedRequestObject[kSignal] = ac.signal; + + // 4. Return clonedRequestObject. + return clonedRequestObject + } + } + + mixinBody(Request); + + function makeRequest (init) { + // https://fetch.spec.whatwg.org/#requests + const request = { + method: 'GET', + localURLsOnly: false, + unsafeRequest: false, + body: null, + client: null, + reservedClient: null, + replacesClientId: '', + window: 'client', + keepalive: false, + serviceWorkers: 'all', + initiator: '', + destination: '', + priority: null, + origin: 'client', + policyContainer: 'client', + referrer: 'client', + referrerPolicy: '', + mode: 'no-cors', + useCORSPreflightFlag: false, + credentials: 'same-origin', + useCredentials: false, + cache: 'default', + redirect: 'follow', + integrity: '', + cryptoGraphicsNonceMetadata: '', + parserMetadata: '', + reloadNavigation: false, + historyNavigation: false, + userActivation: false, + taintedOrigin: false, + redirectCount: 0, + responseTainting: 'basic', + preventNoCacheCacheControlHeaderModification: false, + done: false, + timingAllowFailed: false, + ...init, + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList() + }; + request.url = request.urlList[0]; + return request + } + + // https://fetch.spec.whatwg.org/#concept-request-clone + function cloneRequest (request) { + // To clone a request request, run these steps: + + // 1. Let newRequest be a copy of request, except for its body. + const newRequest = makeRequest({ ...request, body: null }); + + // 2. If request’s body is non-null, set newRequest’s body to the + // result of cloning request’s body. + if (request.body != null) { + newRequest.body = cloneBody(request.body); + } + + // 3. Return newRequest. + return newRequest + } + + Object.defineProperties(Request.prototype, { + method: kEnumerableProperty, + url: kEnumerableProperty, + headers: kEnumerableProperty, + redirect: kEnumerableProperty, + clone: kEnumerableProperty, + signal: kEnumerableProperty, + duplex: kEnumerableProperty, + destination: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + isHistoryNavigation: kEnumerableProperty, + isReloadNavigation: kEnumerableProperty, + keepalive: kEnumerableProperty, + integrity: kEnumerableProperty, + cache: kEnumerableProperty, + credentials: kEnumerableProperty, + attribute: kEnumerableProperty, + referrerPolicy: kEnumerableProperty, + referrer: kEnumerableProperty, + mode: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Request', + configurable: true + } + }); + + webidl.converters.Request = webidl.interfaceConverter( + Request + ); + + // https://fetch.spec.whatwg.org/#requestinfo + webidl.converters.RequestInfo = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } + + if (V instanceof Request) { + return webidl.converters.Request(V) + } + + return webidl.converters.USVString(V) + }; + + webidl.converters.AbortSignal = webidl.interfaceConverter( + AbortSignal + ); + + // https://fetch.spec.whatwg.org/#requestinit + webidl.converters.RequestInit = webidl.dictionaryConverter([ + { + key: 'method', + converter: webidl.converters.ByteString + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + }, + { + key: 'body', + converter: webidl.nullableConverter( + webidl.converters.BodyInit + ) + }, + { + key: 'referrer', + converter: webidl.converters.USVString + }, + { + key: 'referrerPolicy', + converter: webidl.converters.DOMString, + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy + allowedValues: referrerPolicy + }, + { + key: 'mode', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#concept-request-mode + allowedValues: requestMode + }, + { + key: 'credentials', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcredentials + allowedValues: requestCredentials + }, + { + key: 'cache', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcache + allowedValues: requestCache + }, + { + key: 'redirect', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestredirect + allowedValues: requestRedirect + }, + { + key: 'integrity', + converter: webidl.converters.DOMString + }, + { + key: 'keepalive', + converter: webidl.converters.boolean + }, + { + key: 'signal', + converter: webidl.nullableConverter( + (signal) => webidl.converters.AbortSignal( + signal, + { strict: false } + ) + ) + }, + { + key: 'window', + converter: webidl.converters.any + }, + { + key: 'duplex', + converter: webidl.converters.DOMString, + allowedValues: requestDuplex + } + ]); + + request = { Request, makeRequest }; + return request; + } + + var msg = { + 2: 'need dictionary', /* Z_NEED_DICT 2 */ + 1: 'stream end', /* Z_STREAM_END 1 */ + 0: '', /* Z_OK 0 */ + '-1': 'file error', /* Z_ERRNO (-1) */ + '-2': 'stream error', /* Z_STREAM_ERROR (-2) */ + '-3': 'data error', /* Z_DATA_ERROR (-3) */ + '-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */ + '-5': 'buffer error', /* Z_BUF_ERROR (-5) */ + '-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */ + }; + + function ZStream() { + /* next input byte */ + this.input = null; // JS specific, because we have no pointers + this.next_in = 0; + /* number of bytes available at input */ + this.avail_in = 0; + /* total number of input bytes read so far */ + this.total_in = 0; + /* next output byte should be put there */ + this.output = null; // JS specific, because we have no pointers + this.next_out = 0; + /* remaining free space at output */ + this.avail_out = 0; + /* total number of bytes output so far */ + this.total_out = 0; + /* last error message, NULL if no error */ + this.msg = ''/*Z_NULL*/; + /* not visible by applications */ + this.state = null; + /* best guess about the data type: binary or text */ + this.data_type = 2/*Z_UNKNOWN*/; + /* adler32 value of the uncompressed data */ + this.adler = 0; + } + + function arraySet(dest, src, src_offs, len, dest_offs) { + if (src.subarray && dest.subarray) { + dest.set(src.subarray(src_offs, src_offs + len), dest_offs); + return; + } + // Fallback to ordinary array + for (var i = 0; i < len; i++) { + dest[dest_offs + i] = src[src_offs + i]; + } + } + + + var Buf8 = Uint8Array; + var Buf16 = Uint16Array; + var Buf32 = Int32Array; + // Enable/Disable typed arrays use, for testing + // + + /* Public constants ==========================================================*/ + /* ===========================================================================*/ + + + //var Z_FILTERED = 1; + //var Z_HUFFMAN_ONLY = 2; + //var Z_RLE = 3; + var Z_FIXED$2 = 4; + //var Z_DEFAULT_STRATEGY = 0; + + /* Possible values of the data_type field (though see inflate()) */ + var Z_BINARY$1 = 0; + var Z_TEXT$1 = 1; + //var Z_ASCII = 1; // = Z_TEXT + var Z_UNKNOWN$2 = 2; + + /*============================================================================*/ + + + function zero$1(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } + } + + // From zutil.h + + var STORED_BLOCK = 0; + var STATIC_TREES = 1; + var DYN_TREES = 2; + /* The three kinds of block type */ + + var MIN_MATCH$1 = 3; + var MAX_MATCH$1 = 258; + /* The minimum and maximum match lengths */ + + // From deflate.h + /* =========================================================================== + * Internal compression state. + */ + + var LENGTH_CODES$1 = 29; + /* number of length codes, not counting the special END_BLOCK code */ + + var LITERALS$1 = 256; + /* number of literal bytes 0..255 */ + + var L_CODES$1 = LITERALS$1 + 1 + LENGTH_CODES$1; + /* number of Literal or Length codes, including the END_BLOCK code */ + + var D_CODES$1 = 30; + /* number of distance codes */ + + var BL_CODES$1 = 19; + /* number of codes used to transfer the bit lengths */ + + var HEAP_SIZE$1 = 2 * L_CODES$1 + 1; + /* maximum heap size */ + + var MAX_BITS$1 = 15; + /* All codes must not exceed MAX_BITS bits */ + + var Buf_size = 16; + /* size of bit buffer in bi_buf */ + + + /* =========================================================================== + * Constants + */ + + var MAX_BL_BITS = 7; + /* Bit length codes must not exceed MAX_BL_BITS bits */ + + var END_BLOCK = 256; + /* end of block literal code */ + + var REP_3_6 = 16; + /* repeat previous bit length 3-6 times (2 bits of repeat count) */ + + var REPZ_3_10 = 17; + /* repeat a zero length 3-10 times (3 bits of repeat count) */ + + var REPZ_11_138 = 18; + /* repeat a zero length 11-138 times (7 bits of repeat count) */ + + /* eslint-disable comma-spacing,array-bracket-spacing */ + var extra_lbits = /* extra bits for each length code */ [0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0]; + + var extra_dbits = /* extra bits for each distance code */ [0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13]; + + var extra_blbits = /* extra bits for each bit length code */ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 7]; + + var bl_order = [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + /* eslint-enable comma-spacing,array-bracket-spacing */ + + /* The lengths of the bit length codes are sent in order of decreasing + * probability, to avoid transmitting the lengths for unused bit length codes. + */ + + /* =========================================================================== + * Local data. These are initialized only once. + */ + + // We pre-fill arrays with 0 to avoid uninitialized gaps + + var DIST_CODE_LEN = 512; /* see definition of array dist_code below */ + + // !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1 + var static_ltree = new Array((L_CODES$1 + 2) * 2); + zero$1(static_ltree); + /* The static literal tree. Since the bit lengths are imposed, there is no + * need for the L_CODES extra codes used during heap construction. However + * The codes 286 and 287 are needed to build a canonical tree (see _tr_init + * below). + */ + + var static_dtree = new Array(D_CODES$1 * 2); + zero$1(static_dtree); + /* The static distance tree. (Actually a trivial tree since all codes use + * 5 bits.) + */ + + var _dist_code = new Array(DIST_CODE_LEN); + zero$1(_dist_code); + /* Distance codes. The first 256 values correspond to the distances + * 3 .. 258, the last 256 values correspond to the top 8 bits of + * the 15 bit distances. + */ + + var _length_code = new Array(MAX_MATCH$1 - MIN_MATCH$1 + 1); + zero$1(_length_code); + /* length code for each normalized match length (0 == MIN_MATCH) */ + + var base_length = new Array(LENGTH_CODES$1); + zero$1(base_length); + /* First normalized length for each code (0 = MIN_MATCH) */ + + var base_dist = new Array(D_CODES$1); + zero$1(base_dist); + /* First normalized distance for each code (0 = distance of 1) */ + + + function StaticTreeDesc(static_tree, extra_bits, extra_base, elems, max_length) { + + this.static_tree = static_tree; /* static tree or NULL */ + this.extra_bits = extra_bits; /* extra bits for each code or NULL */ + this.extra_base = extra_base; /* base index for extra_bits */ + this.elems = elems; /* max number of elements in the tree */ + this.max_length = max_length; /* max bit length for the codes */ + + // show if `static_tree` has data or dummy - needed for monomorphic objects + this.has_stree = static_tree && static_tree.length; + } + + + var static_l_desc; + var static_d_desc; + var static_bl_desc; + + + function TreeDesc(dyn_tree, stat_desc) { + this.dyn_tree = dyn_tree; /* the dynamic tree */ + this.max_code = 0; /* largest code with non zero frequency */ + this.stat_desc = stat_desc; /* the corresponding static tree */ + } + + + + function d_code(dist) { + return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)]; + } + + + /* =========================================================================== + * Output a short LSB first on the stream. + * IN assertion: there is enough room in pendingBuf. + */ + function put_short(s, w) { + // put_byte(s, (uch)((w) & 0xff)); + // put_byte(s, (uch)((ush)(w) >> 8)); + s.pending_buf[s.pending++] = (w) & 0xff; + s.pending_buf[s.pending++] = (w >>> 8) & 0xff; + } + + + /* =========================================================================== + * Send a value on a given number of bits. + * IN assertion: length <= 16 and value fits in length bits. + */ + function send_bits(s, value, length) { + if (s.bi_valid > (Buf_size - length)) { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + put_short(s, s.bi_buf); + s.bi_buf = value >> (Buf_size - s.bi_valid); + s.bi_valid += length - Buf_size; + } else { + s.bi_buf |= (value << s.bi_valid) & 0xffff; + s.bi_valid += length; + } + } + + + function send_code(s, c, tree) { + send_bits(s, tree[c * 2] /*.Code*/ , tree[c * 2 + 1] /*.Len*/ ); + } + + + /* =========================================================================== + * Reverse the first len bits of a code, using straightforward code (a faster + * method would use a table) + * IN assertion: 1 <= len <= 15 + */ + function bi_reverse(code, len) { + var res = 0; + do { + res |= code & 1; + code >>>= 1; + res <<= 1; + } while (--len > 0); + return res >>> 1; + } + + + /* =========================================================================== + * Flush the bit buffer, keeping at most 7 bits in it. + */ + function bi_flush(s) { + if (s.bi_valid === 16) { + put_short(s, s.bi_buf); + s.bi_buf = 0; + s.bi_valid = 0; + + } else if (s.bi_valid >= 8) { + s.pending_buf[s.pending++] = s.bi_buf & 0xff; + s.bi_buf >>= 8; + s.bi_valid -= 8; + } + } + + + /* =========================================================================== + * Compute the optimal bit lengths for a tree and update the total bit length + * for the current block. + * IN assertion: the fields freq and dad are set, heap[heap_max] and + * above are the tree nodes sorted by increasing frequency. + * OUT assertions: the field len is set to the optimal bit length, the + * array bl_count contains the frequencies for each bit length. + * The length opt_len is updated; static_len is also updated if stree is + * not null. + */ + function gen_bitlen(s, desc) { + // deflate_state *s; + // tree_desc *desc; /* the tree descriptor */ + var tree = desc.dyn_tree; + var max_code = desc.max_code; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var extra = desc.stat_desc.extra_bits; + var base = desc.stat_desc.extra_base; + var max_length = desc.stat_desc.max_length; + var h; /* heap index */ + var n, m; /* iterate over the tree elements */ + var bits; /* bit length */ + var xbits; /* extra bits */ + var f; /* frequency */ + var overflow = 0; /* number of elements with bit length too large */ + + for (bits = 0; bits <= MAX_BITS$1; bits++) { + s.bl_count[bits] = 0; + } + + /* In a first pass, compute the optimal bit lengths (which may + * overflow in the case of the bit length tree). + */ + tree[s.heap[s.heap_max] * 2 + 1] /*.Len*/ = 0; /* root of the heap */ + + for (h = s.heap_max + 1; h < HEAP_SIZE$1; h++) { + n = s.heap[h]; + bits = tree[tree[n * 2 + 1] /*.Dad*/ * 2 + 1] /*.Len*/ + 1; + if (bits > max_length) { + bits = max_length; + overflow++; + } + tree[n * 2 + 1] /*.Len*/ = bits; + /* We overwrite tree[n].Dad which is no longer needed */ + + if (n > max_code) { + continue; + } /* not a leaf node */ + + s.bl_count[bits]++; + xbits = 0; + if (n >= base) { + xbits = extra[n - base]; + } + f = tree[n * 2] /*.Freq*/ ; + s.opt_len += f * (bits + xbits); + if (has_stree) { + s.static_len += f * (stree[n * 2 + 1] /*.Len*/ + xbits); + } + } + if (overflow === 0) { + return; + } + + // Trace((stderr,"\nbit length overflow\n")); + /* This happens for example on obj2 and pic of the Calgary corpus */ + + /* Find the first bit length which could increase: */ + do { + bits = max_length - 1; + while (s.bl_count[bits] === 0) { + bits--; + } + s.bl_count[bits]--; /* move one leaf down the tree */ + s.bl_count[bits + 1] += 2; /* move one overflow item as its brother */ + s.bl_count[max_length]--; + /* The brother of the overflow item also moves one step up, + * but this does not affect bl_count[max_length] + */ + overflow -= 2; + } while (overflow > 0); + + /* Now recompute all bit lengths, scanning in increasing frequency. + * h is still equal to HEAP_SIZE. (It is simpler to reconstruct all + * lengths instead of fixing only the wrong ones. This idea is taken + * from 'ar' written by Haruhiko Okumura.) + */ + for (bits = max_length; bits !== 0; bits--) { + n = s.bl_count[bits]; + while (n !== 0) { + m = s.heap[--h]; + if (m > max_code) { + continue; + } + if (tree[m * 2 + 1] /*.Len*/ !== bits) { + // Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits)); + s.opt_len += (bits - tree[m * 2 + 1] /*.Len*/ ) * tree[m * 2] /*.Freq*/ ; + tree[m * 2 + 1] /*.Len*/ = bits; + } + n--; + } + } + } + + + /* =========================================================================== + * Generate the codes for a given tree and bit counts (which need not be + * optimal). + * IN assertion: the array bl_count contains the bit length statistics for + * the given tree and the field len is set for all tree elements. + * OUT assertion: the field code is set for all tree elements of non + * zero code length. + */ + function gen_codes(tree, max_code, bl_count) { + // ct_data *tree; /* the tree to decorate */ + // int max_code; /* largest code with non zero frequency */ + // ushf *bl_count; /* number of codes at each bit length */ + + var next_code = new Array(MAX_BITS$1 + 1); /* next code value for each bit length */ + var code = 0; /* running code value */ + var bits; /* bit index */ + var n; /* code index */ + + /* The distribution counts are first used to generate the code values + * without bit reversal. + */ + for (bits = 1; bits <= MAX_BITS$1; bits++) { + next_code[bits] = code = (code + bl_count[bits - 1]) << 1; + } + /* Check that the bit counts in bl_count are consistent. The last code + * must be all ones. + */ + //Assert (code + bl_count[MAX_BITS]-1 == (1< length code (0..28) */ + length = 0; + for (code = 0; code < LENGTH_CODES$1 - 1; code++) { + base_length[code] = length; + for (n = 0; n < (1 << extra_lbits[code]); n++) { + _length_code[length++] = code; + } + } + //Assert (length == 256, "tr_static_init: length != 256"); + /* Note that the length 255 (match length 258) can be represented + * in two different ways: code 284 + 5 bits or code 285, so we + * overwrite length_code[255] to use the best encoding: + */ + _length_code[length - 1] = code; + + /* Initialize the mapping dist (0..32K) -> dist code (0..29) */ + dist = 0; + for (code = 0; code < 16; code++) { + base_dist[code] = dist; + for (n = 0; n < (1 << extra_dbits[code]); n++) { + _dist_code[dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: dist != 256"); + dist >>= 7; /* from now on, all distances are divided by 128 */ + for (; code < D_CODES$1; code++) { + base_dist[code] = dist << 7; + for (n = 0; n < (1 << (extra_dbits[code] - 7)); n++) { + _dist_code[256 + dist++] = code; + } + } + //Assert (dist == 256, "tr_static_init: 256+dist != 512"); + + /* Construct the codes of the static literal tree */ + for (bits = 0; bits <= MAX_BITS$1; bits++) { + bl_count[bits] = 0; + } + + n = 0; + while (n <= 143) { + static_ltree[n * 2 + 1] /*.Len*/ = 8; + n++; + bl_count[8]++; + } + while (n <= 255) { + static_ltree[n * 2 + 1] /*.Len*/ = 9; + n++; + bl_count[9]++; + } + while (n <= 279) { + static_ltree[n * 2 + 1] /*.Len*/ = 7; + n++; + bl_count[7]++; + } + while (n <= 287) { + static_ltree[n * 2 + 1] /*.Len*/ = 8; + n++; + bl_count[8]++; + } + /* Codes 286 and 287 do not exist, but we must include them in the + * tree construction to get a canonical Huffman tree (longest code + * all ones) + */ + gen_codes(static_ltree, L_CODES$1 + 1, bl_count); + + /* The static distance tree is trivial: */ + for (n = 0; n < D_CODES$1; n++) { + static_dtree[n * 2 + 1] /*.Len*/ = 5; + static_dtree[n * 2] /*.Code*/ = bi_reverse(n, 5); + } + + // Now data ready and we can init static trees + static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS$1 + 1, L_CODES$1, MAX_BITS$1); + static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES$1, MAX_BITS$1); + static_bl_desc = new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES$1, MAX_BL_BITS); + + //static_init_done = true; + } + + + /* =========================================================================== + * Initialize a new block. + */ + function init_block(s) { + var n; /* iterates over tree elements */ + + /* Initialize the trees. */ + for (n = 0; n < L_CODES$1; n++) { + s.dyn_ltree[n * 2] /*.Freq*/ = 0; + } + for (n = 0; n < D_CODES$1; n++) { + s.dyn_dtree[n * 2] /*.Freq*/ = 0; + } + for (n = 0; n < BL_CODES$1; n++) { + s.bl_tree[n * 2] /*.Freq*/ = 0; + } + + s.dyn_ltree[END_BLOCK * 2] /*.Freq*/ = 1; + s.opt_len = s.static_len = 0; + s.last_lit = s.matches = 0; + } + + + /* =========================================================================== + * Flush the bit buffer and align the output on a byte boundary + */ + function bi_windup(s) { + if (s.bi_valid > 8) { + put_short(s, s.bi_buf); + } else if (s.bi_valid > 0) { + //put_byte(s, (Byte)s->bi_buf); + s.pending_buf[s.pending++] = s.bi_buf; + } + s.bi_buf = 0; + s.bi_valid = 0; + } + + /* =========================================================================== + * Copy a stored block, storing first the length and its + * one's complement if requested. + */ + function copy_block(s, buf, len, header) { + //DeflateState *s; + //charf *buf; /* the input data */ + //unsigned len; /* its length */ + //int header; /* true if block header must be written */ + + bi_windup(s); /* align on byte boundary */ + + if (header) { + put_short(s, len); + put_short(s, ~len); + } + // while (len--) { + // put_byte(s, *buf++); + // } + arraySet(s.pending_buf, s.window, buf, len, s.pending); + s.pending += len; + } + + /* =========================================================================== + * Compares to subtrees, using the tree depth as tie breaker when + * the subtrees have equal frequency. This minimizes the worst case length. + */ + function smaller(tree, n, m, depth) { + var _n2 = n * 2; + var _m2 = m * 2; + return (tree[_n2] /*.Freq*/ < tree[_m2] /*.Freq*/ || + (tree[_n2] /*.Freq*/ === tree[_m2] /*.Freq*/ && depth[n] <= depth[m])); + } + + /* =========================================================================== + * Restore the heap property by moving down the tree starting at node k, + * exchanging a node with the smallest of its two sons if necessary, stopping + * when the heap property is re-established (each father smaller than its + * two sons). + */ + function pqdownheap(s, tree, k) + // deflate_state *s; + // ct_data *tree; /* the tree to restore */ + // int k; /* node to move down */ + { + var v = s.heap[k]; + var j = k << 1; /* left son of k */ + while (j <= s.heap_len) { + /* Set j to the smallest of the two sons: */ + if (j < s.heap_len && + smaller(tree, s.heap[j + 1], s.heap[j], s.depth)) { + j++; + } + /* Exit if v is smaller than both sons */ + if (smaller(tree, v, s.heap[j], s.depth)) { + break; + } + + /* Exchange v with the smallest son */ + s.heap[k] = s.heap[j]; + k = j; + + /* And continue down the tree, setting j to the left son of k */ + j <<= 1; + } + s.heap[k] = v; + } + + + // inlined manually + // var SMALLEST = 1; + + /* =========================================================================== + * Send the block data compressed using the given Huffman trees + */ + function compress_block(s, ltree, dtree) + // deflate_state *s; + // const ct_data *ltree; /* literal tree */ + // const ct_data *dtree; /* distance tree */ + { + var dist; /* distance of matched string */ + var lc; /* match length or unmatched char (if dist == 0) */ + var lx = 0; /* running index in l_buf */ + var code; /* the code to send */ + var extra; /* number of extra bits to send */ + + if (s.last_lit !== 0) { + do { + dist = (s.pending_buf[s.d_buf + lx * 2] << 8) | (s.pending_buf[s.d_buf + lx * 2 + 1]); + lc = s.pending_buf[s.l_buf + lx]; + lx++; + + if (dist === 0) { + send_code(s, lc, ltree); /* send a literal byte */ + //Tracecv(isgraph(lc), (stderr," '%c' ", lc)); + } else { + /* Here, lc is the match length - MIN_MATCH */ + code = _length_code[lc]; + send_code(s, code + LITERALS$1 + 1, ltree); /* send the length code */ + extra = extra_lbits[code]; + if (extra !== 0) { + lc -= base_length[code]; + send_bits(s, lc, extra); /* send the extra length bits */ + } + dist--; /* dist is now the match distance - 1 */ + code = d_code(dist); + //Assert (code < D_CODES, "bad d_code"); + + send_code(s, code, dtree); /* send the distance code */ + extra = extra_dbits[code]; + if (extra !== 0) { + dist -= base_dist[code]; + send_bits(s, dist, extra); /* send the extra distance bits */ + } + } /* literal or match pair ? */ + + /* Check that the overlay between pending_buf and d_buf+l_buf is ok: */ + //Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx, + // "pendingBuf overflow"); + + } while (lx < s.last_lit); + } + + send_code(s, END_BLOCK, ltree); + } + + + /* =========================================================================== + * Construct one Huffman tree and assigns the code bit strings and lengths. + * Update the total bit length for the current block. + * IN assertion: the field freq is set for all tree elements. + * OUT assertions: the fields len and code are set to the optimal bit length + * and corresponding code. The length opt_len is updated; static_len is + * also updated if stree is not null. The field max_code is set. + */ + function build_tree(s, desc) + // deflate_state *s; + // tree_desc *desc; /* the tree descriptor */ + { + var tree = desc.dyn_tree; + var stree = desc.stat_desc.static_tree; + var has_stree = desc.stat_desc.has_stree; + var elems = desc.stat_desc.elems; + var n, m; /* iterate over heap elements */ + var max_code = -1; /* largest code with non zero frequency */ + var node; /* new node being created */ + + /* Construct the initial heap, with least frequent element in + * heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1]. + * heap[0] is not used. + */ + s.heap_len = 0; + s.heap_max = HEAP_SIZE$1; + + for (n = 0; n < elems; n++) { + if (tree[n * 2] /*.Freq*/ !== 0) { + s.heap[++s.heap_len] = max_code = n; + s.depth[n] = 0; + + } else { + tree[n * 2 + 1] /*.Len*/ = 0; + } + } + + /* The pkzip format requires that at least one distance code exists, + * and that at least one bit should be sent even if there is only one + * possible code. So to avoid special checks later on we force at least + * two codes of non zero frequency. + */ + while (s.heap_len < 2) { + node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0); + tree[node * 2] /*.Freq*/ = 1; + s.depth[node] = 0; + s.opt_len--; + + if (has_stree) { + s.static_len -= stree[node * 2 + 1] /*.Len*/ ; + } + /* node is 0 or 1 so it does not have extra bits */ + } + desc.max_code = max_code; + + /* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree, + * establish sub-heaps of increasing lengths: + */ + for (n = (s.heap_len >> 1 /*int /2*/ ); n >= 1; n--) { + pqdownheap(s, tree, n); + } + + /* Construct the Huffman tree by repeatedly combining the least two + * frequent nodes. + */ + node = elems; /* next internal node of the tree */ + do { + //pqremove(s, tree, n); /* n = node of least frequency */ + /*** pqremove ***/ + n = s.heap[1 /*SMALLEST*/ ]; + s.heap[1 /*SMALLEST*/ ] = s.heap[s.heap_len--]; + pqdownheap(s, tree, 1 /*SMALLEST*/ ); + /***/ + + m = s.heap[1 /*SMALLEST*/ ]; /* m = node of next least frequency */ + + s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */ + s.heap[--s.heap_max] = m; + + /* Create a new node father of n and m */ + tree[node * 2] /*.Freq*/ = tree[n * 2] /*.Freq*/ + tree[m * 2] /*.Freq*/ ; + s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1; + tree[n * 2 + 1] /*.Dad*/ = tree[m * 2 + 1] /*.Dad*/ = node; + + /* and insert the new node in the heap */ + s.heap[1 /*SMALLEST*/ ] = node++; + pqdownheap(s, tree, 1 /*SMALLEST*/ ); + + } while (s.heap_len >= 2); + + s.heap[--s.heap_max] = s.heap[1 /*SMALLEST*/ ]; + + /* At this point, the fields freq and dad are set. We can now + * generate the bit lengths. + */ + gen_bitlen(s, desc); + + /* The field len is now set, we can generate the bit codes */ + gen_codes(tree, max_code, s.bl_count); + } + + + /* =========================================================================== + * Scan a literal or distance tree to determine the frequencies of the codes + * in the bit length tree. + */ + function scan_tree(s, tree, max_code) + // deflate_state *s; + // ct_data *tree; /* the tree to be scanned */ + // int max_code; /* and its largest code of non zero frequency */ + { + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1] /*.Len*/ ; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + tree[(max_code + 1) * 2 + 1] /*.Len*/ = 0xffff; /* guard */ + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1] /*.Len*/ ; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + s.bl_tree[curlen * 2] /*.Freq*/ += count; + + } else if (curlen !== 0) { + + if (curlen !== prevlen) { + s.bl_tree[curlen * 2] /*.Freq*/ ++; + } + s.bl_tree[REP_3_6 * 2] /*.Freq*/ ++; + + } else if (count <= 10) { + s.bl_tree[REPZ_3_10 * 2] /*.Freq*/ ++; + + } else { + s.bl_tree[REPZ_11_138 * 2] /*.Freq*/ ++; + } + + count = 0; + prevlen = curlen; + + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } + } + + + /* =========================================================================== + * Send a literal or distance tree in compressed form, using the codes in + * bl_tree. + */ + function send_tree(s, tree, max_code) + // deflate_state *s; + // ct_data *tree; /* the tree to be scanned */ + // int max_code; /* and its largest code of non zero frequency */ + { + var n; /* iterates over all tree elements */ + var prevlen = -1; /* last emitted length */ + var curlen; /* length of current code */ + + var nextlen = tree[0 * 2 + 1] /*.Len*/ ; /* length of next code */ + + var count = 0; /* repeat count of the current code */ + var max_count = 7; /* max repeat count */ + var min_count = 4; /* min repeat count */ + + /* tree[max_code+1].Len = -1; */ + /* guard already set */ + if (nextlen === 0) { + max_count = 138; + min_count = 3; + } + + for (n = 0; n <= max_code; n++) { + curlen = nextlen; + nextlen = tree[(n + 1) * 2 + 1] /*.Len*/ ; + + if (++count < max_count && curlen === nextlen) { + continue; + + } else if (count < min_count) { + do { + send_code(s, curlen, s.bl_tree); + } while (--count !== 0); + + } else if (curlen !== 0) { + if (curlen !== prevlen) { + send_code(s, curlen, s.bl_tree); + count--; + } + //Assert(count >= 3 && count <= 6, " 3_6?"); + send_code(s, REP_3_6, s.bl_tree); + send_bits(s, count - 3, 2); + + } else if (count <= 10) { + send_code(s, REPZ_3_10, s.bl_tree); + send_bits(s, count - 3, 3); + + } else { + send_code(s, REPZ_11_138, s.bl_tree); + send_bits(s, count - 11, 7); + } + + count = 0; + prevlen = curlen; + if (nextlen === 0) { + max_count = 138; + min_count = 3; + + } else if (curlen === nextlen) { + max_count = 6; + min_count = 3; + + } else { + max_count = 7; + min_count = 4; + } + } + } + + + /* =========================================================================== + * Construct the Huffman tree for the bit lengths and return the index in + * bl_order of the last bit length code to send. + */ + function build_bl_tree(s) { + var max_blindex; /* index of last bit length code of non zero freq */ + + /* Determine the bit length frequencies for literal and distance trees */ + scan_tree(s, s.dyn_ltree, s.l_desc.max_code); + scan_tree(s, s.dyn_dtree, s.d_desc.max_code); + + /* Build the bit length tree: */ + build_tree(s, s.bl_desc); + /* opt_len now includes the length of the tree representations, except + * the lengths of the bit lengths codes and the 5+5+4 bits for the counts. + */ + + /* Determine the number of bit length codes to send. The pkzip format + * requires that at least 4 bit length codes be sent. (appnote.txt says + * 3 but the actual value used is 4.) + */ + for (max_blindex = BL_CODES$1 - 1; max_blindex >= 3; max_blindex--) { + if (s.bl_tree[bl_order[max_blindex] * 2 + 1] /*.Len*/ !== 0) { + break; + } + } + /* Update opt_len to include the bit length tree and counts */ + s.opt_len += 3 * (max_blindex + 1) + 5 + 5 + 4; + //Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld", + // s->opt_len, s->static_len)); + + return max_blindex; + } + + + /* =========================================================================== + * Send the header for a block using dynamic Huffman trees: the counts, the + * lengths of the bit length codes, the literal tree and the distance tree. + * IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4. + */ + function send_all_trees(s, lcodes, dcodes, blcodes) + // deflate_state *s; + // int lcodes, dcodes, blcodes; /* number of codes for each tree */ + { + var rank; /* index in bl_order */ + + //Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes"); + //Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES, + // "too many codes"); + //Tracev((stderr, "\nbl counts: ")); + send_bits(s, lcodes - 257, 5); /* not +255 as stated in appnote.txt */ + send_bits(s, dcodes - 1, 5); + send_bits(s, blcodes - 4, 4); /* not -3 as stated in appnote.txt */ + for (rank = 0; rank < blcodes; rank++) { + //Tracev((stderr, "\nbl code %2d ", bl_order[rank])); + send_bits(s, s.bl_tree[bl_order[rank] * 2 + 1] /*.Len*/ , 3); + } + //Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_ltree, lcodes - 1); /* literal tree */ + //Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent)); + + send_tree(s, s.dyn_dtree, dcodes - 1); /* distance tree */ + //Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent)); + } + + + /* =========================================================================== + * Check if the data type is TEXT or BINARY, using the following algorithm: + * - TEXT if the two conditions below are satisfied: + * a) There are no non-portable control characters belonging to the + * "black list" (0..6, 14..25, 28..31). + * b) There is at least one printable character belonging to the + * "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255). + * - BINARY otherwise. + * - The following partially-portable control characters form a + * "gray list" that is ignored in this detection algorithm: + * (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}). + * IN assertion: the fields Freq of dyn_ltree are set. + */ + function detect_data_type(s) { + /* black_mask is the bit mask of black-listed bytes + * set bits 0..6, 14..25, and 28..31 + * 0xf3ffc07f = binary 11110011111111111100000001111111 + */ + var black_mask = 0xf3ffc07f; + var n; + + /* Check for non-textual ("black-listed") bytes. */ + for (n = 0; n <= 31; n++, black_mask >>>= 1) { + if ((black_mask & 1) && (s.dyn_ltree[n * 2] /*.Freq*/ !== 0)) { + return Z_BINARY$1; + } + } + + /* Check for textual ("white-listed") bytes. */ + if (s.dyn_ltree[9 * 2] /*.Freq*/ !== 0 || s.dyn_ltree[10 * 2] /*.Freq*/ !== 0 || + s.dyn_ltree[13 * 2] /*.Freq*/ !== 0) { + return Z_TEXT$1; + } + for (n = 32; n < LITERALS$1; n++) { + if (s.dyn_ltree[n * 2] /*.Freq*/ !== 0) { + return Z_TEXT$1; + } + } + + /* There are no "black-listed" or "white-listed" bytes: + * this stream either is empty or has tolerated ("gray-listed") bytes only. + */ + return Z_BINARY$1; + } + + + var static_init_done = false; + + /* =========================================================================== + * Initialize the tree data structures for a new zlib stream. + */ + function _tr_init(s) { + + if (!static_init_done) { + tr_static_init(); + static_init_done = true; + } + + s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc); + s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc); + s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc); + + s.bi_buf = 0; + s.bi_valid = 0; + + /* Initialize the first block of the first file: */ + init_block(s); + } + + + /* =========================================================================== + * Send a stored block + */ + function _tr_stored_block(s, buf, stored_len, last) + //DeflateState *s; + //charf *buf; /* input block */ + //ulg stored_len; /* length of input block */ + //int last; /* one if this is the last block for a file */ + { + send_bits(s, (STORED_BLOCK << 1) + (last ? 1 : 0), 3); /* send block type */ + copy_block(s, buf, stored_len, true); /* with header */ + } + + + /* =========================================================================== + * Send one empty static block to give enough lookahead for inflate. + * This takes 10 bits, of which 7 may remain in the bit buffer. + */ + function _tr_align(s) { + send_bits(s, STATIC_TREES << 1, 3); + send_code(s, END_BLOCK, static_ltree); + bi_flush(s); + } + + + /* =========================================================================== + * Determine the best encoding for the current block: dynamic trees, static + * trees or store, and output the encoded block to the zip file. + */ + function _tr_flush_block(s, buf, stored_len, last) + //DeflateState *s; + //charf *buf; /* input block, or NULL if too old */ + //ulg stored_len; /* length of input block */ + //int last; /* one if this is the last block for a file */ + { + var opt_lenb, static_lenb; /* opt_len and static_len in bytes */ + var max_blindex = 0; /* index of last bit length code of non zero freq */ + + /* Build the Huffman trees unless a stored block is forced */ + if (s.level > 0) { + + /* Check if the file is binary or text */ + if (s.strm.data_type === Z_UNKNOWN$2) { + s.strm.data_type = detect_data_type(s); + } + + /* Construct the literal and distance trees */ + build_tree(s, s.l_desc); + // Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + + build_tree(s, s.d_desc); + // Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, + // s->static_len)); + /* At this point, opt_len and static_len are the total bit lengths of + * the compressed block data, excluding the tree representations. + */ + + /* Build the bit length tree for the above two trees, and get the index + * in bl_order of the last bit length code to send. + */ + max_blindex = build_bl_tree(s); + + /* Determine the best encoding. Compute the block lengths in bytes. */ + opt_lenb = (s.opt_len + 3 + 7) >>> 3; + static_lenb = (s.static_len + 3 + 7) >>> 3; + + // Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", + // opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, + // s->last_lit)); + + if (static_lenb <= opt_lenb) { + opt_lenb = static_lenb; + } + + } else { + // Assert(buf != (char*)0, "lost buf"); + opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ + } + + if ((stored_len + 4 <= opt_lenb) && (buf !== -1)) { + /* 4: two words for the lengths */ + + /* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE. + * Otherwise we can't have processed more than WSIZE input bytes since + * the last block flush, because compression would have been + * successful. If LIT_BUFSIZE <= WSIZE, it is never too late to + * transform a block into a stored block. + */ + _tr_stored_block(s, buf, stored_len, last); + + } else if (s.strategy === Z_FIXED$2 || static_lenb === opt_lenb) { + + send_bits(s, (STATIC_TREES << 1) + (last ? 1 : 0), 3); + compress_block(s, static_ltree, static_dtree); + + } else { + send_bits(s, (DYN_TREES << 1) + (last ? 1 : 0), 3); + send_all_trees(s, s.l_desc.max_code + 1, s.d_desc.max_code + 1, max_blindex + 1); + compress_block(s, s.dyn_ltree, s.dyn_dtree); + } + // Assert (s->compressed_len == s->bits_sent, "bad compressed size"); + /* The above check is made mod 2^32, for files larger than 512 MB + * and uLong implemented on 32 bits. + */ + init_block(s); + + if (last) { + bi_windup(s); + } + // Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3, + // s->compressed_len-7*last)); + } + + /* =========================================================================== + * Save the match info and tally the frequency counts. Return true if + * the current block must be flushed. + */ + function _tr_tally(s, dist, lc) + // deflate_state *s; + // unsigned dist; /* distance of matched string */ + // unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */ + { + //var out_length, in_length, dcode; + + s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff; + s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff; + + s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff; + s.last_lit++; + + if (dist === 0) { + /* lc is the unmatched char */ + s.dyn_ltree[lc * 2] /*.Freq*/ ++; + } else { + s.matches++; + /* Here, lc is the match length - MIN_MATCH */ + dist--; /* dist = match distance - 1 */ + //Assert((ush)dist < (ush)MAX_DIST(s) && + // (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) && + // (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match"); + + s.dyn_ltree[(_length_code[lc] + LITERALS$1 + 1) * 2] /*.Freq*/ ++; + s.dyn_dtree[d_code(dist) * 2] /*.Freq*/ ++; + } + + // (!) This block is disabled in zlib defailts, + // don't enable it for binary compatibility + + //#ifdef TRUNCATE_BLOCK + // /* Try to guess if it is profitable to stop the current block here */ + // if ((s.last_lit & 0x1fff) === 0 && s.level > 2) { + // /* Compute an upper bound for the compressed length */ + // out_length = s.last_lit*8; + // in_length = s.strstart - s.block_start; + // + // for (dcode = 0; dcode < D_CODES; dcode++) { + // out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]); + // } + // out_length >>>= 3; + // //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ", + // // s->last_lit, in_length, out_length, + // // 100L - out_length*100L/in_length)); + // if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) { + // return true; + // } + // } + //#endif + + return (s.last_lit === s.lit_bufsize - 1); + /* We avoid equality with lit_bufsize because of wraparound at 64K + * on 16 bit machines and because stored blocks are restricted to + * 64K-1 bytes. + */ + } + + // Note: adler32 takes 12% for level 0 and 2% for level 6. + // It doesn't worth to make additional optimizationa as in original. + // Small size is preferable. + + function adler32(adler, buf, len, pos) { + var s1 = (adler & 0xffff) |0, + s2 = ((adler >>> 16) & 0xffff) |0, + n = 0; + + while (len !== 0) { + // Set limit ~ twice less than 5552, to keep + // s2 in 31-bits, because we force signed ints. + // in other case %= will fail. + n = len > 2000 ? 2000 : len; + len -= n; + + do { + s1 = (s1 + buf[pos++]) |0; + s2 = (s2 + s1) |0; + } while (--n); + + s1 %= 65521; + s2 %= 65521; + } + + return (s1 | (s2 << 16)) |0; + } + + // Note: we can't get significant speed boost here. + // So write code to minimize size - no pregenerated tables + // and array tools dependencies. + + + // Use ordinary array, since untyped makes no boost here + function makeTable() { + var c, table = []; + + for (var n = 0; n < 256; n++) { + c = n; + for (var k = 0; k < 8; k++) { + c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); + } + table[n] = c; + } + + return table; + } + + // Create table on load. Just 255 signed longs. Not a problem. + var crcTable = makeTable(); + + + function crc32(crc, buf, len, pos) { + var t = crcTable, + end = pos + len; + + crc ^= -1; + + for (var i = pos; i < end; i++) { + crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF]; + } + + return (crc ^ (-1)); // >>> 0; + } + + /* Public constants ==========================================================*/ + /* ===========================================================================*/ + + + /* Allowed flush values; see deflate() and inflate() below for details */ + var Z_NO_FLUSH$1 = 0; + var Z_PARTIAL_FLUSH$1 = 1; + //var Z_SYNC_FLUSH = 2; + var Z_FULL_FLUSH$1 = 3; + var Z_FINISH$2 = 4; + var Z_BLOCK$2 = 5; + //var Z_TREES = 6; + + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + var Z_OK$2 = 0; + var Z_STREAM_END$2 = 1; + //var Z_NEED_DICT = 2; + //var Z_ERRNO = -1; + var Z_STREAM_ERROR$2 = -2; + var Z_DATA_ERROR$2 = -3; + //var Z_MEM_ERROR = -4; + var Z_BUF_ERROR$2 = -5; + //var Z_VERSION_ERROR = -6; + + + /* compression levels */ + //var Z_NO_COMPRESSION = 0; + //var Z_BEST_SPEED = 1; + //var Z_BEST_COMPRESSION = 9; + var Z_DEFAULT_COMPRESSION$1 = -1; + + + var Z_FILTERED$1 = 1; + var Z_HUFFMAN_ONLY$1 = 2; + var Z_RLE$1 = 3; + var Z_FIXED$1 = 4; + + /* Possible values of the data_type field (though see inflate()) */ + //var Z_BINARY = 0; + //var Z_TEXT = 1; + //var Z_ASCII = 1; // = Z_TEXT + var Z_UNKNOWN$1 = 2; + + + /* The deflate compression method */ + var Z_DEFLATED$2 = 8; + + /*============================================================================*/ + + + var MAX_MEM_LEVEL = 9; + + + var LENGTH_CODES = 29; + /* number of length codes, not counting the special END_BLOCK code */ + var LITERALS = 256; + /* number of literal bytes 0..255 */ + var L_CODES = LITERALS + 1 + LENGTH_CODES; + /* number of Literal or Length codes, including the END_BLOCK code */ + var D_CODES = 30; + /* number of distance codes */ + var BL_CODES = 19; + /* number of codes used to transfer the bit lengths */ + var HEAP_SIZE = 2 * L_CODES + 1; + /* maximum heap size */ + var MAX_BITS = 15; + /* All codes must not exceed MAX_BITS bits */ + + var MIN_MATCH = 3; + var MAX_MATCH = 258; + var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1); + + var PRESET_DICT = 0x20; + + var INIT_STATE = 42; + var EXTRA_STATE = 69; + var NAME_STATE = 73; + var COMMENT_STATE = 91; + var HCRC_STATE = 103; + var BUSY_STATE = 113; + var FINISH_STATE = 666; + + var BS_NEED_MORE = 1; /* block not completed, need more input or more output */ + var BS_BLOCK_DONE = 2; /* block flush performed */ + var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */ + var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */ + + var OS_CODE = 0x03; // Unix :) . Don't detect, use this default. + + function err(strm, errorCode) { + strm.msg = msg[errorCode]; + return errorCode; + } + + function rank(f) { + return ((f) << 1) - ((f) > 4 ? 9 : 0); + } + + function zero(buf) { + var len = buf.length; + while (--len >= 0) { + buf[len] = 0; + } + } + + + /* ========================================================================= + * Flush as much pending output as possible. All deflate() output goes + * through this function so some applications may wish to modify it + * to avoid allocating a large strm->output buffer and copying into it. + * (See also read_buf()). + */ + function flush_pending(strm) { + var s = strm.state; + + //_tr_flush_bits(s); + var len = s.pending; + if (len > strm.avail_out) { + len = strm.avail_out; + } + if (len === 0) { + return; + } + + arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out); + strm.next_out += len; + s.pending_out += len; + strm.total_out += len; + strm.avail_out -= len; + s.pending -= len; + if (s.pending === 0) { + s.pending_out = 0; + } + } + + + function flush_block_only(s, last) { + _tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last); + s.block_start = s.strstart; + flush_pending(s.strm); + } + + + function put_byte(s, b) { + s.pending_buf[s.pending++] = b; + } + + + /* ========================================================================= + * Put a short in the pending buffer. The 16-bit value is put in MSB order. + * IN assertion: the stream state is correct and there is enough room in + * pending_buf. + */ + function putShortMSB(s, b) { + // put_byte(s, (Byte)(b >> 8)); + // put_byte(s, (Byte)(b & 0xff)); + s.pending_buf[s.pending++] = (b >>> 8) & 0xff; + s.pending_buf[s.pending++] = b & 0xff; + } + + + /* =========================================================================== + * Read a new buffer from the current input stream, update the adler32 + * and total number of bytes read. All deflate() input goes through + * this function so some applications may wish to modify it to avoid + * allocating a large strm->input buffer and copying from it. + * (See also flush_pending()). + */ + function read_buf(strm, buf, start, size) { + var len = strm.avail_in; + + if (len > size) { + len = size; + } + if (len === 0) { + return 0; + } + + strm.avail_in -= len; + + // zmemcpy(buf, strm->next_in, len); + arraySet(buf, strm.input, strm.next_in, len, start); + if (strm.state.wrap === 1) { + strm.adler = adler32(strm.adler, buf, len, start); + } else if (strm.state.wrap === 2) { + strm.adler = crc32(strm.adler, buf, len, start); + } + + strm.next_in += len; + strm.total_in += len; + + return len; + } + + + /* =========================================================================== + * Set match_start to the longest match starting at the given string and + * return its length. Matches shorter or equal to prev_length are discarded, + * in which case the result is equal to prev_length and match_start is + * garbage. + * IN assertions: cur_match is the head of the hash chain for the current + * string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1 + * OUT assertion: the match length is not greater than s->lookahead. + */ + function longest_match(s, cur_match) { + var chain_length = s.max_chain_length; /* max hash chain length */ + var scan = s.strstart; /* current string */ + var match; /* matched string */ + var len; /* length of current match */ + var best_len = s.prev_length; /* best match length so far */ + var nice_match = s.nice_match; /* stop if match long enough */ + var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ? + s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0 /*NIL*/ ; + + var _win = s.window; // shortcut + + var wmask = s.w_mask; + var prev = s.prev; + + /* Stop when cur_match becomes <= limit. To simplify the code, + * we prevent matches with the string of window index 0. + */ + + var strend = s.strstart + MAX_MATCH; + var scan_end1 = _win[scan + best_len - 1]; + var scan_end = _win[scan + best_len]; + + /* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16. + * It is easy to get rid of this optimization if necessary. + */ + // Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever"); + + /* Do not waste too much time if we already have a good match: */ + if (s.prev_length >= s.good_match) { + chain_length >>= 2; + } + /* Do not look for matches beyond the end of the input. This is necessary + * to make deflate deterministic. + */ + if (nice_match > s.lookahead) { + nice_match = s.lookahead; + } + + // Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead"); + + do { + // Assert(cur_match < s->strstart, "no future"); + match = cur_match; + + /* Skip to next match if the match length cannot increase + * or if the match length is less than 2. Note that the checks below + * for insufficient lookahead only occur occasionally for performance + * reasons. Therefore uninitialized memory will be accessed, and + * conditional jumps will be made that depend on those values. + * However the length of the match is limited to the lookahead, so + * the output of deflate is not affected by the uninitialized values. + */ + + if (_win[match + best_len] !== scan_end || + _win[match + best_len - 1] !== scan_end1 || + _win[match] !== _win[scan] || + _win[++match] !== _win[scan + 1]) { + continue; + } + + /* The check at best_len-1 can be removed because it will be made + * again later. (This heuristic is not always a win.) + * It is not necessary to compare scan[2] and match[2] since they + * are always equal when the other bytes match, given that + * the hash keys are equal and that HASH_BITS >= 8. + */ + scan += 2; + match++; + // Assert(*scan == *match, "match[2]?"); + + /* We check for insufficient lookahead only every 8th comparison; + * the 256th check will be made at strstart+258. + */ + do { + /*jshint noempty:false*/ + } while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + _win[++scan] === _win[++match] && _win[++scan] === _win[++match] && + scan < strend); + + // Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); + + len = MAX_MATCH - (strend - scan); + scan = strend - MAX_MATCH; + + if (len > best_len) { + s.match_start = cur_match; + best_len = len; + if (len >= nice_match) { + break; + } + scan_end1 = _win[scan + best_len - 1]; + scan_end = _win[scan + best_len]; + } + } while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0); + + if (best_len <= s.lookahead) { + return best_len; + } + return s.lookahead; + } + + + /* =========================================================================== + * Fill the window when the lookahead becomes insufficient. + * Updates strstart and lookahead. + * + * IN assertion: lookahead < MIN_LOOKAHEAD + * OUT assertions: strstart <= window_size-MIN_LOOKAHEAD + * At least one byte has been read, or avail_in == 0; reads are + * performed for at least two bytes (required for the zip translate_eol + * option -- not supported here). + */ + function fill_window(s) { + var _w_size = s.w_size; + var p, n, m, more, str; + + //Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead"); + + do { + more = s.window_size - s.lookahead - s.strstart; + + // JS ints have 32 bit, block below not needed + /* Deal with !@#$% 64K limit: */ + //if (sizeof(int) <= 2) { + // if (more == 0 && s->strstart == 0 && s->lookahead == 0) { + // more = wsize; + // + // } else if (more == (unsigned)(-1)) { + // /* Very unlikely, but possible on 16 bit machine if + // * strstart == 0 && lookahead == 1 (input done a byte at time) + // */ + // more--; + // } + //} + + + /* If the window is almost full and there is insufficient lookahead, + * move the upper half to the lower one to make room in the upper half. + */ + if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) { + + arraySet(s.window, s.window, _w_size, _w_size, 0); + s.match_start -= _w_size; + s.strstart -= _w_size; + /* we now have strstart >= MAX_DIST */ + s.block_start -= _w_size; + + /* Slide the hash table (could be avoided with 32 bit values + at the expense of memory usage). We slide even when level == 0 + to keep the hash table consistent if we switch back to level > 0 + later. (Using level 0 permanently is not an optimal usage of + zlib, so we don't care about this pathological case.) + */ + + n = s.hash_size; + p = n; + do { + m = s.head[--p]; + s.head[p] = (m >= _w_size ? m - _w_size : 0); + } while (--n); + + n = _w_size; + p = n; + do { + m = s.prev[--p]; + s.prev[p] = (m >= _w_size ? m - _w_size : 0); + /* If n is not on any hash chain, prev[n] is garbage but + * its value will never be used. + */ + } while (--n); + + more += _w_size; + } + if (s.strm.avail_in === 0) { + break; + } + + /* If there was no sliding: + * strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 && + * more == window_size - lookahead - strstart + * => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1) + * => more >= window_size - 2*WSIZE + 2 + * In the BIG_MEM or MMAP case (not yet supported), + * window_size == input_size + MIN_LOOKAHEAD && + * strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD. + * Otherwise, window_size == 2*WSIZE so more >= 2. + * If there was sliding, more >= WSIZE. So in all cases, more >= 2. + */ + //Assert(more >= 2, "more < 2"); + n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more); + s.lookahead += n; + + /* Initialize the hash value now that we have some input: */ + if (s.lookahead + s.insert >= MIN_MATCH) { + str = s.strstart - s.insert; + s.ins_h = s.window[str]; + + /* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask; + //#if MIN_MATCH != 3 + // Call update_hash() MIN_MATCH-3 more times + //#endif + while (s.insert) { + /* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH - 1]) & s.hash_mask; + + s.prev[str & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = str; + str++; + s.insert--; + if (s.lookahead + s.insert < MIN_MATCH) { + break; + } + } + } + /* If the whole input has less than MIN_MATCH bytes, ins_h is garbage, + * but this is not important since only literal bytes will be emitted. + */ + + } while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0); + + /* If the WIN_INIT bytes after the end of the current data have never been + * written, then zero those bytes in order to avoid memory check reports of + * the use of uninitialized (or uninitialised as Julian writes) bytes by + * the longest match routines. Update the high water mark for the next + * time through here. WIN_INIT is set to MAX_MATCH since the longest match + * routines allow scanning to strstart + MAX_MATCH, ignoring lookahead. + */ + // if (s.high_water < s.window_size) { + // var curr = s.strstart + s.lookahead; + // var init = 0; + // + // if (s.high_water < curr) { + // /* Previous high water mark below current data -- zero WIN_INIT + // * bytes or up to end of window, whichever is less. + // */ + // init = s.window_size - curr; + // if (init > WIN_INIT) + // init = WIN_INIT; + // zmemzero(s->window + curr, (unsigned)init); + // s->high_water = curr + init; + // } + // else if (s->high_water < (ulg)curr + WIN_INIT) { + // /* High water mark at or above current data, but below current data + // * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up + // * to end of window, whichever is less. + // */ + // init = (ulg)curr + WIN_INIT - s->high_water; + // if (init > s->window_size - s->high_water) + // init = s->window_size - s->high_water; + // zmemzero(s->window + s->high_water, (unsigned)init); + // s->high_water += init; + // } + // } + // + // Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD, + // "not enough room for search"); + } + + /* =========================================================================== + * Copy without compression as much as possible from the input stream, return + * the current block state. + * This function does not insert new strings in the dictionary since + * uncompressible data is probably not useful. This function is used + * only for the level=0 compression option. + * NOTE: this function should be optimized to avoid extra copying from + * window to pending_buf. + */ + function deflate_stored(s, flush) { + /* Stored blocks are limited to 0xffff bytes, pending_buf is limited + * to pending_buf_size, and each stored block has a 5 byte header: + */ + var max_block_size = 0xffff; + + if (max_block_size > s.pending_buf_size - 5) { + max_block_size = s.pending_buf_size - 5; + } + + /* Copy as much as possible from input to output: */ + for (;;) { + /* Fill the window as much as possible: */ + if (s.lookahead <= 1) { + + //Assert(s->strstart < s->w_size+MAX_DIST(s) || + // s->block_start >= (long)s->w_size, "slide too late"); + // if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) || + // s.block_start >= s.w_size)) { + // throw new Error("slide too late"); + // } + + fill_window(s); + if (s.lookahead === 0 && flush === Z_NO_FLUSH$1) { + return BS_NEED_MORE; + } + + if (s.lookahead === 0) { + break; + } + /* flush the current block */ + } + //Assert(s->block_start >= 0L, "block gone"); + // if (s.block_start < 0) throw new Error("block gone"); + + s.strstart += s.lookahead; + s.lookahead = 0; + + /* Emit a stored block if pending_buf will be full: */ + var max_start = s.block_start + max_block_size; + + if (s.strstart === 0 || s.strstart >= max_start) { + /* strstart == 0 is possible when wraparound on 16-bit machine */ + s.lookahead = s.strstart - max_start; + s.strstart = max_start; + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + + + } + /* Flush if we may have to slide, otherwise block_start may become + * negative and the data will be gone: + */ + if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + + s.insert = 0; + + if (flush === Z_FINISH$2) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + + if (s.strstart > s.block_start) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_NEED_MORE; + } + + /* =========================================================================== + * Compress as much as possible from the input stream, return the current + * block state. + * This function does not perform lazy evaluation of matches and inserts + * new strings in the dictionary only for unmatched strings or for short + * matches. It is used only for the fast compression options. + */ + function deflate_fast(s, flush) { + var hash_head; /* head of the hash chain */ + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$1) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; /* flush the current block */ + } + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0 /*NIL*/ ; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + * At this point we have always match_length < MIN_MATCH + */ + if (hash_head !== 0 /*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + } + if (s.match_length >= MIN_MATCH) { + // check_match(s, s.strstart, s.match_start, s.match_length); // for debug only + + /*** _tr_tally_dist(s, s.strstart - s.match_start, + s.match_length - MIN_MATCH, bflush); ***/ + bflush = _tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + + /* Insert new strings in the hash table only if the match length + * is not too large. This saves time but degrades compression. + */ + if (s.match_length <= s.max_lazy_match /*max_insert_length*/ && s.lookahead >= MIN_MATCH) { + s.match_length--; /* string at strstart already in table */ + do { + s.strstart++; + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + /* strstart never exceeds WSIZE-MAX_MATCH, so there are + * always MIN_MATCH bytes ahead. + */ + } while (--s.match_length !== 0); + s.strstart++; + } else { + s.strstart += s.match_length; + s.match_length = 0; + s.ins_h = s.window[s.strstart]; + /* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask; + + //#if MIN_MATCH != 3 + // Call UPDATE_HASH() MIN_MATCH-3 more times + //#endif + /* If lookahead < MIN_MATCH, ins_h is garbage, but it does not + * matter since it will be recomputed at next deflate call. + */ + } + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s.window[s.strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = _tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = ((s.strstart < (MIN_MATCH - 1)) ? s.strstart : MIN_MATCH - 1); + if (flush === Z_FINISH$2) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; + } + + /* =========================================================================== + * Same as above, but achieves better compression. We use a lazy + * evaluation for matches: a match is finally adopted only if there is + * no better match at the next window position. + */ + function deflate_slow(s, flush) { + var hash_head; /* head of hash chain */ + var bflush; /* set if current block must be flushed */ + + var max_insert; + + /* Process the input block. */ + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the next match, plus MIN_MATCH bytes to insert the + * string following the next match. + */ + if (s.lookahead < MIN_LOOKAHEAD) { + fill_window(s); + if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH$1) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } /* flush the current block */ + } + + /* Insert the string window[strstart .. strstart+2] in the + * dictionary, and set hash_head to the head of the hash chain: + */ + hash_head = 0 /*NIL*/ ; + if (s.lookahead >= MIN_MATCH) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + + /* Find the longest match, discarding those <= prev_length. + */ + s.prev_length = s.match_length; + s.prev_match = s.match_start; + s.match_length = MIN_MATCH - 1; + + if (hash_head !== 0 /*NIL*/ && s.prev_length < s.max_lazy_match && + s.strstart - hash_head <= (s.w_size - MIN_LOOKAHEAD) /*MAX_DIST(s)*/ ) { + /* To simplify the code, we prevent matches with the string + * of window index 0 (in particular we have to avoid a match + * of the string with itself at the start of the input file). + */ + s.match_length = longest_match(s, hash_head); + /* longest_match() sets match_start */ + + if (s.match_length <= 5 && + (s.strategy === Z_FILTERED$1 || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096 /*TOO_FAR*/ ))) { + + /* If prev_match is also MIN_MATCH, match_start is garbage + * but we will ignore the current match anyway. + */ + s.match_length = MIN_MATCH - 1; + } + } + /* If there was a match at the previous step and the current + * match is not better, output the previous match: + */ + if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) { + max_insert = s.strstart + s.lookahead - MIN_MATCH; + /* Do not insert strings in hash table beyond this. */ + + //check_match(s, s.strstart-1, s.prev_match, s.prev_length); + + /***_tr_tally_dist(s, s.strstart - 1 - s.prev_match, + s.prev_length - MIN_MATCH, bflush);***/ + bflush = _tr_tally(s, s.strstart - 1 - s.prev_match, s.prev_length - MIN_MATCH); + /* Insert in hash table all strings up to the end of the match. + * strstart-1 and strstart are already inserted. If there is not + * enough lookahead, the last two strings are not inserted in + * the hash table. + */ + s.lookahead -= s.prev_length - 1; + s.prev_length -= 2; + do { + if (++s.strstart <= max_insert) { + /*** INSERT_STRING(s, s.strstart, hash_head); ***/ + s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask; + hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h]; + s.head[s.ins_h] = s.strstart; + /***/ + } + } while (--s.prev_length !== 0); + s.match_available = 0; + s.match_length = MIN_MATCH - 1; + s.strstart++; + + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + } else if (s.match_available) { + /* If there was no match at the previous position, output a + * single literal. If there was a match but the current match + * is longer, truncate the previous match to a single literal. + */ + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); + + if (bflush) { + /*** FLUSH_BLOCK_ONLY(s, 0) ***/ + flush_block_only(s, false); + /***/ + } + s.strstart++; + s.lookahead--; + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + } else { + /* There is no previous match to compare with, wait for + * the next step to decide. + */ + s.match_available = 1; + s.strstart++; + s.lookahead--; + } + } + //Assert (flush != Z_NO_FLUSH, "no flush?"); + if (s.match_available) { + //Tracevv((stderr,"%c", s->window[s->strstart-1])); + /*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/ + bflush = _tr_tally(s, 0, s.window[s.strstart - 1]); + + s.match_available = 0; + } + s.insert = s.strstart < MIN_MATCH - 1 ? s.strstart : MIN_MATCH - 1; + if (flush === Z_FINISH$2) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + + return BS_BLOCK_DONE; + } + + + /* =========================================================================== + * For Z_RLE, simply look for runs of bytes, generate matches only of distance + * one. Do not maintain a hash table. (It will be regenerated if this run of + * deflate switches away from Z_RLE.) + */ + function deflate_rle(s, flush) { + var bflush; /* set if current block must be flushed */ + var prev; /* byte at distance one to match */ + var scan, strend; /* scan goes up to strend for length of run */ + + var _win = s.window; + + for (;;) { + /* Make sure that we always have enough lookahead, except + * at the end of the input file. We need MAX_MATCH bytes + * for the longest run, plus one for the unrolled loop. + */ + if (s.lookahead <= MAX_MATCH) { + fill_window(s); + if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH$1) { + return BS_NEED_MORE; + } + if (s.lookahead === 0) { + break; + } /* flush the current block */ + } + + /* See how many times the previous byte repeats */ + s.match_length = 0; + if (s.lookahead >= MIN_MATCH && s.strstart > 0) { + scan = s.strstart - 1; + prev = _win[scan]; + if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) { + strend = s.strstart + MAX_MATCH; + do { + /*jshint noempty:false*/ + } while (prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + prev === _win[++scan] && prev === _win[++scan] && + scan < strend); + s.match_length = MAX_MATCH - (strend - scan); + if (s.match_length > s.lookahead) { + s.match_length = s.lookahead; + } + } + //Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan"); + } + + /* Emit match if have run of MIN_MATCH or longer, else emit literal */ + if (s.match_length >= MIN_MATCH) { + //check_match(s, s.strstart, s.strstart - 1, s.match_length); + + /*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/ + bflush = _tr_tally(s, 1, s.match_length - MIN_MATCH); + + s.lookahead -= s.match_length; + s.strstart += s.match_length; + s.match_length = 0; + } else { + /* No match, output a literal byte */ + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = _tr_tally(s, 0, s.window[s.strstart]); + + s.lookahead--; + s.strstart++; + } + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH$2) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; + } + + /* =========================================================================== + * For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table. + * (It will be regenerated if this run of deflate switches away from Huffman.) + */ + function deflate_huff(s, flush) { + var bflush; /* set if current block must be flushed */ + + for (;;) { + /* Make sure that we have a literal to write. */ + if (s.lookahead === 0) { + fill_window(s); + if (s.lookahead === 0) { + if (flush === Z_NO_FLUSH$1) { + return BS_NEED_MORE; + } + break; /* flush the current block */ + } + } + + /* Output a literal byte */ + s.match_length = 0; + //Tracevv((stderr,"%c", s->window[s->strstart])); + /*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/ + bflush = _tr_tally(s, 0, s.window[s.strstart]); + s.lookahead--; + s.strstart++; + if (bflush) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + } + s.insert = 0; + if (flush === Z_FINISH$2) { + /*** FLUSH_BLOCK(s, 1); ***/ + flush_block_only(s, true); + if (s.strm.avail_out === 0) { + return BS_FINISH_STARTED; + } + /***/ + return BS_FINISH_DONE; + } + if (s.last_lit) { + /*** FLUSH_BLOCK(s, 0); ***/ + flush_block_only(s, false); + if (s.strm.avail_out === 0) { + return BS_NEED_MORE; + } + /***/ + } + return BS_BLOCK_DONE; + } + + /* Values for max_lazy_match, good_match and max_chain_length, depending on + * the desired pack level (0..9). The values given below have been tuned to + * exclude worst case performance for pathological files. Better values may be + * found for specific files. + */ + function Config(good_length, max_lazy, nice_length, max_chain, func) { + this.good_length = good_length; + this.max_lazy = max_lazy; + this.nice_length = nice_length; + this.max_chain = max_chain; + this.func = func; + } + + var configuration_table; + + configuration_table = [ + /* good lazy nice chain */ + new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */ + new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */ + new Config(4, 5, 16, 8, deflate_fast), /* 2 */ + new Config(4, 6, 32, 32, deflate_fast), /* 3 */ + + new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */ + new Config(8, 16, 32, 32, deflate_slow), /* 5 */ + new Config(8, 16, 128, 128, deflate_slow), /* 6 */ + new Config(8, 32, 128, 256, deflate_slow), /* 7 */ + new Config(32, 128, 258, 1024, deflate_slow), /* 8 */ + new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */ + ]; + + + /* =========================================================================== + * Initialize the "longest match" routines for a new zlib stream + */ + function lm_init(s) { + s.window_size = 2 * s.w_size; + + /*** CLEAR_HASH(s); ***/ + zero(s.head); // Fill with NIL (= 0); + + /* Set the default configuration parameters: + */ + s.max_lazy_match = configuration_table[s.level].max_lazy; + s.good_match = configuration_table[s.level].good_length; + s.nice_match = configuration_table[s.level].nice_length; + s.max_chain_length = configuration_table[s.level].max_chain; + + s.strstart = 0; + s.block_start = 0; + s.lookahead = 0; + s.insert = 0; + s.match_length = s.prev_length = MIN_MATCH - 1; + s.match_available = 0; + s.ins_h = 0; + } + + + function DeflateState() { + this.strm = null; /* pointer back to this zlib stream */ + this.status = 0; /* as the name implies */ + this.pending_buf = null; /* output still pending */ + this.pending_buf_size = 0; /* size of pending_buf */ + this.pending_out = 0; /* next pending byte to output to the stream */ + this.pending = 0; /* nb of bytes in the pending buffer */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.gzhead = null; /* gzip header information to write */ + this.gzindex = 0; /* where in extra, name, or comment */ + this.method = Z_DEFLATED$2; /* can only be DEFLATED */ + this.last_flush = -1; /* value of flush param for previous deflate call */ + + this.w_size = 0; /* LZ77 window size (32K by default) */ + this.w_bits = 0; /* log2(w_size) (8..16) */ + this.w_mask = 0; /* w_size - 1 */ + + this.window = null; + /* Sliding window. Input bytes are read into the second half of the window, + * and move to the first half later to keep a dictionary of at least wSize + * bytes. With this organization, matches are limited to a distance of + * wSize-MAX_MATCH bytes, but this ensures that IO is always + * performed with a length multiple of the block size. + */ + + this.window_size = 0; + /* Actual size of window: 2*wSize, except when the user input buffer + * is directly used as sliding window. + */ + + this.prev = null; + /* Link to older string with same hash index. To limit the size of this + * array to 64K, this link is maintained only for the last 32K strings. + * An index in this array is thus a window index modulo 32K. + */ + + this.head = null; /* Heads of the hash chains or NIL. */ + + this.ins_h = 0; /* hash index of string to be inserted */ + this.hash_size = 0; /* number of elements in hash table */ + this.hash_bits = 0; /* log2(hash_size) */ + this.hash_mask = 0; /* hash_size-1 */ + + this.hash_shift = 0; + /* Number of bits by which ins_h must be shifted at each input + * step. It must be such that after MIN_MATCH steps, the oldest + * byte no longer takes part in the hash key, that is: + * hash_shift * MIN_MATCH >= hash_bits + */ + + this.block_start = 0; + /* Window position at the beginning of the current output block. Gets + * negative when the window is moved backwards. + */ + + this.match_length = 0; /* length of best match */ + this.prev_match = 0; /* previous match */ + this.match_available = 0; /* set if previous match exists */ + this.strstart = 0; /* start of string to insert */ + this.match_start = 0; /* start of matching string */ + this.lookahead = 0; /* number of valid bytes ahead in window */ + + this.prev_length = 0; + /* Length of the best match at previous step. Matches not greater than this + * are discarded. This is used in the lazy match evaluation. + */ + + this.max_chain_length = 0; + /* To speed up deflation, hash chains are never searched beyond this + * length. A higher limit improves compression ratio but degrades the + * speed. + */ + + this.max_lazy_match = 0; + /* Attempt to find a better match only when the current match is strictly + * smaller than this value. This mechanism is used only for compression + * levels >= 4. + */ + // That's alias to max_lazy_match, don't use directly + //this.max_insert_length = 0; + /* Insert new strings in the hash table only if the match length is not + * greater than this length. This saves time but degrades compression. + * max_insert_length is used only for compression levels <= 3. + */ + + this.level = 0; /* compression level (1..9) */ + this.strategy = 0; /* favor or force Huffman coding*/ + + this.good_match = 0; + /* Use a faster search when the previous match is longer than this */ + + this.nice_match = 0; /* Stop searching when current match exceeds this */ + + /* used by c: */ + + /* Didn't use ct_data typedef below to suppress compiler warning */ + + // struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */ + // struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */ + // struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */ + + // Use flat array of DOUBLE size, with interleaved fata, + // because JS does not support effective + this.dyn_ltree = new Buf16(HEAP_SIZE * 2); + this.dyn_dtree = new Buf16((2 * D_CODES + 1) * 2); + this.bl_tree = new Buf16((2 * BL_CODES + 1) * 2); + zero(this.dyn_ltree); + zero(this.dyn_dtree); + zero(this.bl_tree); + + this.l_desc = null; /* desc. for literal tree */ + this.d_desc = null; /* desc. for distance tree */ + this.bl_desc = null; /* desc. for bit length tree */ + + //ush bl_count[MAX_BITS+1]; + this.bl_count = new Buf16(MAX_BITS + 1); + /* number of codes at each bit length for an optimal tree */ + + //int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */ + this.heap = new Buf16(2 * L_CODES + 1); /* heap used to build the Huffman trees */ + zero(this.heap); + + this.heap_len = 0; /* number of elements in the heap */ + this.heap_max = 0; /* element of largest frequency */ + /* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used. + * The same heap array is used to build all + */ + + this.depth = new Buf16(2 * L_CODES + 1); //uch depth[2*L_CODES+1]; + zero(this.depth); + /* Depth of each subtree used as tie breaker for trees of equal frequency + */ + + this.l_buf = 0; /* buffer index for literals or lengths */ + + this.lit_bufsize = 0; + /* Size of match buffer for literals/lengths. There are 4 reasons for + * limiting lit_bufsize to 64K: + * - frequencies can be kept in 16 bit counters + * - if compression is not successful for the first block, all input + * data is still in the window so we can still emit a stored block even + * when input comes from standard input. (This can also be done for + * all blocks if lit_bufsize is not greater than 32K.) + * - if compression is not successful for a file smaller than 64K, we can + * even emit a stored file instead of a stored block (saving 5 bytes). + * This is applicable only for zip (not gzip or zlib). + * - creating new Huffman trees less frequently may not provide fast + * adaptation to changes in the input data statistics. (Take for + * example a binary file with poorly compressible code followed by + * a highly compressible string table.) Smaller buffer sizes give + * fast adaptation but have of course the overhead of transmitting + * trees more frequently. + * - I can't count above 4 + */ + + this.last_lit = 0; /* running index in l_buf */ + + this.d_buf = 0; + /* Buffer index for distances. To simplify the code, d_buf and l_buf have + * the same number of elements. To use different lengths, an extra flag + * array would be necessary. + */ + + this.opt_len = 0; /* bit length of current block with optimal trees */ + this.static_len = 0; /* bit length of current block with static trees */ + this.matches = 0; /* number of string matches in current block */ + this.insert = 0; /* bytes at end of window left to insert */ + + + this.bi_buf = 0; + /* Output buffer. bits are inserted starting at the bottom (least + * significant bits). + */ + this.bi_valid = 0; + /* Number of valid bits in bi_buf. All bits above the last valid bit + * are always zero. + */ + + // Used for window memory init. We safely ignore it for JS. That makes + // sense only for pointers and memory check tools. + //this.high_water = 0; + /* High water mark offset in window for initialized bytes -- bytes above + * this are set to zero in order to avoid memory check warnings when + * longest match routines access bytes past the input. This is then + * updated to the new high water mark. + */ + } + + + function deflateResetKeep(strm) { + var s; + + if (!strm || !strm.state) { + return err(strm, Z_STREAM_ERROR$2); + } + + strm.total_in = strm.total_out = 0; + strm.data_type = Z_UNKNOWN$1; + + s = strm.state; + s.pending = 0; + s.pending_out = 0; + + if (s.wrap < 0) { + s.wrap = -s.wrap; + /* was made negative by deflate(..., Z_FINISH); */ + } + s.status = (s.wrap ? INIT_STATE : BUSY_STATE); + strm.adler = (s.wrap === 2) ? + 0 // crc32(0, Z_NULL, 0) + : + 1; // adler32(0, Z_NULL, 0) + s.last_flush = Z_NO_FLUSH$1; + _tr_init(s); + return Z_OK$2; + } + + + function deflateReset(strm) { + var ret = deflateResetKeep(strm); + if (ret === Z_OK$2) { + lm_init(strm.state); + } + return ret; + } + + + function deflateInit2(strm, level, method, windowBits, memLevel, strategy) { + if (!strm) { // === Z_NULL + return Z_STREAM_ERROR$2; + } + var wrap = 1; + + if (level === Z_DEFAULT_COMPRESSION$1) { + level = 6; + } + + if (windowBits < 0) { /* suppress zlib wrapper */ + wrap = 0; + windowBits = -windowBits; + } else if (windowBits > 15) { + wrap = 2; /* write gzip wrapper instead */ + windowBits -= 16; + } + + + if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED$2 || + windowBits < 8 || windowBits > 15 || level < 0 || level > 9 || + strategy < 0 || strategy > Z_FIXED$1) { + return err(strm, Z_STREAM_ERROR$2); + } + + + if (windowBits === 8) { + windowBits = 9; + } + /* until 256-byte window bug fixed */ + + var s = new DeflateState(); + + strm.state = s; + s.strm = strm; + + s.wrap = wrap; + s.gzhead = null; + s.w_bits = windowBits; + s.w_size = 1 << s.w_bits; + s.w_mask = s.w_size - 1; + + s.hash_bits = memLevel + 7; + s.hash_size = 1 << s.hash_bits; + s.hash_mask = s.hash_size - 1; + s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH); + + s.window = new Buf8(s.w_size * 2); + s.head = new Buf16(s.hash_size); + s.prev = new Buf16(s.w_size); + + // Don't need mem init magic for JS. + //s.high_water = 0; /* nothing written to s->window yet */ + + s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */ + + s.pending_buf_size = s.lit_bufsize * 4; + + //overlay = (ushf *) ZALLOC(strm, s->lit_bufsize, sizeof(ush)+2); + //s->pending_buf = (uchf *) overlay; + s.pending_buf = new Buf8(s.pending_buf_size); + + // It is offset from `s.pending_buf` (size is `s.lit_bufsize * 2`) + //s->d_buf = overlay + s->lit_bufsize/sizeof(ush); + s.d_buf = 1 * s.lit_bufsize; + + //s->l_buf = s->pending_buf + (1+sizeof(ush))*s->lit_bufsize; + s.l_buf = (1 + 2) * s.lit_bufsize; + + s.level = level; + s.strategy = strategy; + s.method = method; + + return deflateReset(strm); + } + + + function deflate$1(strm, flush) { + var old_flush, s; + var beg, val; // for gzip header write only + + if (!strm || !strm.state || + flush > Z_BLOCK$2 || flush < 0) { + return strm ? err(strm, Z_STREAM_ERROR$2) : Z_STREAM_ERROR$2; + } + + s = strm.state; + + if (!strm.output || + (!strm.input && strm.avail_in !== 0) || + (s.status === FINISH_STATE && flush !== Z_FINISH$2)) { + return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR$2 : Z_STREAM_ERROR$2); + } + + s.strm = strm; /* just in case */ + old_flush = s.last_flush; + s.last_flush = flush; + + /* Write the header */ + if (s.status === INIT_STATE) { + if (s.wrap === 2) { + // GZIP header + strm.adler = 0; //crc32(0L, Z_NULL, 0); + put_byte(s, 31); + put_byte(s, 139); + put_byte(s, 8); + if (!s.gzhead) { // s->gzhead == Z_NULL + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, 0); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY$1 || s.level < 2 ? + 4 : 0)); + put_byte(s, OS_CODE); + s.status = BUSY_STATE; + } else { + put_byte(s, (s.gzhead.text ? 1 : 0) + + (s.gzhead.hcrc ? 2 : 0) + + (!s.gzhead.extra ? 0 : 4) + + (!s.gzhead.name ? 0 : 8) + + (!s.gzhead.comment ? 0 : 16) + ); + put_byte(s, s.gzhead.time & 0xff); + put_byte(s, (s.gzhead.time >> 8) & 0xff); + put_byte(s, (s.gzhead.time >> 16) & 0xff); + put_byte(s, (s.gzhead.time >> 24) & 0xff); + put_byte(s, s.level === 9 ? 2 : + (s.strategy >= Z_HUFFMAN_ONLY$1 || s.level < 2 ? + 4 : 0)); + put_byte(s, s.gzhead.os & 0xff); + if (s.gzhead.extra && s.gzhead.extra.length) { + put_byte(s, s.gzhead.extra.length & 0xff); + put_byte(s, (s.gzhead.extra.length >> 8) & 0xff); + } + if (s.gzhead.hcrc) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0); + } + s.gzindex = 0; + s.status = EXTRA_STATE; + } + } else // DEFLATE header + { + var header = (Z_DEFLATED$2 + ((s.w_bits - 8) << 4)) << 8; + var level_flags = -1; + + if (s.strategy >= Z_HUFFMAN_ONLY$1 || s.level < 2) { + level_flags = 0; + } else if (s.level < 6) { + level_flags = 1; + } else if (s.level === 6) { + level_flags = 2; + } else { + level_flags = 3; + } + header |= (level_flags << 6); + if (s.strstart !== 0) { + header |= PRESET_DICT; + } + header += 31 - (header % 31); + + s.status = BUSY_STATE; + putShortMSB(s, header); + + /* Save the adler32 of the preset dictionary: */ + if (s.strstart !== 0) { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + strm.adler = 1; // adler32(0L, Z_NULL, 0); + } + } + + //#ifdef GZIP + if (s.status === EXTRA_STATE) { + if (s.gzhead.extra /* != Z_NULL*/ ) { + beg = s.pending; /* start of bytes to update crc */ + + while (s.gzindex < (s.gzhead.extra.length & 0xffff)) { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + break; + } + } + put_byte(s, s.gzhead.extra[s.gzindex] & 0xff); + s.gzindex++; + } + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (s.gzindex === s.gzhead.extra.length) { + s.gzindex = 0; + s.status = NAME_STATE; + } + } else { + s.status = NAME_STATE; + } + } + if (s.status === NAME_STATE) { + if (s.gzhead.name /* != Z_NULL*/ ) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.name.length) { + val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.gzindex = 0; + s.status = COMMENT_STATE; + } + } else { + s.status = COMMENT_STATE; + } + } + if (s.status === COMMENT_STATE) { + if (s.gzhead.comment /* != Z_NULL*/ ) { + beg = s.pending; /* start of bytes to update crc */ + //int val; + + do { + if (s.pending === s.pending_buf_size) { + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + flush_pending(strm); + beg = s.pending; + if (s.pending === s.pending_buf_size) { + val = 1; + break; + } + } + // JS specific: little magic to add zero terminator to end of string + if (s.gzindex < s.gzhead.comment.length) { + val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff; + } else { + val = 0; + } + put_byte(s, val); + } while (val !== 0); + + if (s.gzhead.hcrc && s.pending > beg) { + strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg); + } + if (val === 0) { + s.status = HCRC_STATE; + } + } else { + s.status = HCRC_STATE; + } + } + if (s.status === HCRC_STATE) { + if (s.gzhead.hcrc) { + if (s.pending + 2 > s.pending_buf_size) { + flush_pending(strm); + } + if (s.pending + 2 <= s.pending_buf_size) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + strm.adler = 0; //crc32(0L, Z_NULL, 0); + s.status = BUSY_STATE; + } + } else { + s.status = BUSY_STATE; + } + } + //#endif + + /* Flush as much pending output as possible */ + if (s.pending !== 0) { + flush_pending(strm); + if (strm.avail_out === 0) { + /* Since avail_out is 0, deflate will be called again with + * more output space, but possibly with both pending and + * avail_in equal to zero. There won't be anything to do, + * but this is not an error situation so make sure we + * return OK instead of BUF_ERROR at next call of deflate: + */ + s.last_flush = -1; + return Z_OK$2; + } + + /* Make sure there is something to do and avoid duplicate consecutive + * flushes. For repeated and useless calls with Z_FINISH, we keep + * returning Z_STREAM_END instead of Z_BUF_ERROR. + */ + } else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) && + flush !== Z_FINISH$2) { + return err(strm, Z_BUF_ERROR$2); + } + + /* User must not provide more input after the first FINISH: */ + if (s.status === FINISH_STATE && strm.avail_in !== 0) { + return err(strm, Z_BUF_ERROR$2); + } + + /* Start a new block or continue the current one. + */ + if (strm.avail_in !== 0 || s.lookahead !== 0 || + (flush !== Z_NO_FLUSH$1 && s.status !== FINISH_STATE)) { + var bstate = (s.strategy === Z_HUFFMAN_ONLY$1) ? deflate_huff(s, flush) : + (s.strategy === Z_RLE$1 ? deflate_rle(s, flush) : + configuration_table[s.level].func(s, flush)); + + if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) { + s.status = FINISH_STATE; + } + if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) { + if (strm.avail_out === 0) { + s.last_flush = -1; + /* avoid BUF_ERROR next call, see above */ + } + return Z_OK$2; + /* If flush != Z_NO_FLUSH && avail_out == 0, the next call + * of deflate should use the same flush parameter to make sure + * that the flush is complete. So we don't have to output an + * empty block here, this will be done at next call. This also + * ensures that for a very small output buffer, we emit at most + * one empty block. + */ + } + if (bstate === BS_BLOCK_DONE) { + if (flush === Z_PARTIAL_FLUSH$1) { + _tr_align(s); + } else if (flush !== Z_BLOCK$2) { /* FULL_FLUSH or SYNC_FLUSH */ + + _tr_stored_block(s, 0, 0, false); + /* For a full flush, this empty block will be recognized + * as a special marker by inflate_sync(). + */ + if (flush === Z_FULL_FLUSH$1) { + /*** CLEAR_HASH(s); ***/ + /* forget history */ + zero(s.head); // Fill with NIL (= 0); + + if (s.lookahead === 0) { + s.strstart = 0; + s.block_start = 0; + s.insert = 0; + } + } + } + flush_pending(strm); + if (strm.avail_out === 0) { + s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */ + return Z_OK$2; + } + } + } + //Assert(strm->avail_out > 0, "bug2"); + //if (strm.avail_out <= 0) { throw new Error("bug2");} + + if (flush !== Z_FINISH$2) { + return Z_OK$2; + } + if (s.wrap <= 0) { + return Z_STREAM_END$2; + } + + /* Write the trailer */ + if (s.wrap === 2) { + put_byte(s, strm.adler & 0xff); + put_byte(s, (strm.adler >> 8) & 0xff); + put_byte(s, (strm.adler >> 16) & 0xff); + put_byte(s, (strm.adler >> 24) & 0xff); + put_byte(s, strm.total_in & 0xff); + put_byte(s, (strm.total_in >> 8) & 0xff); + put_byte(s, (strm.total_in >> 16) & 0xff); + put_byte(s, (strm.total_in >> 24) & 0xff); + } else { + putShortMSB(s, strm.adler >>> 16); + putShortMSB(s, strm.adler & 0xffff); + } + + flush_pending(strm); + /* If avail_out is zero, the application will call deflate again + * to flush the rest. + */ + if (s.wrap > 0) { + s.wrap = -s.wrap; + } + /* write the trailer only once! */ + return s.pending !== 0 ? Z_OK$2 : Z_STREAM_END$2; + } + + function deflateEnd(strm) { + var status; + + if (!strm /*== Z_NULL*/ || !strm.state /*== Z_NULL*/ ) { + return Z_STREAM_ERROR$2; + } + + status = strm.state.status; + if (status !== INIT_STATE && + status !== EXTRA_STATE && + status !== NAME_STATE && + status !== COMMENT_STATE && + status !== HCRC_STATE && + status !== BUSY_STATE && + status !== FINISH_STATE + ) { + return err(strm, Z_STREAM_ERROR$2); + } + + strm.state = null; + + return status === BUSY_STATE ? err(strm, Z_DATA_ERROR$2) : Z_OK$2; + } + + /* Not implemented + exports.deflateBound = deflateBound; + exports.deflateCopy = deflateCopy; + exports.deflateParams = deflateParams; + exports.deflatePending = deflatePending; + exports.deflatePrime = deflatePrime; + exports.deflateTune = deflateTune; + */ + + // See state defs from inflate.js + var BAD$1 = 30; /* got a data error -- remain here until reset */ + var TYPE$1 = 12; /* i: waiting for type bits, including last-flag bit */ + + /* + Decode literal, length, and distance codes and write out the resulting + literal and match bytes until either not enough input or output is + available, an end-of-block is encountered, or a data error is encountered. + When large enough input and output buffers are supplied to inflate(), for + example, a 16K input buffer and a 64K output buffer, more than 95% of the + inflate execution time is spent in this routine. + + Entry assumptions: + + state.mode === LEN + strm.avail_in >= 6 + strm.avail_out >= 258 + start >= strm.avail_out + state.bits < 8 + + On return, state.mode is one of: + + LEN -- ran out of enough output space or enough available input + TYPE -- reached end of block code, inflate() to interpret next block + BAD -- error in block data + + Notes: + + - The maximum input bits used by a length/distance pair is 15 bits for the + length code, 5 bits for the length extra, 15 bits for the distance code, + and 13 bits for the distance extra. This totals 48 bits, or six bytes. + Therefore if strm.avail_in >= 6, then there is enough input to avoid + checking for available input while decoding. + + - The maximum bytes that a single length/distance pair can output is 258 + bytes, which is the maximum length that can be coded. inflate_fast() + requires strm.avail_out >= 258 for each loop to avoid checking for + output space. + */ + function inflate_fast(strm, start) { + var state; + var _in; /* local strm.input */ + var last; /* have enough input while in < last */ + var _out; /* local strm.output */ + var beg; /* inflate()'s initial strm.output */ + var end; /* while out < end, enough space available */ + //#ifdef INFLATE_STRICT + var dmax; /* maximum distance from zlib header */ + //#endif + var wsize; /* window size or zero if not using window */ + var whave; /* valid bytes in the window */ + var wnext; /* window write index */ + // Use `s_window` instead `window`, avoid conflict with instrumentation tools + var s_window; /* allocated sliding window, if wsize != 0 */ + var hold; /* local strm.hold */ + var bits; /* local strm.bits */ + var lcode; /* local strm.lencode */ + var dcode; /* local strm.distcode */ + var lmask; /* mask for first level of length codes */ + var dmask; /* mask for first level of distance codes */ + var here; /* retrieved table entry */ + var op; /* code bits, operation, extra bits, or */ + /* window position, window bytes to copy */ + var len; /* match length, unused bytes */ + var dist; /* match distance */ + var from; /* where to copy match from */ + var from_source; + + + var input, output; // JS specific, because we have no pointers + + /* copy state to local variables */ + state = strm.state; + //here = state.here; + _in = strm.next_in; + input = strm.input; + last = _in + (strm.avail_in - 5); + _out = strm.next_out; + output = strm.output; + beg = _out - (start - strm.avail_out); + end = _out + (strm.avail_out - 257); + //#ifdef INFLATE_STRICT + dmax = state.dmax; + //#endif + wsize = state.wsize; + whave = state.whave; + wnext = state.wnext; + s_window = state.window; + hold = state.hold; + bits = state.bits; + lcode = state.lencode; + dcode = state.distcode; + lmask = (1 << state.lenbits) - 1; + dmask = (1 << state.distbits) - 1; + + + /* decode literals and length/distances until end-of-block or not enough + input data or output space */ + + top: + do { + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + + here = lcode[hold & lmask]; + + dolen: + for (;;) { // Goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + if (op === 0) { /* literal */ + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + output[_out++] = here & 0xffff/*here.val*/; + } + else if (op & 16) { /* length base */ + len = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (op) { + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + len += hold & ((1 << op) - 1); + hold >>>= op; + bits -= op; + } + //Tracevv((stderr, "inflate: length %u\n", len)); + if (bits < 15) { + hold += input[_in++] << bits; + bits += 8; + hold += input[_in++] << bits; + bits += 8; + } + here = dcode[hold & dmask]; + + dodist: + for (;;) { // goto emulation + op = here >>> 24/*here.bits*/; + hold >>>= op; + bits -= op; + op = (here >>> 16) & 0xff/*here.op*/; + + if (op & 16) { /* distance base */ + dist = here & 0xffff/*here.val*/; + op &= 15; /* number of extra bits */ + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + if (bits < op) { + hold += input[_in++] << bits; + bits += 8; + } + } + dist += hold & ((1 << op) - 1); + //#ifdef INFLATE_STRICT + if (dist > dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$1; + break top; + } + //#endif + hold >>>= op; + bits -= op; + //Tracevv((stderr, "inflate: distance %u\n", dist)); + op = _out - beg; /* max distance in output */ + if (dist > op) { /* see if copy from window */ + op = dist - op; /* distance back in window */ + if (op > whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD$1; + break top; + } + + // (!) This block is disabled in zlib defailts, + // don't enable it for binary compatibility + //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + // if (len <= op - whave) { + // do { + // output[_out++] = 0; + // } while (--len); + // continue top; + // } + // len -= op - whave; + // do { + // output[_out++] = 0; + // } while (--op > whave); + // if (op === 0) { + // from = _out - dist; + // do { + // output[_out++] = output[from++]; + // } while (--len); + // continue top; + // } + //#endif + } + from = 0; // window index + from_source = s_window; + if (wnext === 0) { /* very common case */ + from += wsize - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + else if (wnext < op) { /* wrap around window */ + from += wsize + wnext - op; + op -= wnext; + if (op < len) { /* some from end of window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = 0; + if (wnext < len) { /* some from start of window */ + op = wnext; + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + } + else { /* contiguous in window */ + from += wnext - op; + if (op < len) { /* some from window */ + len -= op; + do { + output[_out++] = s_window[from++]; + } while (--op); + from = _out - dist; /* rest from output */ + from_source = output; + } + } + while (len > 2) { + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + output[_out++] = from_source[from++]; + len -= 3; + } + if (len) { + output[_out++] = from_source[from++]; + if (len > 1) { + output[_out++] = from_source[from++]; + } + } + } + else { + from = _out - dist; /* copy direct from output */ + do { /* minimum length is three */ + output[_out++] = output[from++]; + output[_out++] = output[from++]; + output[_out++] = output[from++]; + len -= 3; + } while (len > 2); + if (len) { + output[_out++] = output[from++]; + if (len > 1) { + output[_out++] = output[from++]; + } + } + } + } + else if ((op & 64) === 0) { /* 2nd level distance code */ + here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dodist; + } + else { + strm.msg = 'invalid distance code'; + state.mode = BAD$1; + break top; + } + + break; // need to emulate goto via "continue" + } + } + else if ((op & 64) === 0) { /* 2nd level length code */ + here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))]; + continue dolen; + } + else if (op & 32) { /* end-of-block */ + //Tracevv((stderr, "inflate: end of block\n")); + state.mode = TYPE$1; + break top; + } + else { + strm.msg = 'invalid literal/length code'; + state.mode = BAD$1; + break top; + } + + break; // need to emulate goto via "continue" + } + } while (_in < last && _out < end); + + /* return unused bytes (on entry, bits < 8, so in won't go too far back) */ + len = bits >> 3; + _in -= len; + bits -= len << 3; + hold &= (1 << bits) - 1; + + /* update state and return */ + strm.next_in = _in; + strm.next_out = _out; + strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last)); + strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end)); + state.hold = hold; + state.bits = bits; + return; + } + + var MAXBITS = 15; + var ENOUGH_LENS$1 = 852; + var ENOUGH_DISTS$1 = 592; + //var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS); + + var CODES$1 = 0; + var LENS$1 = 1; + var DISTS$1 = 2; + + var lbase = [ /* Length codes 257..285 base */ + 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, + 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258, 0, 0 + ]; + + var lext = [ /* Length codes 257..285 extra */ + 16, 16, 16, 16, 16, 16, 16, 16, 17, 17, 17, 17, 18, 18, 18, 18, + 19, 19, 19, 19, 20, 20, 20, 20, 21, 21, 21, 21, 16, 72, 78 + ]; + + var dbase = [ /* Distance codes 0..29 base */ + 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, + 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, + 8193, 12289, 16385, 24577, 0, 0 + ]; + + var dext = [ /* Distance codes 0..29 extra */ + 16, 16, 16, 16, 17, 17, 18, 18, 19, 19, 20, 20, 21, 21, 22, 22, + 23, 23, 24, 24, 25, 25, 26, 26, 27, 27, + 28, 28, 29, 29, 64, 64 + ]; + + function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts) { + var bits = opts.bits; + //here = opts.here; /* table entry for duplication */ + + var len = 0; /* a code's length in bits */ + var sym = 0; /* index of code symbols */ + var min = 0, + max = 0; /* minimum and maximum code lengths */ + var root = 0; /* number of index bits for root table */ + var curr = 0; /* number of index bits for current table */ + var drop = 0; /* code bits to drop for sub-table */ + var left = 0; /* number of prefix codes available */ + var used = 0; /* code entries in table used */ + var huff = 0; /* Huffman code */ + var incr; /* for incrementing code, index */ + var fill; /* index for replicating entries */ + var low; /* low bits for current root entry */ + var mask; /* mask for low root bits */ + var next; /* next available space in table */ + var base = null; /* base value table to use */ + var base_index = 0; + // var shoextra; /* extra bits table to use */ + var end; /* use base and extra for symbol > end */ + var count = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* number of codes of each length */ + var offs = new Buf16(MAXBITS + 1); //[MAXBITS+1]; /* offsets in table for each length */ + var extra = null; + var extra_index = 0; + + var here_bits, here_op, here_val; + + /* + Process a set of code lengths to create a canonical Huffman code. The + code lengths are lens[0..codes-1]. Each length corresponds to the + symbols 0..codes-1. The Huffman code is generated by first sorting the + symbols by length from short to long, and retaining the symbol order + for codes with equal lengths. Then the code starts with all zero bits + for the first code of the shortest length, and the codes are integer + increments for the same length, and zeros are appended as the length + increases. For the deflate format, these bits are stored backwards + from their more natural integer increment ordering, and so when the + decoding tables are built in the large loop below, the integer codes + are incremented backwards. + + This routine assumes, but does not check, that all of the entries in + lens[] are in the range 0..MAXBITS. The caller must assure this. + 1..MAXBITS is interpreted as that code length. zero means that that + symbol does not occur in this code. + + The codes are sorted by computing a count of codes for each length, + creating from that a table of starting indices for each length in the + sorted table, and then entering the symbols in order in the sorted + table. The sorted table is work[], with that space being provided by + the caller. + + The length counts are used for other purposes as well, i.e. finding + the minimum and maximum length codes, determining if there are any + codes at all, checking for a valid set of lengths, and looking ahead + at length counts to determine sub-table sizes when building the + decoding tables. + */ + + /* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */ + for (len = 0; len <= MAXBITS; len++) { + count[len] = 0; + } + for (sym = 0; sym < codes; sym++) { + count[lens[lens_index + sym]]++; + } + + /* bound code lengths, force root to be within code lengths */ + root = bits; + for (max = MAXBITS; max >= 1; max--) { + if (count[max] !== 0) { + break; + } + } + if (root > max) { + root = max; + } + if (max === 0) { /* no symbols to code at all */ + //table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */ + //table.bits[opts.table_index] = 1; //here.bits = (var char)1; + //table.val[opts.table_index++] = 0; //here.val = (var short)0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + + //table.op[opts.table_index] = 64; + //table.bits[opts.table_index] = 1; + //table.val[opts.table_index++] = 0; + table[table_index++] = (1 << 24) | (64 << 16) | 0; + + opts.bits = 1; + return 0; /* no symbols, but wait for decoding to report error */ + } + for (min = 1; min < max; min++) { + if (count[min] !== 0) { + break; + } + } + if (root < min) { + root = min; + } + + /* check for an over-subscribed or incomplete set of lengths */ + left = 1; + for (len = 1; len <= MAXBITS; len++) { + left <<= 1; + left -= count[len]; + if (left < 0) { + return -1; + } /* over-subscribed */ + } + if (left > 0 && (type === CODES$1 || max !== 1)) { + return -1; /* incomplete set */ + } + + /* generate offsets into symbol table for each length for sorting */ + offs[1] = 0; + for (len = 1; len < MAXBITS; len++) { + offs[len + 1] = offs[len] + count[len]; + } + + /* sort symbols by length, by symbol order within each length */ + for (sym = 0; sym < codes; sym++) { + if (lens[lens_index + sym] !== 0) { + work[offs[lens[lens_index + sym]]++] = sym; + } + } + + /* + Create and fill in decoding tables. In this loop, the table being + filled is at next and has curr index bits. The code being used is huff + with length len. That code is converted to an index by dropping drop + bits off of the bottom. For codes where len is less than drop + curr, + those top drop + curr - len bits are incremented through all values to + fill the table with replicated entries. + + root is the number of index bits for the root table. When len exceeds + root, sub-tables are created pointed to by the root entry with an index + of the low root bits of huff. This is saved in low to check for when a + new sub-table should be started. drop is zero when the root table is + being filled, and drop is root when sub-tables are being filled. + + When a new sub-table is needed, it is necessary to look ahead in the + code lengths to determine what size sub-table is needed. The length + counts are used for this, and so count[] is decremented as codes are + entered in the tables. + + used keeps track of how many table entries have been allocated from the + provided *table space. It is checked for LENS and DIST tables against + the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in + the initial root table size constants. See the comments in inftrees.h + for more information. + + sym increments through all symbols, and the loop terminates when + all codes of length max, i.e. all codes, have been processed. This + routine permits incomplete codes, so another loop after this one fills + in the rest of the decoding tables with invalid code markers. + */ + + /* set up for code type */ + // poor man optimization - use if-else instead of switch, + // to avoid deopts in old v8 + if (type === CODES$1) { + base = extra = work; /* dummy value--not used */ + end = 19; + + } else if (type === LENS$1) { + base = lbase; + base_index -= 257; + extra = lext; + extra_index -= 257; + end = 256; + + } else { /* DISTS */ + base = dbase; + extra = dext; + end = -1; + } + + /* initialize opts for loop */ + huff = 0; /* starting code */ + sym = 0; /* starting code symbol */ + len = min; /* starting code length */ + next = table_index; /* current table to fill in */ + curr = root; /* current table index bits */ + drop = 0; /* current bits to drop from code for index */ + low = -1; /* trigger new sub-table when len > root */ + used = 1 << root; /* use root table entries */ + mask = used - 1; /* mask for comparing low */ + + /* check available table space */ + if ((type === LENS$1 && used > ENOUGH_LENS$1) || + (type === DISTS$1 && used > ENOUGH_DISTS$1)) { + return 1; + } + /* process all codes and make table entries */ + for (;;) { + /* create table entry */ + here_bits = len - drop; + if (work[sym] < end) { + here_op = 0; + here_val = work[sym]; + } else if (work[sym] > end) { + here_op = extra[extra_index + work[sym]]; + here_val = base[base_index + work[sym]]; + } else { + here_op = 32 + 64; /* end of block */ + here_val = 0; + } + + /* replicate for those indices with low len bits equal to huff */ + incr = 1 << (len - drop); + fill = 1 << curr; + min = fill; /* save offset to next table */ + do { + fill -= incr; + table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val | 0; + } while (fill !== 0); + + /* backwards increment the len-bit code huff */ + incr = 1 << (len - 1); + while (huff & incr) { + incr >>= 1; + } + if (incr !== 0) { + huff &= incr - 1; + huff += incr; + } else { + huff = 0; + } + + /* go to next symbol, update count, len */ + sym++; + if (--count[len] === 0) { + if (len === max) { + break; + } + len = lens[lens_index + work[sym]]; + } + + /* create new sub-table if needed */ + if (len > root && (huff & mask) !== low) { + /* if first time, transition to sub-tables */ + if (drop === 0) { + drop = root; + } + + /* increment past last table */ + next += min; /* here min is 1 << curr */ + + /* determine length of next table */ + curr = len - drop; + left = 1 << curr; + while (curr + drop < max) { + left -= count[curr + drop]; + if (left <= 0) { + break; + } + curr++; + left <<= 1; + } + + /* check for enough space */ + used += 1 << curr; + if ((type === LENS$1 && used > ENOUGH_LENS$1) || + (type === DISTS$1 && used > ENOUGH_DISTS$1)) { + return 1; + } + + /* point entry in root table to sub-table */ + low = huff & mask; + /*table.op[low] = curr; + table.bits[low] = root; + table.val[low] = next - opts.table_index;*/ + table[low] = (root << 24) | (curr << 16) | (next - table_index) | 0; + } + } + + /* fill in remaining table entry if code is incomplete (guaranteed to have + at most one remaining entry, since if the code is incomplete, the + maximum code length that was allowed to get this far is one bit) */ + if (huff !== 0) { + //table.op[next + huff] = 64; /* invalid code marker */ + //table.bits[next + huff] = len - drop; + //table.val[next + huff] = 0; + table[next + huff] = ((len - drop) << 24) | (64 << 16) | 0; + } + + /* set return parameters */ + //opts.table_index += used; + opts.bits = root; + return 0; + } + + var CODES = 0; + var LENS = 1; + var DISTS = 2; + + /* Public constants ==========================================================*/ + /* ===========================================================================*/ + + + /* Allowed flush values; see deflate() and inflate() below for details */ + //var Z_NO_FLUSH = 0; + //var Z_PARTIAL_FLUSH = 1; + //var Z_SYNC_FLUSH = 2; + //var Z_FULL_FLUSH = 3; + var Z_FINISH$1 = 4; + var Z_BLOCK$1 = 5; + var Z_TREES$1 = 6; + + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + var Z_OK$1 = 0; + var Z_STREAM_END$1 = 1; + var Z_NEED_DICT$1 = 2; + //var Z_ERRNO = -1; + var Z_STREAM_ERROR$1 = -2; + var Z_DATA_ERROR$1 = -3; + var Z_MEM_ERROR = -4; + var Z_BUF_ERROR$1 = -5; + //var Z_VERSION_ERROR = -6; + + /* The deflate compression method */ + var Z_DEFLATED$1 = 8; + + + /* STATES ====================================================================*/ + /* ===========================================================================*/ + + + var HEAD = 1; /* i: waiting for magic header */ + var FLAGS = 2; /* i: waiting for method and flags (gzip) */ + var TIME = 3; /* i: waiting for modification time (gzip) */ + var OS = 4; /* i: waiting for extra flags and operating system (gzip) */ + var EXLEN = 5; /* i: waiting for extra length (gzip) */ + var EXTRA = 6; /* i: waiting for extra bytes (gzip) */ + var NAME = 7; /* i: waiting for end of file name (gzip) */ + var COMMENT = 8; /* i: waiting for end of comment (gzip) */ + var HCRC = 9; /* i: waiting for header crc (gzip) */ + var DICTID = 10; /* i: waiting for dictionary check value */ + var DICT = 11; /* waiting for inflateSetDictionary() call */ + var TYPE = 12; /* i: waiting for type bits, including last-flag bit */ + var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */ + var STORED = 14; /* i: waiting for stored size (length and complement) */ + var COPY_ = 15; /* i/o: same as COPY below, but only first time in */ + var COPY = 16; /* i/o: waiting for input or output to copy stored block */ + var TABLE = 17; /* i: waiting for dynamic block table lengths */ + var LENLENS = 18; /* i: waiting for code length code lengths */ + var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */ + var LEN_ = 20; /* i: same as LEN below, but only first time in */ + var LEN = 21; /* i: waiting for length/lit/eob code */ + var LENEXT = 22; /* i: waiting for length extra bits */ + var DIST = 23; /* i: waiting for distance code */ + var DISTEXT = 24; /* i: waiting for distance extra bits */ + var MATCH = 25; /* o: waiting for output space to copy string */ + var LIT = 26; /* o: waiting for output space to write literal */ + var CHECK = 27; /* i: waiting for 32-bit check value */ + var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */ + var DONE = 29; /* finished check, done -- remain here until reset */ + var BAD = 30; /* got a data error -- remain here until reset */ + var MEM = 31; /* got an inflate() memory error -- remain here until reset */ + var SYNC = 32; /* looking for synchronization bytes to restart inflate() */ + + /* ===========================================================================*/ + + + + var ENOUGH_LENS = 852; + var ENOUGH_DISTS = 592; + + + function zswap32(q) { + return (((q >>> 24) & 0xff) + + ((q >>> 8) & 0xff00) + + ((q & 0xff00) << 8) + + ((q & 0xff) << 24)); + } + + + function InflateState() { + this.mode = 0; /* current inflate mode */ + this.last = false; /* true if processing last block */ + this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */ + this.havedict = false; /* true if dictionary provided */ + this.flags = 0; /* gzip header method and flags (0 if zlib) */ + this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */ + this.check = 0; /* protected copy of check value */ + this.total = 0; /* protected copy of output count */ + // TODO: may be {} + this.head = null; /* where to save gzip header information */ + + /* sliding window */ + this.wbits = 0; /* log base 2 of requested window size */ + this.wsize = 0; /* window size or zero if not using window */ + this.whave = 0; /* valid bytes in the window */ + this.wnext = 0; /* window write index */ + this.window = null; /* allocated sliding window, if needed */ + + /* bit accumulator */ + this.hold = 0; /* input bit accumulator */ + this.bits = 0; /* number of bits in "in" */ + + /* for string and stored block copying */ + this.length = 0; /* literal or length of data to copy */ + this.offset = 0; /* distance back to copy string from */ + + /* for table and code decoding */ + this.extra = 0; /* extra bits needed */ + + /* fixed and dynamic code tables */ + this.lencode = null; /* starting table for length/literal codes */ + this.distcode = null; /* starting table for distance codes */ + this.lenbits = 0; /* index bits for lencode */ + this.distbits = 0; /* index bits for distcode */ + + /* dynamic table building */ + this.ncode = 0; /* number of code length code lengths */ + this.nlen = 0; /* number of length code lengths */ + this.ndist = 0; /* number of distance code lengths */ + this.have = 0; /* number of code lengths in lens[] */ + this.next = null; /* next available space in codes[] */ + + this.lens = new Buf16(320); /* temporary storage for code lengths */ + this.work = new Buf16(288); /* work area for code table building */ + + /* + because we don't have pointers in js, we use lencode and distcode directly + as buffers so we don't need codes + */ + //this.codes = new Buf32(ENOUGH); /* space for code tables */ + this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */ + this.distdyn = null; /* dynamic table for distance codes (JS specific) */ + this.sane = 0; /* if false, allow invalid distance too far */ + this.back = 0; /* bits back of last unprocessed length/lit */ + this.was = 0; /* initial length of match */ + } + + function inflateResetKeep(strm) { + var state; + + if (!strm || !strm.state) { + return Z_STREAM_ERROR$1; + } + state = strm.state; + strm.total_in = strm.total_out = state.total = 0; + strm.msg = ''; /*Z_NULL*/ + if (state.wrap) { /* to support ill-conceived Java test suite */ + strm.adler = state.wrap & 1; + } + state.mode = HEAD; + state.last = 0; + state.havedict = 0; + state.dmax = 32768; + state.head = null /*Z_NULL*/ ; + state.hold = 0; + state.bits = 0; + //state.lencode = state.distcode = state.next = state.codes; + state.lencode = state.lendyn = new Buf32(ENOUGH_LENS); + state.distcode = state.distdyn = new Buf32(ENOUGH_DISTS); + + state.sane = 1; + state.back = -1; + //Tracev((stderr, "inflate: reset\n")); + return Z_OK$1; + } + + function inflateReset(strm) { + var state; + + if (!strm || !strm.state) { + return Z_STREAM_ERROR$1; + } + state = strm.state; + state.wsize = 0; + state.whave = 0; + state.wnext = 0; + return inflateResetKeep(strm); + + } + + function inflateReset2(strm, windowBits) { + var wrap; + var state; + + /* get the state */ + if (!strm || !strm.state) { + return Z_STREAM_ERROR$1; + } + state = strm.state; + + /* extract wrap request from windowBits parameter */ + if (windowBits < 0) { + wrap = 0; + windowBits = -windowBits; + } else { + wrap = (windowBits >> 4) + 1; + if (windowBits < 48) { + windowBits &= 15; + } + } + + /* set number of window bits, free window if different */ + if (windowBits && (windowBits < 8 || windowBits > 15)) { + return Z_STREAM_ERROR$1; + } + if (state.window !== null && state.wbits !== windowBits) { + state.window = null; + } + + /* update state and reset the rest of it */ + state.wrap = wrap; + state.wbits = windowBits; + return inflateReset(strm); + } + + function inflateInit2(strm, windowBits) { + var ret; + var state; + + if (!strm) { + return Z_STREAM_ERROR$1; + } + //strm.msg = Z_NULL; /* in case we return an error */ + + state = new InflateState(); + + //if (state === Z_NULL) return Z_MEM_ERROR; + //Tracev((stderr, "inflate: allocated\n")); + strm.state = state; + state.window = null /*Z_NULL*/ ; + ret = inflateReset2(strm, windowBits); + if (ret !== Z_OK$1) { + strm.state = null /*Z_NULL*/ ; + } + return ret; + } + + + /* + Return state with length and distance decoding tables and index sizes set to + fixed code decoding. Normally this returns fixed tables from inffixed.h. + If BUILDFIXED is defined, then instead this routine builds the tables the + first time it's called, and returns those tables the first time and + thereafter. This reduces the size of the code by about 2K bytes, in + exchange for a little execution time. However, BUILDFIXED should not be + used for threaded applications, since the rewriting of the tables and virgin + may not be thread-safe. + */ + var virgin = true; + + var lenfix, distfix; // We have no pointers in JS, so keep tables separate + + function fixedtables(state) { + /* build fixed huffman tables if first call (may not be thread safe) */ + if (virgin) { + var sym; + + lenfix = new Buf32(512); + distfix = new Buf32(32); + + /* literal/length table */ + sym = 0; + while (sym < 144) { + state.lens[sym++] = 8; + } + while (sym < 256) { + state.lens[sym++] = 9; + } + while (sym < 280) { + state.lens[sym++] = 7; + } + while (sym < 288) { + state.lens[sym++] = 8; + } + + inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, { + bits: 9 + }); + + /* distance table */ + sym = 0; + while (sym < 32) { + state.lens[sym++] = 5; + } + + inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, { + bits: 5 + }); + + /* do this just once */ + virgin = false; + } + + state.lencode = lenfix; + state.lenbits = 9; + state.distcode = distfix; + state.distbits = 5; + } + + + /* + Update the window with the last wsize (normally 32K) bytes written before + returning. If window does not exist yet, create it. This is only called + when a window is already in use, or when output has been written during this + inflate call, but the end of the deflate stream has not been reached yet. + It is also called to create a window for dictionary data when a dictionary + is loaded. + + Providing output buffers larger than 32K to inflate() should provide a speed + advantage, since only the last 32K of output is copied to the sliding window + upon return from inflate(), and since all distances after the first 32K of + output will fall in the output data, making match copies simpler and faster. + The advantage may be dependent on the size of the processor's data caches. + */ + function updatewindow(strm, src, end, copy) { + var dist; + var state = strm.state; + + /* if it hasn't been done already, allocate space for the window */ + if (state.window === null) { + state.wsize = 1 << state.wbits; + state.wnext = 0; + state.whave = 0; + + state.window = new Buf8(state.wsize); + } + + /* copy state->wsize or less output bytes into the circular window */ + if (copy >= state.wsize) { + arraySet(state.window, src, end - state.wsize, state.wsize, 0); + state.wnext = 0; + state.whave = state.wsize; + } else { + dist = state.wsize - state.wnext; + if (dist > copy) { + dist = copy; + } + //zmemcpy(state->window + state->wnext, end - copy, dist); + arraySet(state.window, src, end - copy, dist, state.wnext); + copy -= dist; + if (copy) { + //zmemcpy(state->window, end - copy, copy); + arraySet(state.window, src, end - copy, copy, 0); + state.wnext = copy; + state.whave = state.wsize; + } else { + state.wnext += dist; + if (state.wnext === state.wsize) { + state.wnext = 0; + } + if (state.whave < state.wsize) { + state.whave += dist; + } + } + } + return 0; + } + + function inflate$1(strm, flush) { + var state; + var input, output; // input/output buffers + var next; /* next input INDEX */ + var put; /* next output INDEX */ + var have, left; /* available input and output */ + var hold; /* bit buffer */ + var bits; /* bits in bit buffer */ + var _in, _out; /* save starting available input and output */ + var copy; /* number of stored or match bytes to copy */ + var from; /* where to copy match bytes from */ + var from_source; + var here = 0; /* current decoding table entry */ + var here_bits, here_op, here_val; // paked "here" denormalized (JS specific) + //var last; /* parent table entry */ + var last_bits, last_op, last_val; // paked "last" denormalized (JS specific) + var len; /* length to copy for repeats, bits to drop */ + var ret; /* return code */ + var hbuf = new Buf8(4); /* buffer for gzip header crc calculation */ + var opts; + + var n; // temporary var for NEED_BITS + + var order = /* permutation of code lengths */ [16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15]; + + + if (!strm || !strm.state || !strm.output || + (!strm.input && strm.avail_in !== 0)) { + return Z_STREAM_ERROR$1; + } + + state = strm.state; + if (state.mode === TYPE) { + state.mode = TYPEDO; + } /* skip check */ + + + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + _in = have; + _out = left; + ret = Z_OK$1; + + inf_leave: // goto emulation + for (;;) { + switch (state.mode) { + case HEAD: + if (state.wrap === 0) { + state.mode = TYPEDO; + break; + } + //=== NEEDBITS(16); + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */ + state.check = 0 /*crc32(0L, Z_NULL, 0)*/ ; + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = FLAGS; + break; + } + state.flags = 0; /* expect zlib header */ + if (state.head) { + state.head.done = false; + } + if (!(state.wrap & 1) || /* check if zlib header allowed */ + (((hold & 0xff) /*BITS(8)*/ << 8) + (hold >> 8)) % 31) { + strm.msg = 'incorrect header check'; + state.mode = BAD; + break; + } + if ((hold & 0x0f) /*BITS(4)*/ !== Z_DEFLATED$1) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + len = (hold & 0x0f) /*BITS(4)*/ + 8; + if (state.wbits === 0) { + state.wbits = len; + } else if (len > state.wbits) { + strm.msg = 'invalid window size'; + state.mode = BAD; + break; + } + state.dmax = 1 << len; + //Tracev((stderr, "inflate: zlib header ok\n")); + strm.adler = state.check = 1 /*adler32(0L, Z_NULL, 0)*/ ; + state.mode = hold & 0x200 ? DICTID : TYPE; + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + break; + case FLAGS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.flags = hold; + if ((state.flags & 0xff) !== Z_DEFLATED$1) { + strm.msg = 'unknown compression method'; + state.mode = BAD; + break; + } + if (state.flags & 0xe000) { + strm.msg = 'unknown header flags set'; + state.mode = BAD; + break; + } + if (state.head) { + state.head.text = ((hold >> 8) & 1); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = TIME; + /* falls through */ + case TIME: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.time = hold; + } + if (state.flags & 0x0200) { + //=== CRC4(state.check, hold) + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + hbuf[2] = (hold >>> 16) & 0xff; + hbuf[3] = (hold >>> 24) & 0xff; + state.check = crc32(state.check, hbuf, 4, 0); + //=== + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = OS; + /* falls through */ + case OS: + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (state.head) { + state.head.xflags = (hold & 0xff); + state.head.os = (hold >> 8); + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = EXLEN; + /* falls through */ + case EXLEN: + if (state.flags & 0x0400) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length = hold; + if (state.head) { + state.head.extra_len = hold; + } + if (state.flags & 0x0200) { + //=== CRC2(state.check, hold); + hbuf[0] = hold & 0xff; + hbuf[1] = (hold >>> 8) & 0xff; + state.check = crc32(state.check, hbuf, 2, 0); + //===// + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } else if (state.head) { + state.head.extra = null /*Z_NULL*/ ; + } + state.mode = EXTRA; + /* falls through */ + case EXTRA: + if (state.flags & 0x0400) { + copy = state.length; + if (copy > have) { + copy = have; + } + if (copy) { + if (state.head) { + len = state.head.extra_len - state.length; + if (!state.head.extra) { + // Use untyped array for more conveniend processing later + state.head.extra = new Array(state.head.extra_len); + } + arraySet( + state.head.extra, + input, + next, + // extra field is limited to 65536 bytes + // - no need for additional size check + copy, + /*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/ + len + ); + //zmemcpy(state.head.extra + len, next, + // len + copy > state.head.extra_max ? + // state.head.extra_max - len : copy); + } + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + state.length -= copy; + } + if (state.length) { + break inf_leave; + } + } + state.length = 0; + state.mode = NAME; + /* falls through */ + case NAME: + if (state.flags & 0x0800) { + if (have === 0) { + break inf_leave; + } + copy = 0; + do { + // TODO: 2 or 1 bytes? + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.name_max*/ )) { + state.head.name += String.fromCharCode(len); + } + } while (len && copy < have); + + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { + break inf_leave; + } + } else if (state.head) { + state.head.name = null; + } + state.length = 0; + state.mode = COMMENT; + /* falls through */ + case COMMENT: + if (state.flags & 0x1000) { + if (have === 0) { + break inf_leave; + } + copy = 0; + do { + len = input[next + copy++]; + /* use constant limit because in js we should not preallocate memory */ + if (state.head && len && + (state.length < 65536 /*state.head.comm_max*/ )) { + state.head.comment += String.fromCharCode(len); + } + } while (len && copy < have); + if (state.flags & 0x0200) { + state.check = crc32(state.check, input, copy, next); + } + have -= copy; + next += copy; + if (len) { + break inf_leave; + } + } else if (state.head) { + state.head.comment = null; + } + state.mode = HCRC; + /* falls through */ + case HCRC: + if (state.flags & 0x0200) { + //=== NEEDBITS(16); */ + while (bits < 16) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.check & 0xffff)) { + strm.msg = 'header crc mismatch'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + } + if (state.head) { + state.head.hcrc = ((state.flags >> 9) & 1); + state.head.done = true; + } + strm.adler = state.check = 0; + state.mode = TYPE; + break; + case DICTID: + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + strm.adler = state.check = zswap32(hold); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = DICT; + /* falls through */ + case DICT: + if (state.havedict === 0) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + return Z_NEED_DICT$1; + } + strm.adler = state.check = 1 /*adler32(0L, Z_NULL, 0)*/ ; + state.mode = TYPE; + /* falls through */ + case TYPE: + if (flush === Z_BLOCK$1 || flush === Z_TREES$1) { + break inf_leave; + } + /* falls through */ + case TYPEDO: + if (state.last) { + //--- BYTEBITS() ---// + hold >>>= bits & 7; + bits -= bits & 7; + //---// + state.mode = CHECK; + break; + } + //=== NEEDBITS(3); */ + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.last = (hold & 0x01) /*BITS(1)*/ ; + //--- DROPBITS(1) ---// + hold >>>= 1; + bits -= 1; + //---// + + switch ((hold & 0x03) /*BITS(2)*/ ) { + case 0: + /* stored block */ + //Tracev((stderr, "inflate: stored block%s\n", + // state.last ? " (last)" : "")); + state.mode = STORED; + break; + case 1: + /* fixed block */ + fixedtables(state); + //Tracev((stderr, "inflate: fixed codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = LEN_; /* decode codes */ + if (flush === Z_TREES$1) { + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break inf_leave; + } + break; + case 2: + /* dynamic block */ + //Tracev((stderr, "inflate: dynamic codes block%s\n", + // state.last ? " (last)" : "")); + state.mode = TABLE; + break; + case 3: + strm.msg = 'invalid block type'; + state.mode = BAD; + } + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + break; + case STORED: + //--- BYTEBITS() ---// /* go to byte boundary */ + hold >>>= bits & 7; + bits -= bits & 7; + //---// + //=== NEEDBITS(32); */ + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) { + strm.msg = 'invalid stored block lengths'; + state.mode = BAD; + break; + } + state.length = hold & 0xffff; + //Tracev((stderr, "inflate: stored length %u\n", + // state.length)); + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + state.mode = COPY_; + if (flush === Z_TREES$1) { + break inf_leave; + } + /* falls through */ + case COPY_: + state.mode = COPY; + /* falls through */ + case COPY: + copy = state.length; + if (copy) { + if (copy > have) { + copy = have; + } + if (copy > left) { + copy = left; + } + if (copy === 0) { + break inf_leave; + } + //--- zmemcpy(put, next, copy); --- + arraySet(output, input, next, copy, put); + //---// + have -= copy; + next += copy; + left -= copy; + put += copy; + state.length -= copy; + break; + } + //Tracev((stderr, "inflate: stored end\n")); + state.mode = TYPE; + break; + case TABLE: + //=== NEEDBITS(14); */ + while (bits < 14) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.nlen = (hold & 0x1f) /*BITS(5)*/ + 257; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ndist = (hold & 0x1f) /*BITS(5)*/ + 1; + //--- DROPBITS(5) ---// + hold >>>= 5; + bits -= 5; + //---// + state.ncode = (hold & 0x0f) /*BITS(4)*/ + 4; + //--- DROPBITS(4) ---// + hold >>>= 4; + bits -= 4; + //---// + //#ifndef PKZIP_BUG_WORKAROUND + if (state.nlen > 286 || state.ndist > 30) { + strm.msg = 'too many length or distance symbols'; + state.mode = BAD; + break; + } + //#endif + //Tracev((stderr, "inflate: table sizes ok\n")); + state.have = 0; + state.mode = LENLENS; + /* falls through */ + case LENLENS: + while (state.have < state.ncode) { + //=== NEEDBITS(3); + while (bits < 3) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.lens[order[state.have++]] = (hold & 0x07); //BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } + while (state.have < 19) { + state.lens[order[state.have++]] = 0; + } + // We have separate tables & no pointers. 2 commented lines below not needed. + //state.next = state.codes; + //state.lencode = state.next; + // Switch to use dynamic table + state.lencode = state.lendyn; + state.lenbits = 7; + + opts = { + bits: state.lenbits + }; + ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts); + state.lenbits = opts.bits; + + if (ret) { + strm.msg = 'invalid code lengths set'; + state.mode = BAD; + break; + } + //Tracev((stderr, "inflate: code lengths ok\n")); + state.have = 0; + state.mode = CODELENS; + /* falls through */ + case CODELENS: + while (state.have < state.nlen + state.ndist) { + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { + break; + } + //--- PULLBYTE() ---// + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_val < 16) { + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.lens[state.have++] = here_val; + } else { + if (here_val === 16) { + //=== NEEDBITS(here.bits + 2); + n = here_bits + 2; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + if (state.have === 0) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + len = state.lens[state.have - 1]; + copy = 3 + (hold & 0x03); //BITS(2); + //--- DROPBITS(2) ---// + hold >>>= 2; + bits -= 2; + //---// + } else if (here_val === 17) { + //=== NEEDBITS(here.bits + 3); + n = here_bits + 3; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 3 + (hold & 0x07); //BITS(3); + //--- DROPBITS(3) ---// + hold >>>= 3; + bits -= 3; + //---// + } else { + //=== NEEDBITS(here.bits + 7); + n = here_bits + 7; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + len = 0; + copy = 11 + (hold & 0x7f); //BITS(7); + //--- DROPBITS(7) ---// + hold >>>= 7; + bits -= 7; + //---// + } + if (state.have + copy > state.nlen + state.ndist) { + strm.msg = 'invalid bit length repeat'; + state.mode = BAD; + break; + } + while (copy--) { + state.lens[state.have++] = len; + } + } + } + + /* handle error breaks in while */ + if (state.mode === BAD) { + break; + } + + /* check for end-of-block code (better have one) */ + if (state.lens[256] === 0) { + strm.msg = 'invalid code -- missing end-of-block'; + state.mode = BAD; + break; + } + + /* build code tables -- note: do not change the lenbits or distbits + values here (9 and 6) without reading the comments in inftrees.h + concerning the ENOUGH constants, which depend on those values */ + state.lenbits = 9; + + opts = { + bits: state.lenbits + }; + ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.lenbits = opts.bits; + // state.lencode = state.next; + + if (ret) { + strm.msg = 'invalid literal/lengths set'; + state.mode = BAD; + break; + } + + state.distbits = 6; + //state.distcode.copy(state.codes); + // Switch to use dynamic table + state.distcode = state.distdyn; + opts = { + bits: state.distbits + }; + ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts); + // We have separate tables & no pointers. 2 commented lines below not needed. + // state.next_index = opts.table_index; + state.distbits = opts.bits; + // state.distcode = state.next; + + if (ret) { + strm.msg = 'invalid distances set'; + state.mode = BAD; + break; + } + //Tracev((stderr, 'inflate: codes ok\n')); + state.mode = LEN_; + if (flush === Z_TREES$1) { + break inf_leave; + } + /* falls through */ + case LEN_: + state.mode = LEN; + /* falls through */ + case LEN: + if (have >= 6 && left >= 258) { + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + inflate_fast(strm, _out); + //--- LOAD() --- + put = strm.next_out; + output = strm.output; + left = strm.avail_out; + next = strm.next_in; + input = strm.input; + have = strm.avail_in; + hold = state.hold; + bits = state.bits; + //--- + + if (state.mode === TYPE) { + state.back = -1; + } + break; + } + state.back = 0; + for (;;) { + here = state.lencode[hold & ((1 << state.lenbits) - 1)]; /*BITS(state.lenbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if (here_bits <= bits) { + break; + } + //--- PULLBYTE() ---// + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if (here_op && (here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.lencode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1)) /*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { + break; + } + //--- PULLBYTE() ---// + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + state.length = here_val; + if (here_op === 0) { + //Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ? + // "inflate: literal '%c'\n" : + // "inflate: literal 0x%02x\n", here.val)); + state.mode = LIT; + break; + } + if (here_op & 32) { + //Tracevv((stderr, "inflate: end of block\n")); + state.back = -1; + state.mode = TYPE; + break; + } + if (here_op & 64) { + strm.msg = 'invalid literal/length code'; + state.mode = BAD; + break; + } + state.extra = here_op & 15; + state.mode = LENEXT; + /* falls through */ + case LENEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.length += hold & ((1 << state.extra) - 1) /*BITS(state.extra)*/ ; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //Tracevv((stderr, "inflate: length %u\n", state.length)); + state.was = state.length; + state.mode = DIST; + /* falls through */ + case DIST: + for (;;) { + here = state.distcode[hold & ((1 << state.distbits) - 1)]; /*BITS(state.distbits)*/ + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((here_bits) <= bits) { + break; + } + //--- PULLBYTE() ---// + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + if ((here_op & 0xf0) === 0) { + last_bits = here_bits; + last_op = here_op; + last_val = here_val; + for (;;) { + here = state.distcode[last_val + + ((hold & ((1 << (last_bits + last_op)) - 1)) /*BITS(last.bits + last.op)*/ >> last_bits)]; + here_bits = here >>> 24; + here_op = (here >>> 16) & 0xff; + here_val = here & 0xffff; + + if ((last_bits + here_bits) <= bits) { + break; + } + //--- PULLBYTE() ---// + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + //---// + } + //--- DROPBITS(last.bits) ---// + hold >>>= last_bits; + bits -= last_bits; + //---// + state.back += last_bits; + } + //--- DROPBITS(here.bits) ---// + hold >>>= here_bits; + bits -= here_bits; + //---// + state.back += here_bits; + if (here_op & 64) { + strm.msg = 'invalid distance code'; + state.mode = BAD; + break; + } + state.offset = here_val; + state.extra = (here_op) & 15; + state.mode = DISTEXT; + /* falls through */ + case DISTEXT: + if (state.extra) { + //=== NEEDBITS(state.extra); + n = state.extra; + while (bits < n) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + state.offset += hold & ((1 << state.extra) - 1) /*BITS(state.extra)*/ ; + //--- DROPBITS(state.extra) ---// + hold >>>= state.extra; + bits -= state.extra; + //---// + state.back += state.extra; + } + //#ifdef INFLATE_STRICT + if (state.offset > state.dmax) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } + //#endif + //Tracevv((stderr, "inflate: distance %u\n", state.offset)); + state.mode = MATCH; + /* falls through */ + case MATCH: + if (left === 0) { + break inf_leave; + } + copy = _out - left; + if (state.offset > copy) { /* copy from window */ + copy = state.offset - copy; + if (copy > state.whave) { + if (state.sane) { + strm.msg = 'invalid distance too far back'; + state.mode = BAD; + break; + } + // (!) This block is disabled in zlib defailts, + // don't enable it for binary compatibility + //#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR + // Trace((stderr, "inflate.c too far\n")); + // copy -= state.whave; + // if (copy > state.length) { copy = state.length; } + // if (copy > left) { copy = left; } + // left -= copy; + // state.length -= copy; + // do { + // output[put++] = 0; + // } while (--copy); + // if (state.length === 0) { state.mode = LEN; } + // break; + //#endif + } + if (copy > state.wnext) { + copy -= state.wnext; + from = state.wsize - copy; + } else { + from = state.wnext - copy; + } + if (copy > state.length) { + copy = state.length; + } + from_source = state.window; + } else { /* copy from output */ + from_source = output; + from = put - state.offset; + copy = state.length; + } + if (copy > left) { + copy = left; + } + left -= copy; + state.length -= copy; + do { + output[put++] = from_source[from++]; + } while (--copy); + if (state.length === 0) { + state.mode = LEN; + } + break; + case LIT: + if (left === 0) { + break inf_leave; + } + output[put++] = state.length; + left--; + state.mode = LEN; + break; + case CHECK: + if (state.wrap) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + // Use '|' insdead of '+' to make sure that result is signed + hold |= input[next++] << bits; + bits += 8; + } + //===// + _out -= left; + strm.total_out += _out; + state.total += _out; + if (_out) { + strm.adler = state.check = + /*UPDATE(state.check, put - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out)); + + } + _out = left; + // NB: crc32 stored as signed 32-bit int, zswap32 returns signed too + if ((state.flags ? hold : zswap32(hold)) !== state.check) { + strm.msg = 'incorrect data check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: check matches trailer\n")); + } + state.mode = LENGTH; + /* falls through */ + case LENGTH: + if (state.wrap && state.flags) { + //=== NEEDBITS(32); + while (bits < 32) { + if (have === 0) { + break inf_leave; + } + have--; + hold += input[next++] << bits; + bits += 8; + } + //===// + if (hold !== (state.total & 0xffffffff)) { + strm.msg = 'incorrect length check'; + state.mode = BAD; + break; + } + //=== INITBITS(); + hold = 0; + bits = 0; + //===// + //Tracev((stderr, "inflate: length matches trailer\n")); + } + state.mode = DONE; + /* falls through */ + case DONE: + ret = Z_STREAM_END$1; + break inf_leave; + case BAD: + ret = Z_DATA_ERROR$1; + break inf_leave; + case MEM: + return Z_MEM_ERROR; + case SYNC: + /* falls through */ + default: + return Z_STREAM_ERROR$1; + } + } + + // inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave" + + /* + Return from inflate(), updating the total counts and the check value. + If there was no progress during the inflate() call, return a buffer + error. Call updatewindow() to create and/or update the window state. + Note: a memory error from inflate() is non-recoverable. + */ + + //--- RESTORE() --- + strm.next_out = put; + strm.avail_out = left; + strm.next_in = next; + strm.avail_in = have; + state.hold = hold; + state.bits = bits; + //--- + + if (state.wsize || (_out !== strm.avail_out && state.mode < BAD && + (state.mode < CHECK || flush !== Z_FINISH$1))) { + if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) ; + } + _in -= strm.avail_in; + _out -= strm.avail_out; + strm.total_in += _in; + strm.total_out += _out; + state.total += _out; + if (state.wrap && _out) { + strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/ + (state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out)); + } + strm.data_type = state.bits + (state.last ? 64 : 0) + + (state.mode === TYPE ? 128 : 0) + + (state.mode === LEN_ || state.mode === COPY_ ? 256 : 0); + if (((_in === 0 && _out === 0) || flush === Z_FINISH$1) && ret === Z_OK$1) { + ret = Z_BUF_ERROR$1; + } + return ret; + } + + function inflateEnd(strm) { + + if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/ ) { + return Z_STREAM_ERROR$1; + } + + var state = strm.state; + if (state.window) { + state.window = null; + } + strm.state = null; + return Z_OK$1; + } + + /* Not implemented + exports.inflateCopy = inflateCopy; + exports.inflateGetDictionary = inflateGetDictionary; + exports.inflateMark = inflateMark; + exports.inflatePrime = inflatePrime; + exports.inflateSync = inflateSync; + exports.inflateSyncPoint = inflateSyncPoint; + exports.inflateUndermine = inflateUndermine; + */ + + // import constants from './constants'; + + + // zlib modes + var NONE = 0; + var DEFLATE = 1; + var INFLATE = 2; + var GZIP = 3; + var GUNZIP = 4; + var DEFLATERAW = 5; + var INFLATERAW = 6; + var UNZIP = 7; + var Z_NO_FLUSH= 0, + Z_PARTIAL_FLUSH= 1, + Z_SYNC_FLUSH= 2, + Z_FULL_FLUSH= 3, + Z_FINISH= 4, + Z_BLOCK= 5, + Z_TREES= 6, + + /* Return codes for the compression/decompression functions. Negative values + * are errors, positive values are used for special but normal events. + */ + Z_OK= 0, + Z_STREAM_END= 1, + Z_NEED_DICT= 2, + Z_ERRNO= -1, + Z_STREAM_ERROR= -2, + Z_DATA_ERROR= -3, + //Z_MEM_ERROR: -4, + Z_BUF_ERROR= -5, + //Z_VERSION_ERROR: -6, + + /* compression levels */ + Z_NO_COMPRESSION= 0, + Z_BEST_SPEED= 1, + Z_BEST_COMPRESSION= 9, + Z_DEFAULT_COMPRESSION= -1, + + + Z_FILTERED= 1, + Z_HUFFMAN_ONLY= 2, + Z_RLE= 3, + Z_FIXED= 4, + Z_DEFAULT_STRATEGY= 0, + + /* Possible values of the data_type field (though see inflate()) */ + Z_BINARY= 0, + Z_TEXT= 1, + //Z_ASCII: 1, // = Z_TEXT (deprecated) + Z_UNKNOWN= 2, + + /* The deflate compression method */ + Z_DEFLATED= 8; + function Zlib$1(mode) { + if (mode < DEFLATE || mode > UNZIP) + throw new TypeError('Bad argument'); + + this.mode = mode; + this.init_done = false; + this.write_in_progress = false; + this.pending_close = false; + this.windowBits = 0; + this.level = 0; + this.memLevel = 0; + this.strategy = 0; + this.dictionary = null; + } + + Zlib$1.prototype.init = function(windowBits, level, memLevel, strategy, dictionary) { + this.windowBits = windowBits; + this.level = level; + this.memLevel = memLevel; + this.strategy = strategy; + // dictionary not supported. + + if (this.mode === GZIP || this.mode === GUNZIP) + this.windowBits += 16; + + if (this.mode === UNZIP) + this.windowBits += 32; + + if (this.mode === DEFLATERAW || this.mode === INFLATERAW) + this.windowBits = -this.windowBits; + + this.strm = new ZStream(); + var status; + switch (this.mode) { + case DEFLATE: + case GZIP: + case DEFLATERAW: + status = deflateInit2( + this.strm, + this.level, + Z_DEFLATED, + this.windowBits, + this.memLevel, + this.strategy + ); + break; + case INFLATE: + case GUNZIP: + case INFLATERAW: + case UNZIP: + status = inflateInit2( + this.strm, + this.windowBits + ); + break; + default: + throw new Error('Unknown mode ' + this.mode); + } + + if (status !== Z_OK) { + this._error(status); + return; + } + + this.write_in_progress = false; + this.init_done = true; + }; + + Zlib$1.prototype.params = function() { + throw new Error('deflateParams Not supported'); + }; + + Zlib$1.prototype._writeCheck = function() { + if (!this.init_done) + throw new Error('write before init'); + + if (this.mode === NONE) + throw new Error('already finalized'); + + if (this.write_in_progress) + throw new Error('write already in progress'); + + if (this.pending_close) + throw new Error('close is pending'); + }; + + Zlib$1.prototype.write = function(flush, input, in_off, in_len, out, out_off, out_len) { + this._writeCheck(); + this.write_in_progress = true; + + var self = this; + browser$1$1.nextTick(function() { + self.write_in_progress = false; + var res = self._write(flush, input, in_off, in_len, out, out_off, out_len); + self.callback(res[0], res[1]); + + if (self.pending_close) + self.close(); + }); + + return this; + }; + + // set method for Node buffers, used by pako + function bufferSet(data, offset) { + for (var i = 0; i < data.length; i++) { + this[offset + i] = data[i]; + } + } + + Zlib$1.prototype.writeSync = function(flush, input, in_off, in_len, out, out_off, out_len) { + this._writeCheck(); + return this._write(flush, input, in_off, in_len, out, out_off, out_len); + }; + + Zlib$1.prototype._write = function(flush, input, in_off, in_len, out, out_off, out_len) { + this.write_in_progress = true; + + if (flush !== Z_NO_FLUSH && + flush !== Z_PARTIAL_FLUSH && + flush !== Z_SYNC_FLUSH && + flush !== Z_FULL_FLUSH && + flush !== Z_FINISH && + flush !== Z_BLOCK) { + throw new Error('Invalid flush value'); + } + + if (input == null) { + input = new Buffer(0); + in_len = 0; + in_off = 0; + } + + if (out._set) + out.set = out._set; + else + out.set = bufferSet; + + var strm = this.strm; + strm.avail_in = in_len; + strm.input = input; + strm.next_in = in_off; + strm.avail_out = out_len; + strm.output = out; + strm.next_out = out_off; + var status; + switch (this.mode) { + case DEFLATE: + case GZIP: + case DEFLATERAW: + status = deflate$1(strm, flush); + break; + case UNZIP: + case INFLATE: + case GUNZIP: + case INFLATERAW: + status = inflate$1(strm, flush); + break; + default: + throw new Error('Unknown mode ' + this.mode); + } + + if (!this._checkError(status, strm, flush)) { + this._error(status); + } + + this.write_in_progress = false; + return [strm.avail_in, strm.avail_out]; + }; + + Zlib$1.prototype._checkError = function (status, strm, flush) { + // Acceptable error states depend on the type of zlib stream. + switch (status) { + case Z_OK: + case Z_BUF_ERROR: + if (strm.avail_out !== 0 && flush === Z_FINISH) { + return false + } + break + case Z_STREAM_END: + // normal statuses, not fatal + break + case Z_NEED_DICT: + return false + default: + return false + } + + return true + }; + + Zlib$1.prototype.close = function() { + if (this.write_in_progress) { + this.pending_close = true; + return; + } + + this.pending_close = false; + + if (this.mode === DEFLATE || this.mode === GZIP || this.mode === DEFLATERAW) { + deflateEnd(this.strm); + } else { + inflateEnd(this.strm); + } + + this.mode = NONE; + }; + var status; + Zlib$1.prototype.reset = function() { + switch (this.mode) { + case DEFLATE: + case DEFLATERAW: + status = deflateReset(this.strm); + break; + case INFLATE: + case INFLATERAW: + status = inflateReset(this.strm); + break; + } + + if (status !== Z_OK) { + this._error(status); + } + }; + + Zlib$1.prototype._error = function(status) { + this.onerror(msg[status] + ': ' + this.strm.msg, status); + + this.write_in_progress = false; + if (this.pending_close) + this.close(); + }; + + var _binding = /*#__PURE__*/Object.freeze({ + __proto__: null, + DEFLATE: DEFLATE, + DEFLATERAW: DEFLATERAW, + GUNZIP: GUNZIP, + GZIP: GZIP, + INFLATE: INFLATE, + INFLATERAW: INFLATERAW, + NONE: NONE, + UNZIP: UNZIP, + Z_BEST_COMPRESSION: Z_BEST_COMPRESSION, + Z_BEST_SPEED: Z_BEST_SPEED, + Z_BINARY: Z_BINARY, + Z_BLOCK: Z_BLOCK, + Z_BUF_ERROR: Z_BUF_ERROR, + Z_DATA_ERROR: Z_DATA_ERROR, + Z_DEFAULT_COMPRESSION: Z_DEFAULT_COMPRESSION, + Z_DEFAULT_STRATEGY: Z_DEFAULT_STRATEGY, + Z_DEFLATED: Z_DEFLATED, + Z_ERRNO: Z_ERRNO, + Z_FILTERED: Z_FILTERED, + Z_FINISH: Z_FINISH, + Z_FIXED: Z_FIXED, + Z_FULL_FLUSH: Z_FULL_FLUSH, + Z_HUFFMAN_ONLY: Z_HUFFMAN_ONLY, + Z_NEED_DICT: Z_NEED_DICT, + Z_NO_COMPRESSION: Z_NO_COMPRESSION, + Z_NO_FLUSH: Z_NO_FLUSH, + Z_OK: Z_OK, + Z_PARTIAL_FLUSH: Z_PARTIAL_FLUSH, + Z_RLE: Z_RLE, + Z_STREAM_END: Z_STREAM_END, + Z_STREAM_ERROR: Z_STREAM_ERROR, + Z_SYNC_FLUSH: Z_SYNC_FLUSH, + Z_TEXT: Z_TEXT, + Z_TREES: Z_TREES, + Z_UNKNOWN: Z_UNKNOWN, + Zlib: Zlib$1 + }); + + function assert (a, msg) { + if (!a) { + throw new Error(msg); + } + } + var binding = {}; + Object.keys(_binding).forEach(function (key) { + binding[key] = _binding[key]; + }); + // zlib doesn't provide these, so kludge them in following the same + // const naming scheme zlib uses. + binding.Z_MIN_WINDOWBITS = 8; + binding.Z_MAX_WINDOWBITS = 15; + binding.Z_DEFAULT_WINDOWBITS = 15; + + // fewer than 64 bytes per chunk is stupid. + // technically it could work with as few as 8, but even 64 bytes + // is absurdly low. Usually a MB or more is best. + binding.Z_MIN_CHUNK = 64; + binding.Z_MAX_CHUNK = Infinity; + binding.Z_DEFAULT_CHUNK = (16 * 1024); + + binding.Z_MIN_MEMLEVEL = 1; + binding.Z_MAX_MEMLEVEL = 9; + binding.Z_DEFAULT_MEMLEVEL = 8; + + binding.Z_MIN_LEVEL = -1; + binding.Z_MAX_LEVEL = 9; + binding.Z_DEFAULT_LEVEL = binding.Z_DEFAULT_COMPRESSION; + + + // translation table for return codes. + var codes = { + Z_OK: binding.Z_OK, + Z_STREAM_END: binding.Z_STREAM_END, + Z_NEED_DICT: binding.Z_NEED_DICT, + Z_ERRNO: binding.Z_ERRNO, + Z_STREAM_ERROR: binding.Z_STREAM_ERROR, + Z_DATA_ERROR: binding.Z_DATA_ERROR, + Z_MEM_ERROR: binding.Z_MEM_ERROR, + Z_BUF_ERROR: binding.Z_BUF_ERROR, + Z_VERSION_ERROR: binding.Z_VERSION_ERROR + }; + + Object.keys(codes).forEach(function(k) { + codes[codes[k]] = k; + }); + + function createDeflate(o) { + return new Deflate(o); + } + + function createInflate(o) { + return new Inflate(o); + } + + function createDeflateRaw(o) { + return new DeflateRaw(o); + } + + function createInflateRaw(o) { + return new InflateRaw(o); + } + + function createGzip(o) { + return new Gzip(o); + } + + function createGunzip(o) { + return new Gunzip(o); + } + + function createUnzip(o) { + return new Unzip(o); + } + + + // Convenience methods. + // compress/decompress a string or buffer in one step. + function deflate(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Deflate(opts), buffer, callback); + } + + function deflateSync(buffer, opts) { + return zlibBufferSync(new Deflate(opts), buffer); + } + + function gzip(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gzip(opts), buffer, callback); + } + + function gzipSync(buffer, opts) { + return zlibBufferSync(new Gzip(opts), buffer); + } + + function deflateRaw(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new DeflateRaw(opts), buffer, callback); + } + + function deflateRawSync(buffer, opts) { + return zlibBufferSync(new DeflateRaw(opts), buffer); + } + + function unzip(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Unzip(opts), buffer, callback); + } + + function unzipSync(buffer, opts) { + return zlibBufferSync(new Unzip(opts), buffer); + } + + function inflate(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Inflate(opts), buffer, callback); + } + + function inflateSync(buffer, opts) { + return zlibBufferSync(new Inflate(opts), buffer); + } + + function gunzip(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new Gunzip(opts), buffer, callback); + } + + function gunzipSync(buffer, opts) { + return zlibBufferSync(new Gunzip(opts), buffer); + } + + function inflateRaw(buffer, opts, callback) { + if (typeof opts === 'function') { + callback = opts; + opts = {}; + } + return zlibBuffer(new InflateRaw(opts), buffer, callback); + } + + function inflateRawSync(buffer, opts) { + return zlibBufferSync(new InflateRaw(opts), buffer); + } + + function zlibBuffer(engine, buffer, callback) { + var buffers = []; + var nread = 0; + + engine.on('error', onError); + engine.on('end', onEnd); + + engine.end(buffer); + flow(); + + function flow() { + var chunk; + while (null !== (chunk = engine.read())) { + buffers.push(chunk); + nread += chunk.length; + } + engine.once('readable', flow); + } + + function onError(err) { + engine.removeListener('end', onEnd); + engine.removeListener('readable', flow); + callback(err); + } + + function onEnd() { + var buf = Buffer.concat(buffers, nread); + buffers = []; + callback(null, buf); + engine.close(); + } + } + + function zlibBufferSync(engine, buffer) { + if (typeof buffer === 'string') + buffer = new Buffer(buffer); + if (!Buffer.isBuffer(buffer)) + throw new TypeError('Not a string or buffer'); + + var flushFlag = binding.Z_FINISH; + + return engine._processChunk(buffer, flushFlag); + } + + // generic zlib + // minimal 2-byte header + function Deflate(opts) { + if (!(this instanceof Deflate)) return new Deflate(opts); + Zlib.call(this, opts, binding.DEFLATE); + } + + function Inflate(opts) { + if (!(this instanceof Inflate)) return new Inflate(opts); + Zlib.call(this, opts, binding.INFLATE); + } + + + + // gzip - bigger header, same deflate compression + function Gzip(opts) { + if (!(this instanceof Gzip)) return new Gzip(opts); + Zlib.call(this, opts, binding.GZIP); + } + + function Gunzip(opts) { + if (!(this instanceof Gunzip)) return new Gunzip(opts); + Zlib.call(this, opts, binding.GUNZIP); + } + + + + // raw - no header + function DeflateRaw(opts) { + if (!(this instanceof DeflateRaw)) return new DeflateRaw(opts); + Zlib.call(this, opts, binding.DEFLATERAW); + } + + function InflateRaw(opts) { + if (!(this instanceof InflateRaw)) return new InflateRaw(opts); + Zlib.call(this, opts, binding.INFLATERAW); + } + + + // auto-detect header. + function Unzip(opts) { + if (!(this instanceof Unzip)) return new Unzip(opts); + Zlib.call(this, opts, binding.UNZIP); + } + + + // the Zlib class they all inherit from + // This thing manages the queue of requests, and returns + // true or false if there is anything in the queue when + // you call the .write() method. + + function Zlib(opts, mode) { + this._opts = opts = opts || {}; + this._chunkSize = opts.chunkSize || binding.Z_DEFAULT_CHUNK; + + Transform$1.call(this, opts); + + if (opts.flush) { + if (opts.flush !== binding.Z_NO_FLUSH && + opts.flush !== binding.Z_PARTIAL_FLUSH && + opts.flush !== binding.Z_SYNC_FLUSH && + opts.flush !== binding.Z_FULL_FLUSH && + opts.flush !== binding.Z_FINISH && + opts.flush !== binding.Z_BLOCK) { + throw new Error('Invalid flush flag: ' + opts.flush); + } + } + this._flushFlag = opts.flush || binding.Z_NO_FLUSH; + + if (opts.chunkSize) { + if (opts.chunkSize < binding.Z_MIN_CHUNK || + opts.chunkSize > binding.Z_MAX_CHUNK) { + throw new Error('Invalid chunk size: ' + opts.chunkSize); + } + } + + if (opts.windowBits) { + if (opts.windowBits < binding.Z_MIN_WINDOWBITS || + opts.windowBits > binding.Z_MAX_WINDOWBITS) { + throw new Error('Invalid windowBits: ' + opts.windowBits); + } + } + + if (opts.level) { + if (opts.level < binding.Z_MIN_LEVEL || + opts.level > binding.Z_MAX_LEVEL) { + throw new Error('Invalid compression level: ' + opts.level); + } + } + + if (opts.memLevel) { + if (opts.memLevel < binding.Z_MIN_MEMLEVEL || + opts.memLevel > binding.Z_MAX_MEMLEVEL) { + throw new Error('Invalid memLevel: ' + opts.memLevel); + } + } + + if (opts.strategy) { + if (opts.strategy != binding.Z_FILTERED && + opts.strategy != binding.Z_HUFFMAN_ONLY && + opts.strategy != binding.Z_RLE && + opts.strategy != binding.Z_FIXED && + opts.strategy != binding.Z_DEFAULT_STRATEGY) { + throw new Error('Invalid strategy: ' + opts.strategy); + } + } + + if (opts.dictionary) { + if (!Buffer.isBuffer(opts.dictionary)) { + throw new Error('Invalid dictionary: it should be a Buffer instance'); + } + } + + this._binding = new binding.Zlib(mode); + + var self = this; + this._hadError = false; + this._binding.onerror = function(message, errno) { + // there is no way to cleanly recover. + // continuing only obscures problems. + self._binding = null; + self._hadError = true; + + var error = new Error(message); + error.errno = errno; + error.code = codes[errno]; + self.emit('error', error); + }; + + var level = binding.Z_DEFAULT_COMPRESSION; + if (typeof opts.level === 'number') level = opts.level; + + var strategy = binding.Z_DEFAULT_STRATEGY; + if (typeof opts.strategy === 'number') strategy = opts.strategy; + + this._binding.init(opts.windowBits || binding.Z_DEFAULT_WINDOWBITS, + level, + opts.memLevel || binding.Z_DEFAULT_MEMLEVEL, + strategy, + opts.dictionary); + + this._buffer = new Buffer(this._chunkSize); + this._offset = 0; + this._closed = false; + this._level = level; + this._strategy = strategy; + + this.once('end', this.close); + } + + inherits$1(Zlib, Transform$1); + + Zlib.prototype.params = function(level, strategy, callback) { + if (level < binding.Z_MIN_LEVEL || + level > binding.Z_MAX_LEVEL) { + throw new RangeError('Invalid compression level: ' + level); + } + if (strategy != binding.Z_FILTERED && + strategy != binding.Z_HUFFMAN_ONLY && + strategy != binding.Z_RLE && + strategy != binding.Z_FIXED && + strategy != binding.Z_DEFAULT_STRATEGY) { + throw new TypeError('Invalid strategy: ' + strategy); + } + + if (this._level !== level || this._strategy !== strategy) { + var self = this; + this.flush(binding.Z_SYNC_FLUSH, function() { + self._binding.params(level, strategy); + if (!self._hadError) { + self._level = level; + self._strategy = strategy; + if (callback) callback(); + } + }); + } else { + browser$1$1.nextTick(callback); + } + }; + + Zlib.prototype.reset = function() { + return this._binding.reset(); + }; + + // This is the _flush function called by the transform class, + // internally, when the last chunk has been written. + Zlib.prototype._flush = function(callback) { + this._transform(new Buffer(0), '', callback); + }; + + Zlib.prototype.flush = function(kind, callback) { + var ws = this._writableState; + + if (typeof kind === 'function' || (kind === void 0 && !callback)) { + callback = kind; + kind = binding.Z_FULL_FLUSH; + } + + if (ws.ended) { + if (callback) + browser$1$1.nextTick(callback); + } else if (ws.ending) { + if (callback) + this.once('end', callback); + } else if (ws.needDrain) { + var self = this; + this.once('drain', function() { + self.flush(callback); + }); + } else { + this._flushFlag = kind; + this.write(new Buffer(0), '', callback); + } + }; + + Zlib.prototype.close = function(callback) { + if (callback) + browser$1$1.nextTick(callback); + + if (this._closed) + return; + + this._closed = true; + + this._binding.close(); + + var self = this; + browser$1$1.nextTick(function() { + self.emit('close'); + }); + }; + + Zlib.prototype._transform = function(chunk, encoding, cb) { + var flushFlag; + var ws = this._writableState; + var ending = ws.ending || ws.ended; + var last = ending && (!chunk || ws.length === chunk.length); + + if (!chunk === null && !Buffer.isBuffer(chunk)) + return cb(new Error('invalid input')); + + // If it's the last chunk, or a final flush, we use the Z_FINISH flush flag. + // If it's explicitly flushing at some other time, then we use + // Z_FULL_FLUSH. Otherwise, use Z_NO_FLUSH for maximum compression + // goodness. + if (last) + flushFlag = binding.Z_FINISH; + else { + flushFlag = this._flushFlag; + // once we've flushed the last of the queue, stop flushing and + // go back to the normal behavior. + if (chunk.length >= ws.length) { + this._flushFlag = this._opts.flush || binding.Z_NO_FLUSH; + } + } + + this._processChunk(chunk, flushFlag, cb); + }; + + Zlib.prototype._processChunk = function(chunk, flushFlag, cb) { + var availInBefore = chunk && chunk.length; + var availOutBefore = this._chunkSize - this._offset; + var inOff = 0; + + var self = this; + + var async = typeof cb === 'function'; + + if (!async) { + var buffers = []; + var nread = 0; + + var error; + this.on('error', function(er) { + error = er; + }); + + do { + var res = this._binding.writeSync(flushFlag, + chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + } while (!this._hadError && callback(res[0], res[1])); + + if (this._hadError) { + throw error; + } + + var buf = Buffer.concat(buffers, nread); + this.close(); + + return buf; + } + + var req = this._binding.write(flushFlag, + chunk, // in + inOff, // in_off + availInBefore, // in_len + this._buffer, // out + this._offset, //out_off + availOutBefore); // out_len + + req.buffer = chunk; + req.callback = callback; + + function callback(availInAfter, availOutAfter) { + if (self._hadError) + return; + + var have = availOutBefore - availOutAfter; + assert(have >= 0, 'have should not go down'); + + if (have > 0) { + var out = self._buffer.slice(self._offset, self._offset + have); + self._offset += have; + // serve some output to the consumer. + if (async) { + self.push(out); + } else { + buffers.push(out); + nread += out.length; + } + } + + // exhausted the output buffer, or used all the input create a new one. + if (availOutAfter === 0 || self._offset >= self._chunkSize) { + availOutBefore = self._chunkSize; + self._offset = 0; + self._buffer = new Buffer(self._chunkSize); + } + + if (availOutAfter === 0) { + // Not actually done. Need to reprocess. + // Also, update the availInBefore to the availInAfter value, + // so that if we have to hit it a third (fourth, etc.) time, + // it'll have the correct byte counts. + inOff += (availInBefore - availInAfter); + availInBefore = availInAfter; + + if (!async) + return true; + + var newReq = self._binding.write(flushFlag, + chunk, + inOff, + availInBefore, + self._buffer, + self._offset, + self._chunkSize); + newReq.callback = callback; // this same function + newReq.buffer = chunk; + return; + } + + if (!async) + return false; + + // finished with the chunk. + cb(); + } + }; + + inherits$1(Deflate, Zlib); + inherits$1(Inflate, Zlib); + inherits$1(Gzip, Zlib); + inherits$1(Gunzip, Zlib); + inherits$1(DeflateRaw, Zlib); + inherits$1(InflateRaw, Zlib); + inherits$1(Unzip, Zlib); + var _polyfillNode_zlib = { + codes: codes, + createDeflate: createDeflate, + createInflate: createInflate, + createDeflateRaw: createDeflateRaw, + createInflateRaw: createInflateRaw, + createGzip: createGzip, + createGunzip: createGunzip, + createUnzip: createUnzip, + deflate: deflate, + deflateSync: deflateSync, + gzip: gzip, + gzipSync: gzipSync, + deflateRaw: deflateRaw, + deflateRawSync: deflateRawSync, + unzip: unzip, + unzipSync: unzipSync, + inflate: inflate, + inflateSync: inflateSync, + gunzip: gunzip, + gunzipSync: gunzipSync, + inflateRaw: inflateRaw, + inflateRawSync: inflateRawSync, + Deflate: Deflate, + Inflate: Inflate, + Gzip: Gzip, + Gunzip: Gunzip, + DeflateRaw: DeflateRaw, + InflateRaw: InflateRaw, + Unzip: Unzip, + Zlib: Zlib + }; + + var _polyfillNode_zlib$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + Deflate: Deflate, + DeflateRaw: DeflateRaw, + Gunzip: Gunzip, + Gzip: Gzip, + Inflate: Inflate, + InflateRaw: InflateRaw, + Unzip: Unzip, + Zlib: Zlib, + codes: codes, + createDeflate: createDeflate, + createDeflateRaw: createDeflateRaw, + createGunzip: createGunzip, + createGzip: createGzip, + createInflate: createInflate, + createInflateRaw: createInflateRaw, + createUnzip: createUnzip, + default: _polyfillNode_zlib, + deflate: deflate, + deflateRaw: deflateRaw, + deflateRawSync: deflateRawSync, + deflateSync: deflateSync, + gunzip: gunzip, + gunzipSync: gunzipSync, + gzip: gzip, + gzipSync: gzipSync, + inflate: inflate, + inflateRaw: inflateRaw, + inflateRawSync: inflateRawSync, + inflateSync: inflateSync, + unzip: unzip, + unzipSync: unzipSync + }); + + var require$$3 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_zlib$1); + + var fetch_1; + var hasRequiredFetch; + + function requireFetch () { + if (hasRequiredFetch) return fetch_1; + hasRequiredFetch = 1; + + const { + Response, + makeNetworkError, + makeAppropriateNetworkError, + filterResponse, + makeResponse + } = requireResponse(); + const { Headers } = requireHeaders(); + const { Request, makeRequest } = requireRequest(); + const zlib = require$$3; + const { + bytesMatch, + makePolicyContainer, + clonePolicyContainer, + requestBadPort, + TAOCheck, + appendRequestOriginHeader, + responseLocationURL, + requestCurrentURL, + setRequestReferrerPolicyOnRedirect, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + createOpaqueTimingInfo, + appendFetchMetadata, + corsCheck, + crossOriginResourcePolicyCheck, + determineRequestsReferrer, + coarsenedSharedCurrentTime, + createDeferredPromise, + isBlobLike, + sameOrigin, + isCancelled, + isAborted, + isErrorLike, + fullyReadBody, + readableStreamClose, + isomorphicEncode, + urlIsLocal, + urlIsHttpHttpsScheme, + urlHasHttpsScheme + } = requireUtil$4(); + const { kState, kHeaders, kGuard, kRealm } = requireSymbols$3(); + const assert = require$$3$1; + const { safelyExtractBody } = requireBody(); + const { + redirectStatus, + nullBodyStatus, + safeMethods, + requestBodyHeader, + subresource, + DOMException + } = requireConstants$3(); + const { kHeadersList } = symbols$4; + const EE = require$$10$1; + const { Readable, pipeline } = require$$0$1; + const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = util$l; + const { dataURLProcessor, serializeAMimeType } = requireDataURL(); + const { TransformStream } = require$$14; + const { getGlobalDispatcher } = global$1; + const { webidl } = requireWebidl(); + const { STATUS_CODES } = require$$17; + + /** @type {import('buffer').resolveObjectURL} */ + let resolveObjectURL; + let ReadableStream = globalThis.ReadableStream; + + class Fetch extends EE { + constructor (dispatcher) { + super(); + + this.dispatcher = dispatcher; + this.connection = null; + this.dump = false; + this.state = 'ongoing'; + // 2 terminated listeners get added per request, + // but only 1 gets removed. If there are 20 redirects, + // 21 listeners will be added. + // See https://github.com/nodejs/undici/issues/1711 + // TODO (fix): Find and fix root cause for leaked listener. + this.setMaxListeners(21); + } + + terminate (reason) { + if (this.state !== 'ongoing') { + return + } + + this.state = 'terminated'; + this.connection?.destroy(reason); + this.emit('terminated', reason); + } + + // https://fetch.spec.whatwg.org/#fetch-controller-abort + abort (error) { + if (this.state !== 'ongoing') { + return + } + + // 1. Set controller’s state to "aborted". + this.state = 'aborted'; + + // 2. Let fallbackError be an "AbortError" DOMException. + // 3. Set error to fallbackError if it is not given. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError'); + } + + // 4. Let serializedError be StructuredSerialize(error). + // If that threw an exception, catch it, and let + // serializedError be StructuredSerialize(fallbackError). + + // 5. Set controller’s serialized abort reason to serializedError. + this.serializedAbortReason = error; + + this.connection?.destroy(error); + this.emit('terminated', error); + } + } + + // https://fetch.spec.whatwg.org/#fetch-method + function fetch (input, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }); + + // 1. Let p be a new promise. + const p = createDeferredPromise(); + + // 2. Let requestObject be the result of invoking the initial value of + // Request as constructor with input and init as arguments. If this throws + // an exception, reject p with it and return p. + let requestObject; + + try { + requestObject = new Request(input, init); + } catch (e) { + p.reject(e); + return p.promise + } + + // 3. Let request be requestObject’s request. + const request = requestObject[kState]; + + // 4. If requestObject’s signal’s aborted flag is set, then: + if (requestObject.signal.aborted) { + // 1. Abort the fetch() call with p, request, null, and + // requestObject’s signal’s abort reason. + abortFetch(p, request, null, requestObject.signal.reason); + + // 2. Return p. + return p.promise + } + + // 5. Let globalObject be request’s client’s global object. + const globalObject = request.client.globalObject; + + // 6. If globalObject is a ServiceWorkerGlobalScope object, then set + // request’s service-workers mode to "none". + if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { + request.serviceWorkers = 'none'; + } + + // 7. Let responseObject be null. + let responseObject = null; + + // 8. Let relevantRealm be this’s relevant Realm. + const relevantRealm = null; + + // 9. Let locallyAborted be false. + let locallyAborted = false; + + // 10. Let controller be null. + let controller = null; + + // 11. Add the following abort steps to requestObject’s signal: + addAbortListener( + requestObject.signal, + () => { + // 1. Set locallyAborted to true. + locallyAborted = true; + + // 2. Assert: controller is non-null. + assert(controller != null); + + // 3. Abort controller with requestObject’s signal’s abort reason. + controller.abort(requestObject.signal.reason); + + // 4. Abort the fetch() call with p, request, responseObject, + // and requestObject’s signal’s abort reason. + abortFetch(p, request, responseObject, requestObject.signal.reason); + } + ); + + // 12. Let handleFetchDone given response response be to finalize and + // report timing with response, globalObject, and "fetch". + const handleFetchDone = (response) => + finalizeAndReportTiming(response, 'fetch'); + + // 13. Set controller to the result of calling fetch given request, + // with processResponseEndOfBody set to handleFetchDone, and processResponse + // given response being these substeps: + + const processResponse = (response) => { + // 1. If locallyAborted is true, terminate these substeps. + if (locallyAborted) { + return Promise.resolve() + } + + // 2. If response’s aborted flag is set, then: + if (response.aborted) { + // 1. Let deserializedError be the result of deserialize a serialized + // abort reason given controller’s serialized abort reason and + // relevantRealm. + + // 2. Abort the fetch() call with p, request, responseObject, and + // deserializedError. + + abortFetch(p, request, responseObject, controller.serializedAbortReason); + return Promise.resolve() + } + + // 3. If response is a network error, then reject p with a TypeError + // and terminate these substeps. + if (response.type === 'error') { + p.reject( + Object.assign(new TypeError('fetch failed'), { cause: response.error }) + ); + return Promise.resolve() + } + + // 4. Set responseObject to the result of creating a Response object, + // given response, "immutable", and relevantRealm. + responseObject = new Response(); + responseObject[kState] = response; + responseObject[kRealm] = relevantRealm; + responseObject[kHeaders][kHeadersList] = response.headersList; + responseObject[kHeaders][kGuard] = 'immutable'; + responseObject[kHeaders][kRealm] = relevantRealm; + + // 5. Resolve p with responseObject. + p.resolve(responseObject); + }; + + controller = fetching({ + request, + processResponseEndOfBody: handleFetchDone, + processResponse, + dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici + }); + + // 14. Return p. + return p.promise + } + + // https://fetch.spec.whatwg.org/#finalize-and-report-timing + function finalizeAndReportTiming (response, initiatorType = 'other') { + // 1. If response is an aborted network error, then return. + if (response.type === 'error' && response.aborted) { + return + } + + // 2. If response’s URL list is null or empty, then return. + if (!response.urlList?.length) { + return + } + + // 3. Let originalURL be response’s URL list[0]. + const originalURL = response.urlList[0]; + + // 4. Let timingInfo be response’s timing info. + let timingInfo = response.timingInfo; + + // 5. Let cacheState be response’s cache state. + let cacheState = response.cacheState; + + // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. + if (!urlIsHttpHttpsScheme(originalURL)) { + return + } + + // 7. If timingInfo is null, then return. + if (timingInfo === null) { + return + } + + // 8. If response’s timing allow passed flag is not set, then: + if (!timingInfo.timingAllowPassed) { + // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. + timingInfo = createOpaqueTimingInfo({ + startTime: timingInfo.startTime + }); + + // 2. Set cacheState to the empty string. + cacheState = ''; + } + + // 9. Set timingInfo’s end time to the coarsened shared current time + // given global’s relevant settings object’s cross-origin isolated + // capability. + // TODO: given global’s relevant settings object’s cross-origin isolated + // capability? + timingInfo.endTime = coarsenedSharedCurrentTime(); + + // 10. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo; + + // 11. Mark resource timing for timingInfo, originalURL, initiatorType, + // global, and cacheState. + markResourceTiming( + timingInfo, + originalURL, + initiatorType, + globalThis, + cacheState + ); + } + + // https://w3c.github.io/resource-timing/#dfn-mark-resource-timing + function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) { + if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) { + performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState); + } + } + + // https://fetch.spec.whatwg.org/#abort-fetch + function abortFetch (p, request, responseObject, error) { + // Note: AbortSignal.reason was added in node v17.2.0 + // which would give us an undefined error to reject with. + // Remove this once node v16 is no longer supported. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError'); + } + + // 1. Reject promise with error. + p.reject(error); + + // 2. If request’s body is not null and is readable, then cancel request’s + // body with error. + if (request.body != null && isReadable(request.body?.stream)) { + request.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }); + } + + // 3. If responseObject is null, then return. + if (responseObject == null) { + return + } + + // 4. Let response be responseObject’s response. + const response = responseObject[kState]; + + // 5. If response’s body is not null and is readable, then error response’s + // body with error. + if (response.body != null && isReadable(response.body?.stream)) { + response.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }); + } + } + + // https://fetch.spec.whatwg.org/#fetching + function fetching ({ + request, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseEndOfBody, + processResponseConsumeBody, + useParallelQueue = false, + dispatcher // undici + }) { + // 1. Let taskDestination be null. + let taskDestination = null; + + // 2. Let crossOriginIsolatedCapability be false. + let crossOriginIsolatedCapability = false; + + // 3. If request’s client is non-null, then: + if (request.client != null) { + // 1. Set taskDestination to request’s client’s global object. + taskDestination = request.client.globalObject; + + // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin + // isolated capability. + crossOriginIsolatedCapability = + request.client.crossOriginIsolatedCapability; + } + + // 4. If useParallelQueue is true, then set taskDestination to the result of + // starting a new parallel queue. + // TODO + + // 5. Let timingInfo be a new fetch timing info whose start time and + // post-redirect start time are the coarsened shared current time given + // crossOriginIsolatedCapability. + const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability); + const timingInfo = createOpaqueTimingInfo({ + startTime: currenTime + }); + + // 6. Let fetchParams be a new fetch params whose + // request is request, + // timing info is timingInfo, + // process request body chunk length is processRequestBodyChunkLength, + // process request end-of-body is processRequestEndOfBody, + // process response is processResponse, + // process response consume body is processResponseConsumeBody, + // process response end-of-body is processResponseEndOfBody, + // task destination is taskDestination, + // and cross-origin isolated capability is crossOriginIsolatedCapability. + const fetchParams = { + controller: new Fetch(dispatcher), + request, + timingInfo, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseConsumeBody, + processResponseEndOfBody, + taskDestination, + crossOriginIsolatedCapability + }; + + // 7. If request’s body is a byte sequence, then set request’s body to + // request’s body as a body. + // NOTE: Since fetching is only called from fetch, body should already be + // extracted. + assert(!request.body || request.body.stream); + + // 8. If request’s window is "client", then set request’s window to request’s + // client, if request’s client’s global object is a Window object; otherwise + // "no-window". + if (request.window === 'client') { + // TODO: What if request.client is null? + request.window = + request.client?.globalObject?.constructor?.name === 'Window' + ? request.client + : 'no-window'; + } + + // 9. If request’s origin is "client", then set request’s origin to request’s + // client’s origin. + if (request.origin === 'client') { + // TODO: What if request.client is null? + request.origin = request.client?.origin; + } + + // 10. If all of the following conditions are true: + // TODO + + // 11. If request’s policy container is "client", then: + if (request.policyContainer === 'client') { + // 1. If request’s client is non-null, then set request’s policy + // container to a clone of request’s client’s policy container. [HTML] + if (request.client != null) { + request.policyContainer = clonePolicyContainer( + request.client.policyContainer + ); + } else { + // 2. Otherwise, set request’s policy container to a new policy + // container. + request.policyContainer = makePolicyContainer(); + } + } + + // 12. If request’s header list does not contain `Accept`, then: + if (!request.headersList.contains('accept')) { + // 1. Let value be `*/*`. + const value = '*/*'; + + // 2. A user agent should set value to the first matching statement, if + // any, switching on request’s destination: + // "document" + // "frame" + // "iframe" + // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` + // "image" + // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` + // "style" + // `text/css,*/*;q=0.1` + // TODO + + // 3. Append `Accept`/value to request’s header list. + request.headersList.append('accept', value); + } + + // 13. If request’s header list does not contain `Accept-Language`, then + // user agents should append `Accept-Language`/an appropriate value to + // request’s header list. + if (!request.headersList.contains('accept-language')) { + request.headersList.append('accept-language', '*'); + } + + // 14. If request’s priority is null, then use request’s initiator and + // destination appropriately in setting request’s priority to a + // user-agent-defined object. + if (request.priority === null) ; + + // 15. If request is a subresource request, then: + if (subresource.includes(request.destination)) ; + + // 16. Run main fetch given fetchParams. + mainFetch(fetchParams) + .catch(err => { + fetchParams.controller.terminate(err); + }); + + // 17. Return fetchParam's controller + return fetchParams.controller + } + + // https://fetch.spec.whatwg.org/#concept-main-fetch + async function mainFetch (fetchParams, recursive = false) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request; + + // 2. Let response be null. + let response = null; + + // 3. If request’s local-URLs-only flag is set and request’s current URL is + // not local, then set response to a network error. + if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { + response = makeNetworkError('local URLs only'); + } + + // 4. Run report Content Security Policy violations for request. + // TODO + + // 5. Upgrade request to a potentially trustworthy URL, if appropriate. + tryUpgradeRequestToAPotentiallyTrustworthyURL(request); + + // 6. If should request be blocked due to a bad port, should fetching request + // be blocked as mixed content, or should request be blocked by Content + // Security Policy returns blocked, then set response to a network error. + if (requestBadPort(request) === 'blocked') { + response = makeNetworkError('bad port'); + } + // TODO: should fetching request be blocked as mixed content? + // TODO: should request be blocked by Content Security Policy? + + // 7. If request’s referrer policy is the empty string, then set request’s + // referrer policy to request’s policy container’s referrer policy. + if (request.referrerPolicy === '') { + request.referrerPolicy = request.policyContainer.referrerPolicy; + } + + // 8. If request’s referrer is not "no-referrer", then set request’s + // referrer to the result of invoking determine request’s referrer. + if (request.referrer !== 'no-referrer') { + request.referrer = determineRequestsReferrer(request); + } + + // 9. Set request’s current URL’s scheme to "https" if all of the following + // conditions are true: + // - request’s current URL’s scheme is "http" + // - request’s current URL’s host is a domain + // - Matching request’s current URL’s host per Known HSTS Host Domain Name + // Matching results in either a superdomain match with an asserted + // includeSubDomains directive or a congruent match (with or without an + // asserted includeSubDomains directive). [HSTS] + // TODO + + // 10. If recursive is false, then run the remaining steps in parallel. + // TODO + + // 11. If response is null, then set response to the result of running + // the steps corresponding to the first matching statement: + if (response === null) { + response = await (async () => { + const currentURL = requestCurrentURL(request); + + if ( + // - request’s current URL’s origin is same origin with request’s origin, + // and request’s response tainting is "basic" + (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || + // request’s current URL’s scheme is "data" + (currentURL.protocol === 'data:') || + // - request’s mode is "navigate" or "websocket" + (request.mode === 'navigate' || request.mode === 'websocket') + ) { + // 1. Set request’s response tainting to "basic". + request.responseTainting = 'basic'; + + // 2. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } + + // request’s mode is "same-origin" + if (request.mode === 'same-origin') { + // 1. Return a network error. + return makeNetworkError('request mode cannot be "same-origin"') + } + + // request’s mode is "no-cors" + if (request.mode === 'no-cors') { + // 1. If request’s redirect mode is not "follow", then return a network + // error. + if (request.redirect !== 'follow') { + return makeNetworkError( + 'redirect mode cannot be "follow" for "no-cors" request' + ) + } + + // 2. Set request’s response tainting to "opaque". + request.responseTainting = 'opaque'; + + // 3. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } + + // request’s current URL’s scheme is not an HTTP(S) scheme + if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { + // Return a network error. + return makeNetworkError('URL scheme must be a HTTP(S) scheme') + } + + // - request’s use-CORS-preflight flag is set + // - request’s unsafe-request flag is set and either request’s method is + // not a CORS-safelisted method or CORS-unsafe request-header names with + // request’s header list is not empty + // 1. Set request’s response tainting to "cors". + // 2. Let corsWithPreflightResponse be the result of running HTTP fetch + // given fetchParams and true. + // 3. If corsWithPreflightResponse is a network error, then clear cache + // entries using request. + // 4. Return corsWithPreflightResponse. + // TODO + + // Otherwise + // 1. Set request’s response tainting to "cors". + request.responseTainting = 'cors'; + + // 2. Return the result of running HTTP fetch given fetchParams. + return await httpFetch(fetchParams) + })(); + } + + // 12. If recursive is true, then return response. + if (recursive) { + return response + } + + // 13. If response is not a network error and response is not a filtered + // response, then: + if (response.status !== 0 && !response.internalResponse) { + // If request’s response tainting is "cors", then: + if (request.responseTainting === 'cors') ; + + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (request.responseTainting === 'basic') { + response = filterResponse(response, 'basic'); + } else if (request.responseTainting === 'cors') { + response = filterResponse(response, 'cors'); + } else if (request.responseTainting === 'opaque') { + response = filterResponse(response, 'opaque'); + } else { + assert(false); + } + } + + // 14. Let internalResponse be response, if response is a network error, + // and response’s internal response otherwise. + let internalResponse = + response.status === 0 ? response : response.internalResponse; + + // 15. If internalResponse’s URL list is empty, then set it to a clone of + // request’s URL list. + if (internalResponse.urlList.length === 0) { + internalResponse.urlList.push(...request.urlList); + } + + // 16. If request’s timing allow failed flag is unset, then set + // internalResponse’s timing allow passed flag. + if (!request.timingAllowFailed) { + response.timingAllowPassed = true; + } + + // 17. If response is not a network error and any of the following returns + // blocked + // - should internalResponse to request be blocked as mixed content + // - should internalResponse to request be blocked by Content Security Policy + // - should internalResponse to request be blocked due to its MIME type + // - should internalResponse to request be blocked due to nosniff + // TODO + + // 18. If response’s type is "opaque", internalResponse’s status is 206, + // internalResponse’s range-requested flag is set, and request’s header + // list does not contain `Range`, then set response and internalResponse + // to a network error. + if ( + response.type === 'opaque' && + internalResponse.status === 206 && + internalResponse.rangeRequested && + !request.headers.contains('range') + ) { + response = internalResponse = makeNetworkError(); + } + + // 19. If response is not a network error and either request’s method is + // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, + // set internalResponse’s body to null and disregard any enqueuing toward + // it (if any). + if ( + response.status !== 0 && + (request.method === 'HEAD' || + request.method === 'CONNECT' || + nullBodyStatus.includes(internalResponse.status)) + ) { + internalResponse.body = null; + fetchParams.controller.dump = true; + } + + // 20. If request’s integrity metadata is not the empty string, then: + if (request.integrity) { + // 1. Let processBodyError be this step: run fetch finale given fetchParams + // and a network error. + const processBodyError = (reason) => + fetchFinale(fetchParams, makeNetworkError(reason)); + + // 2. If request’s response tainting is "opaque", or response’s body is null, + // then run processBodyError and abort these steps. + if (request.responseTainting === 'opaque' || response.body == null) { + processBodyError(response.error); + return + } + + // 3. Let processBody given bytes be these steps: + const processBody = (bytes) => { + // 1. If bytes do not match request’s integrity metadata, + // then run processBodyError and abort these steps. [SRI] + if (!bytesMatch(bytes, request.integrity)) { + processBodyError('integrity mismatch'); + return + } + + // 2. Set response’s body to bytes as a body. + response.body = safelyExtractBody(bytes)[0]; + + // 3. Run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response); + }; + + // 4. Fully read response’s body given processBody and processBodyError. + await fullyReadBody(response.body, processBody, processBodyError); + } else { + // 21. Otherwise, run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response); + } + } + + // https://fetch.spec.whatwg.org/#concept-scheme-fetch + // given a fetch params fetchParams + function schemeFetch (fetchParams) { + // Note: since the connection is destroyed on redirect, which sets fetchParams to a + // cancelled state, we do not want this condition to trigger *unless* there have been + // no redirects. See https://github.com/nodejs/undici/issues/1776 + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { + return Promise.resolve(makeAppropriateNetworkError(fetchParams)) + } + + // 2. Let request be fetchParams’s request. + const { request } = fetchParams; + + const { protocol: scheme } = requestCurrentURL(request); + + // 3. Switch on request’s current URL’s scheme and run the associated steps: + switch (scheme) { + case 'about:': { + // If request’s current URL’s path is the string "blank", then return a new response + // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », + // and body is the empty byte sequence as a body. + + // Otherwise, return a network error. + return Promise.resolve(makeNetworkError('about scheme is not supported')) + } + case 'blob:': { + if (!resolveObjectURL) { + resolveObjectURL = require$$7.resolveObjectURL; + } + + // 1. Let blobURLEntry be request’s current URL’s blob URL entry. + const blobURLEntry = requestCurrentURL(request); + + // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 + // Buffer.resolveObjectURL does not ignore URL queries. + if (blobURLEntry.search.length !== 0) { + return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) + } + + const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()); + + // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s + // object is not a Blob object, then return a network error. + if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) { + return Promise.resolve(makeNetworkError('invalid method')) + } + + // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. + const bodyWithType = safelyExtractBody(blobURLEntryObject); + + // 4. Let body be bodyWithType’s body. + const body = bodyWithType[0]; + + // 5. Let length be body’s length, serialized and isomorphic encoded. + const length = isomorphicEncode(`${body.length}`); + + // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. + const type = bodyWithType[1] ?? ''; + + // 7. Return a new response whose status message is `OK`, header list is + // « (`Content-Length`, length), (`Content-Type`, type) », and body is body. + const response = makeResponse({ + statusText: 'OK', + headersList: [ + ['content-length', { name: 'Content-Length', value: length }], + ['content-type', { name: 'Content-Type', value: type }] + ] + }); + + response.body = body; + + return Promise.resolve(response) + } + case 'data:': { + // 1. Let dataURLStruct be the result of running the + // data: URL processor on request’s current URL. + const currentURL = requestCurrentURL(request); + const dataURLStruct = dataURLProcessor(currentURL); + + // 2. If dataURLStruct is failure, then return a + // network error. + if (dataURLStruct === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) + } + + // 3. Let mimeType be dataURLStruct’s MIME type, serialized. + const mimeType = serializeAMimeType(dataURLStruct.mimeType); + + // 4. Return a response whose status message is `OK`, + // header list is « (`Content-Type`, mimeType) », + // and body is dataURLStruct’s body as a body. + return Promise.resolve(makeResponse({ + statusText: 'OK', + headersList: [ + ['content-type', { name: 'Content-Type', value: mimeType }] + ], + body: safelyExtractBody(dataURLStruct.body)[0] + })) + } + case 'file:': { + // For now, unfortunate as it is, file URLs are left as an exercise for the reader. + // When in doubt, return a network error. + return Promise.resolve(makeNetworkError('not implemented... yet...')) + } + case 'http:': + case 'https:': { + // Return the result of running HTTP fetch given fetchParams. + + return httpFetch(fetchParams) + .catch((err) => makeNetworkError(err)) + } + default: { + return Promise.resolve(makeNetworkError('unknown scheme')) + } + } + } + + // https://fetch.spec.whatwg.org/#finalize-response + function finalizeResponse (fetchParams, response) { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true; + + // 2, If fetchParams’s process response done is not null, then queue a fetch + // task to run fetchParams’s process response done given response, with + // fetchParams’s task destination. + if (fetchParams.processResponseDone != null) { + queueMicrotask(() => fetchParams.processResponseDone(response)); + } + } + + // https://fetch.spec.whatwg.org/#fetch-finale + function fetchFinale (fetchParams, response) { + // 1. If response is a network error, then: + if (response.type === 'error') { + // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ». + response.urlList = [fetchParams.request.urlList[0]]; + + // 2. Set response’s timing info to the result of creating an opaque timing + // info for fetchParams’s timing info. + response.timingInfo = createOpaqueTimingInfo({ + startTime: fetchParams.timingInfo.startTime + }); + } + + // 2. Let processResponseEndOfBody be the following steps: + const processResponseEndOfBody = () => { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true; + + // If fetchParams’s process response end-of-body is not null, + // then queue a fetch task to run fetchParams’s process response + // end-of-body given response with fetchParams’s task destination. + if (fetchParams.processResponseEndOfBody != null) { + queueMicrotask(() => fetchParams.processResponseEndOfBody(response)); + } + }; + + // 3. If fetchParams’s process response is non-null, then queue a fetch task + // to run fetchParams’s process response given response, with fetchParams’s + // task destination. + if (fetchParams.processResponse != null) { + queueMicrotask(() => fetchParams.processResponse(response)); + } + + // 4. If response’s body is null, then run processResponseEndOfBody. + if (response.body == null) { + processResponseEndOfBody(); + } else { + // 5. Otherwise: + + // 1. Let transformStream be a new a TransformStream. + + // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, + // enqueues chunk in transformStream. + const identityTransformAlgorithm = (chunk, controller) => { + controller.enqueue(chunk); + }; + + // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm + // and flushAlgorithm set to processResponseEndOfBody. + const transformStream = new TransformStream({ + start () {}, + transform: identityTransformAlgorithm, + flush: processResponseEndOfBody + }, { + size () { + return 1 + } + }, { + size () { + return 1 + } + }); + + // 4. Set response’s body to the result of piping response’s body through transformStream. + response.body = { stream: response.body.stream.pipeThrough(transformStream) }; + } + + // 6. If fetchParams’s process response consume body is non-null, then: + if (fetchParams.processResponseConsumeBody != null) { + // 1. Let processBody given nullOrBytes be this step: run fetchParams’s + // process response consume body given response and nullOrBytes. + const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes); + + // 2. Let processBodyError be this step: run fetchParams’s process + // response consume body given response and failure. + const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure); + + // 3. If response’s body is null, then queue a fetch task to run processBody + // given null, with fetchParams’s task destination. + if (response.body == null) { + queueMicrotask(() => processBody(null)); + } else { + // 4. Otherwise, fully read response’s body given processBody, processBodyError, + // and fetchParams’s task destination. + return fullyReadBody(response.body, processBody, processBodyError) + } + return Promise.resolve() + } + } + + // https://fetch.spec.whatwg.org/#http-fetch + async function httpFetch (fetchParams) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request; + + // 2. Let response be null. + let response = null; + + // 3. Let actualResponse be null. + let actualResponse = null; + + // 4. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo; + + // 5. If request’s service-workers mode is "all", then: + if (request.serviceWorkers === 'all') ; + + // 6. If response is null, then: + if (response === null) { + // 1. If makeCORSPreflight is true and one of these conditions is true: + // TODO + + // 2. If request’s redirect mode is "follow", then set request’s + // service-workers mode to "none". + if (request.redirect === 'follow') { + request.serviceWorkers = 'none'; + } + + // 3. Set response and actualResponse to the result of running + // HTTP-network-or-cache fetch given fetchParams. + actualResponse = response = await httpNetworkOrCacheFetch(fetchParams); + + // 4. If request’s response tainting is "cors" and a CORS check + // for request and response returns failure, then return a network error. + if ( + request.responseTainting === 'cors' && + corsCheck(request, response) === 'failure' + ) { + return makeNetworkError('cors failure') + } + + // 5. If the TAO check for request and response returns failure, then set + // request’s timing allow failed flag. + if (TAOCheck(request, response) === 'failure') { + request.timingAllowFailed = true; + } + } + + // 7. If either request’s response tainting or response’s type + // is "opaque", and the cross-origin resource policy check with + // request’s origin, request’s client, request’s destination, + // and actualResponse returns blocked, then return a network error. + if ( + (request.responseTainting === 'opaque' || response.type === 'opaque') && + crossOriginResourcePolicyCheck( + request.origin, + request.client, + request.destination, + actualResponse + ) === 'blocked' + ) { + return makeNetworkError('blocked') + } + + // 8. If actualResponse’s status is a redirect status, then: + if (redirectStatus.includes(actualResponse.status)) { + // 1. If actualResponse’s status is not 303, request’s body is not null, + // and the connection uses HTTP/2, then user agents may, and are even + // encouraged to, transmit an RST_STREAM frame. + // See, https://github.com/whatwg/fetch/issues/1288 + if (request.redirect !== 'manual') { + fetchParams.controller.connection.destroy(); + } + + // 2. Switch on request’s redirect mode: + if (request.redirect === 'error') { + // Set response to a network error. + response = makeNetworkError('unexpected redirect'); + } else if (request.redirect === 'manual') { + // Set response to an opaque-redirect filtered response whose internal + // response is actualResponse. + // NOTE(spec): On the web this would return an `opaqueredirect` response, + // but that doesn't make sense server side. + // See https://github.com/nodejs/undici/issues/1193. + response = actualResponse; + } else if (request.redirect === 'follow') { + // Set response to the result of running HTTP-redirect fetch given + // fetchParams and response. + response = await httpRedirectFetch(fetchParams, response); + } else { + assert(false); + } + } + + // 9. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo; + + // 10. Return response. + return response + } + + // https://fetch.spec.whatwg.org/#http-redirect-fetch + function httpRedirectFetch (fetchParams, response) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request; + + // 2. Let actualResponse be response, if response is not a filtered response, + // and response’s internal response otherwise. + const actualResponse = response.internalResponse + ? response.internalResponse + : response; + + // 3. Let locationURL be actualResponse’s location URL given request’s current + // URL’s fragment. + let locationURL; + + try { + locationURL = responseLocationURL( + actualResponse, + requestCurrentURL(request).hash + ); + + // 4. If locationURL is null, then return response. + if (locationURL == null) { + return response + } + } catch (err) { + // 5. If locationURL is failure, then return a network error. + return Promise.resolve(makeNetworkError(err)) + } + + // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network + // error. + if (!urlIsHttpHttpsScheme(locationURL)) { + return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) + } + + // 7. If request’s redirect count is 20, then return a network error. + if (request.redirectCount === 20) { + return Promise.resolve(makeNetworkError('redirect count exceeded')) + } + + // 8. Increase request’s redirect count by 1. + request.redirectCount += 1; + + // 9. If request’s mode is "cors", locationURL includes credentials, and + // request’s origin is not same origin with locationURL’s origin, then return + // a network error. + if ( + request.mode === 'cors' && + (locationURL.username || locationURL.password) && + !sameOrigin(request, locationURL) + ) { + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) + } + + // 10. If request’s response tainting is "cors" and locationURL includes + // credentials, then return a network error. + if ( + request.responseTainting === 'cors' && + (locationURL.username || locationURL.password) + ) { + return Promise.resolve(makeNetworkError( + 'URL cannot contain credentials for request mode "cors"' + )) + } + + // 11. If actualResponse’s status is not 303, request’s body is non-null, + // and request’s body’s source is null, then return a network error. + if ( + actualResponse.status !== 303 && + request.body != null && + request.body.source == null + ) { + return Promise.resolve(makeNetworkError()) + } + + // 12. If one of the following is true + // - actualResponse’s status is 301 or 302 and request’s method is `POST` + // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` + if ( + ([301, 302].includes(actualResponse.status) && request.method === 'POST') || + (actualResponse.status === 303 && + !['GET', 'HEAD'].includes(request.method)) + ) { + // then: + // 1. Set request’s method to `GET` and request’s body to null. + request.method = 'GET'; + request.body = null; + + // 2. For each headerName of request-body-header name, delete headerName from + // request’s header list. + for (const headerName of requestBodyHeader) { + request.headersList.delete(headerName); + } + } + + // 13. If request’s current URL’s origin is not same origin with locationURL’s + // origin, then for each headerName of CORS non-wildcard request-header name, + // delete headerName from request’s header list. + if (!sameOrigin(requestCurrentURL(request), locationURL)) { + // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name + request.headersList.delete('authorization'); + + // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. + request.headersList.delete('cookie'); + request.headersList.delete('host'); + } + + // 14. If request’s body is non-null, then set request’s body to the first return + // value of safely extracting request’s body’s source. + if (request.body != null) { + assert(request.body.source != null); + request.body = safelyExtractBody(request.body.source)[0]; + } + + // 15. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo; + + // 16. Set timingInfo’s redirect end time and post-redirect start time to the + // coarsened shared current time given fetchParams’s cross-origin isolated + // capability. + timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = + coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability); + + // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s + // redirect start time to timingInfo’s start time. + if (timingInfo.redirectStartTime === 0) { + timingInfo.redirectStartTime = timingInfo.startTime; + } + + // 18. Append locationURL to request’s URL list. + request.urlList.push(locationURL); + + // 19. Invoke set request’s referrer policy on redirect on request and + // actualResponse. + setRequestReferrerPolicyOnRedirect(request, actualResponse); + + // 20. Return the result of running main fetch given fetchParams and true. + return mainFetch(fetchParams, true) + } + + // https://fetch.spec.whatwg.org/#http-network-or-cache-fetch + async function httpNetworkOrCacheFetch ( + fetchParams, + isAuthenticationFetch = false, + isNewConnectionFetch = false + ) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request; + + // 2. Let httpFetchParams be null. + let httpFetchParams = null; + + // 3. Let httpRequest be null. + let httpRequest = null; + + // 4. Let response be null. + let response = null; + + // 8. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If request’s window is "no-window" and request’s redirect mode is + // "error", then set httpFetchParams to fetchParams and httpRequest to + // request. + if (request.window === 'no-window' && request.redirect === 'error') { + httpFetchParams = fetchParams; + httpRequest = request; + } else { + // Otherwise: + + // 1. Set httpRequest to a clone of request. + httpRequest = makeRequest(request); + + // 2. Set httpFetchParams to a copy of fetchParams. + httpFetchParams = { ...fetchParams }; + + // 3. Set httpFetchParams’s request to httpRequest. + httpFetchParams.request = httpRequest; + } + + // 3. Let includeCredentials be true if one of + const includeCredentials = + request.credentials === 'include' || + (request.credentials === 'same-origin' && + request.responseTainting === 'basic'); + + // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s + // body is non-null; otherwise null. + const contentLength = httpRequest.body ? httpRequest.body.length : null; + + // 5. Let contentLengthHeaderValue be null. + let contentLengthHeaderValue = null; + + // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or + // `PUT`, then set contentLengthHeaderValue to `0`. + if ( + httpRequest.body == null && + ['POST', 'PUT'].includes(httpRequest.method) + ) { + contentLengthHeaderValue = '0'; + } + + // 7. If contentLength is non-null, then set contentLengthHeaderValue to + // contentLength, serialized and isomorphic encoded. + if (contentLength != null) { + contentLengthHeaderValue = isomorphicEncode(`${contentLength}`); + } + + // 8. If contentLengthHeaderValue is non-null, then append + // `Content-Length`/contentLengthHeaderValue to httpRequest’s header + // list. + if (contentLengthHeaderValue != null) { + httpRequest.headersList.append('content-length', contentLengthHeaderValue); + } + + // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, + // contentLengthHeaderValue) to httpRequest’s header list. + + // 10. If contentLength is non-null and httpRequest’s keepalive is true, + // then: + if (contentLength != null && httpRequest.keepalive) ; + + // 11. If httpRequest’s referrer is a URL, then append + // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, + // to httpRequest’s header list. + if (httpRequest.referrer instanceof URL) { + httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href)); + } + + // 12. Append a request `Origin` header for httpRequest. + appendRequestOriginHeader(httpRequest); + + // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] + appendFetchMetadata(httpRequest); + + // 14. If httpRequest’s header list does not contain `User-Agent`, then + // user agents should append `User-Agent`/default `User-Agent` value to + // httpRequest’s header list. + if (!httpRequest.headersList.contains('user-agent')) { + httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node'); + } + + // 15. If httpRequest’s cache mode is "default" and httpRequest’s header + // list contains `If-Modified-Since`, `If-None-Match`, + // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set + // httpRequest’s cache mode to "no-store". + if ( + httpRequest.cache === 'default' && + (httpRequest.headersList.contains('if-modified-since') || + httpRequest.headersList.contains('if-none-match') || + httpRequest.headersList.contains('if-unmodified-since') || + httpRequest.headersList.contains('if-match') || + httpRequest.headersList.contains('if-range')) + ) { + httpRequest.cache = 'no-store'; + } + + // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent + // no-cache cache-control header modification flag is unset, and + // httpRequest’s header list does not contain `Cache-Control`, then append + // `Cache-Control`/`max-age=0` to httpRequest’s header list. + if ( + httpRequest.cache === 'no-cache' && + !httpRequest.preventNoCacheCacheControlHeaderModification && + !httpRequest.headersList.contains('cache-control') + ) { + httpRequest.headersList.append('cache-control', 'max-age=0'); + } + + // 17. If httpRequest’s cache mode is "no-store" or "reload", then: + if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { + // 1. If httpRequest’s header list does not contain `Pragma`, then append + // `Pragma`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('pragma')) { + httpRequest.headersList.append('pragma', 'no-cache'); + } + + // 2. If httpRequest’s header list does not contain `Cache-Control`, + // then append `Cache-Control`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('cache-control')) { + httpRequest.headersList.append('cache-control', 'no-cache'); + } + } + + // 18. If httpRequest’s header list contains `Range`, then append + // `Accept-Encoding`/`identity` to httpRequest’s header list. + if (httpRequest.headersList.contains('range')) { + httpRequest.headersList.append('accept-encoding', 'identity'); + } + + // 19. Modify httpRequest’s header list per HTTP. Do not append a given + // header if httpRequest’s header list contains that header’s name. + // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 + if (!httpRequest.headersList.contains('accept-encoding')) { + if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { + httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate'); + } else { + httpRequest.headersList.append('accept-encoding', 'gzip, deflate'); + } + } + + httpRequest.headersList.delete('host'); + + // 21. If there’s a proxy-authentication entry, use it as appropriate. + // TODO: proxy-authentication + + // 22. Set httpCache to the result of determining the HTTP cache + // partition, given httpRequest. + // TODO: cache + + // 23. If httpCache is null, then set httpRequest’s cache mode to + // "no-store". + { + httpRequest.cache = 'no-store'; + } + + // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", + // then: + if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') ; + + // 9. If aborted, then return the appropriate network error for fetchParams. + // TODO + + // 10. If response is null, then: + if (response == null) { + // 1. If httpRequest’s cache mode is "only-if-cached", then return a + // network error. + if (httpRequest.mode === 'only-if-cached') { + return makeNetworkError('only if cached') + } + + // 2. Let forwardResponse be the result of running HTTP-network fetch + // given httpFetchParams, includeCredentials, and isNewConnectionFetch. + const forwardResponse = await httpNetworkFetch( + httpFetchParams, + includeCredentials, + isNewConnectionFetch + ); + + // 3. If httpRequest’s method is unsafe and forwardResponse’s status is + // in the range 200 to 399, inclusive, invalidate appropriate stored + // responses in httpCache, as per the "Invalidation" chapter of HTTP + // Caching, and set storedResponse to null. [HTTP-CACHING] + if ( + !safeMethods.includes(httpRequest.method) && + forwardResponse.status >= 200 && + forwardResponse.status <= 399 + ) ; + + // 5. If response is null, then: + if (response == null) { + // 1. Set response to forwardResponse. + response = forwardResponse; + + // 2. Store httpRequest and forwardResponse in httpCache, as per the + // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] + // TODO: cache + } + } + + // 11. Set response’s URL list to a clone of httpRequest’s URL list. + response.urlList = [...httpRequest.urlList]; + + // 12. If httpRequest’s header list contains `Range`, then set response’s + // range-requested flag. + if (httpRequest.headersList.contains('range')) { + response.rangeRequested = true; + } + + // 13. Set response’s request-includes-credentials to includeCredentials. + response.requestIncludesCredentials = includeCredentials; + + // 14. If response’s status is 401, httpRequest’s response tainting is not + // "cors", includeCredentials is true, and request’s window is an environment + // settings object, then: + // TODO + + // 15. If response’s status is 407, then: + if (response.status === 407) { + // 1. If request’s window is "no-window", then return a network error. + if (request.window === 'no-window') { + return makeNetworkError() + } + + // 2. ??? + + // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 4. Prompt the end user as appropriate in request’s window and store + // the result as a proxy-authentication entry. [HTTP-AUTH] + // TODO: Invoke some kind of callback? + + // 5. Set response to the result of running HTTP-network-or-cache fetch given + // fetchParams. + // TODO + return makeNetworkError('proxy authentication required') + } + + // 16. If all of the following are true + if ( + // response’s status is 421 + response.status === 421 && + // isNewConnectionFetch is false + !isNewConnectionFetch && + // request’s body is null, or request’s body is non-null and request’s body’s source is non-null + (request.body == null || request.body.source != null) + ) { + // then: + + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 2. Set response to the result of running HTTP-network-or-cache + // fetch given fetchParams, isAuthenticationFetch, and true. + + // TODO (spec): The spec doesn't specify this but we need to cancel + // the active response before we can start a new one. + // https://github.com/whatwg/fetch/issues/1293 + fetchParams.controller.connection.destroy(); + + response = await httpNetworkOrCacheFetch( + fetchParams, + isAuthenticationFetch, + true + ); + } + + // 18. Return response. + return response + } + + // https://fetch.spec.whatwg.org/#http-network-fetch + async function httpNetworkFetch ( + fetchParams, + includeCredentials = false, + forceNewConnection = false + ) { + assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed); + + fetchParams.controller.connection = { + abort: null, + destroyed: false, + destroy (err) { + if (!this.destroyed) { + this.destroyed = true; + this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')); + } + } + }; + + // 1. Let request be fetchParams’s request. + const request = fetchParams.request; + + // 2. Let response be null. + let response = null; + + // 3. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo; + + // 5. If httpCache is null, then set request’s cache mode to "no-store". + { + request.cache = 'no-store'; + } + + // 8. Switch on request’s mode: + if (request.mode === 'websocket') ; + + // 9. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If connection is failure, then return a network error. + + // 2. Set timingInfo’s final connection timing info to the result of + // calling clamp and coarsen connection timing info with connection’s + // timing info, timingInfo’s post-redirect start time, and fetchParams’s + // cross-origin isolated capability. + + // 3. If connection is not an HTTP/2 connection, request’s body is non-null, + // and request’s body’s source is null, then append (`Transfer-Encoding`, + // `chunked`) to request’s header list. + + // 4. Set timingInfo’s final network-request start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated + // capability. + + // 5. Set response to the result of making an HTTP request over connection + // using request with the following caveats: + + // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] + // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] + + // - If request’s body is non-null, and request’s body’s source is null, + // then the user agent may have a buffer of up to 64 kibibytes and store + // a part of request’s body in that buffer. If the user agent reads from + // request’s body beyond that buffer’s size and the user agent needs to + // resend request, then instead return a network error. + + // - Set timingInfo’s final network-response start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated capability, + // immediately after the user agent’s HTTP parser receives the first byte + // of the response (e.g., frame header bytes for HTTP/2 or response status + // line for HTTP/1.x). + + // - Wait until all the headers are transmitted. + + // - Any responses whose status is in the range 100 to 199, inclusive, + // and is not 101, are to be ignored, except for the purposes of setting + // timingInfo’s final network-response start time above. + + // - If request’s header list contains `Transfer-Encoding`/`chunked` and + // response is transferred via HTTP/1.0 or older, then return a network + // error. + + // - If the HTTP request results in a TLS client certificate dialog, then: + + // 1. If request’s window is an environment settings object, make the + // dialog available in request’s window. + + // 2. Otherwise, return a network error. + + // To transmit request’s body body, run these steps: + let requestBody = null; + // 1. If body is null and fetchParams’s process request end-of-body is + // non-null, then queue a fetch task given fetchParams’s process request + // end-of-body and fetchParams’s task destination. + if (request.body == null && fetchParams.processRequestEndOfBody) { + queueMicrotask(() => fetchParams.processRequestEndOfBody()); + } else if (request.body != null) { + // 2. Otherwise, if body is non-null: + + // 1. Let processBodyChunk given bytes be these steps: + const processBodyChunk = async function * (bytes) { + // 1. If the ongoing fetch is terminated, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. Run this step in parallel: transmit bytes. + yield bytes; + + // 3. If fetchParams’s process request body is non-null, then run + // fetchParams’s process request body given bytes’s length. + fetchParams.processRequestBodyChunkLength?.(bytes.byteLength); + }; + + // 2. Let processEndOfBody be these steps: + const processEndOfBody = () => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If fetchParams’s process request end-of-body is non-null, + // then run fetchParams’s process request end-of-body. + if (fetchParams.processRequestEndOfBody) { + fetchParams.processRequestEndOfBody(); + } + }; + + // 3. Let processBodyError given e be these steps: + const processBodyError = (e) => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. + if (e.name === 'AbortError') { + fetchParams.controller.abort(); + } else { + fetchParams.controller.terminate(e); + } + }; + + // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, + // processBodyError, and fetchParams’s task destination. + requestBody = (async function * () { + try { + for await (const bytes of request.body.stream) { + yield * processBodyChunk(bytes); + } + processEndOfBody(); + } catch (err) { + processBodyError(err); + } + })(); + } + + try { + // socket is only provided for websockets + const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }); + + if (socket) { + response = makeResponse({ status, statusText, headersList, socket }); + } else { + const iterator = body[Symbol.asyncIterator](); + fetchParams.controller.next = () => iterator.next(); + + response = makeResponse({ status, statusText, headersList }); + } + } catch (err) { + // 10. If aborted, then: + if (err.name === 'AbortError') { + // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. + fetchParams.controller.connection.destroy(); + + // 2. Return the appropriate network error for fetchParams. + return makeAppropriateNetworkError(fetchParams, err) + } + + return makeNetworkError(err) + } + + // 11. Let pullAlgorithm be an action that resumes the ongoing fetch + // if it is suspended. + const pullAlgorithm = () => { + fetchParams.controller.resume(); + }; + + // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s + // controller with reason, given reason. + const cancelAlgorithm = (reason) => { + fetchParams.controller.abort(reason); + }; + + // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by + // the user agent. + // TODO + + // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object + // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. + // TODO + + // 15. Let stream be a new ReadableStream. + // 16. Set up stream with pullAlgorithm set to pullAlgorithm, + // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to + // highWaterMark, and sizeAlgorithm set to sizeAlgorithm. + if (!ReadableStream) { + ReadableStream = require$$14.ReadableStream; + } + + const stream = new ReadableStream( + { + async start (controller) { + fetchParams.controller.controller = controller; + }, + async pull (controller) { + await pullAlgorithm(); + }, + async cancel (reason) { + await cancelAlgorithm(reason); + } + }, + { + highWaterMark: 0, + size () { + return 1 + } + } + ); + + // 17. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. Set response’s body to a new body whose stream is stream. + response.body = { stream }; + + // 2. If response is not a network error and request’s cache mode is + // not "no-store", then update response in httpCache for request. + // TODO + + // 3. If includeCredentials is true and the user agent is not configured + // to block cookies for request (see section 7 of [COOKIES]), then run the + // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on + // the value of each header whose name is a byte-case-insensitive match for + // `Set-Cookie` in response’s header list, if any, and request’s current URL. + // TODO + + // 18. If aborted, then: + // TODO + + // 19. Run these steps in parallel: + + // 1. Run these steps, but abort when fetchParams is canceled: + fetchParams.controller.on('terminated', onAborted); + fetchParams.controller.resume = async () => { + // 1. While true + while (true) { + // 1-3. See onData... + + // 4. Set bytes to the result of handling content codings given + // codings and bytes. + let bytes; + let isFailure; + try { + const { done, value } = await fetchParams.controller.next(); + + if (isAborted(fetchParams)) { + break + } + + bytes = done ? undefined : value; + } catch (err) { + if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { + // zlib doesn't like empty streams. + bytes = undefined; + } else { + bytes = err; + + // err may be propagated from the result of calling readablestream.cancel, + // which might not be an error. https://github.com/nodejs/undici/issues/2009 + isFailure = true; + } + } + + if (bytes === undefined) { + // 2. Otherwise, if the bytes transmission for response’s message + // body is done normally and stream is readable, then close + // stream, finalize response for fetchParams and response, and + // abort these in-parallel steps. + readableStreamClose(fetchParams.controller.controller); + + finalizeResponse(fetchParams, response); + + return + } + + // 5. Increase timingInfo’s decoded body size by bytes’s length. + timingInfo.decodedBodySize += bytes?.byteLength ?? 0; + + // 6. If bytes is failure, then terminate fetchParams’s controller. + if (isFailure) { + fetchParams.controller.terminate(bytes); + return + } + + // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes + // into stream. + fetchParams.controller.controller.enqueue(new Uint8Array(bytes)); + + // 8. If stream is errored, then terminate the ongoing fetch. + if (isErrored(stream)) { + fetchParams.controller.terminate(); + return + } + + // 9. If stream doesn’t need more data ask the user agent to suspend + // the ongoing fetch. + if (!fetchParams.controller.controller.desiredSize) { + return + } + } + }; + + // 2. If aborted, then: + function onAborted (reason) { + // 2. If fetchParams is aborted, then: + if (isAborted(fetchParams)) { + // 1. Set response’s aborted flag. + response.aborted = true; + + // 2. If stream is readable, then error stream with the result of + // deserialize a serialized abort reason given fetchParams’s + // controller’s serialized abort reason and an + // implementation-defined realm. + if (isReadable(stream)) { + fetchParams.controller.controller.error( + fetchParams.controller.serializedAbortReason + ); + } + } else { + // 3. Otherwise, if stream is readable, error stream with a TypeError. + if (isReadable(stream)) { + fetchParams.controller.controller.error(new TypeError('terminated', { + cause: isErrorLike(reason) ? reason : undefined + })); + } + } + + // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. + // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. + fetchParams.controller.connection.destroy(); + } + + // 20. Return response. + return response + + async function dispatch ({ body }) { + const url = requestCurrentURL(request); + /** @type {import('../..').Agent} */ + const agent = fetchParams.controller.dispatcher; + + return new Promise((resolve, reject) => agent.dispatch( + { + path: url.pathname + url.search, + origin: url.origin, + method: request.method, + body: fetchParams.controller.dispatcher.isMockActive ? request.body && request.body.source : body, + headers: request.headersList.entries, + maxRedirections: 0, + upgrade: request.mode === 'websocket' ? 'websocket' : undefined + }, + { + body: null, + abort: null, + + onConnect (abort) { + // TODO (fix): Do we need connection here? + const { connection } = fetchParams.controller; + + if (connection.destroyed) { + abort(new DOMException('The operation was aborted.', 'AbortError')); + } else { + fetchParams.controller.on('terminated', abort); + this.abort = connection.abort = abort; + } + }, + + onHeaders (status, headersList, resume, statusText) { + if (status < 200) { + return + } + + let codings = []; + let location = ''; + + const headers = new Headers(); + + // For H2, the headers are a plain JS object + // We distinguish between them and iterate accordingly + if (Array.isArray(headersList)) { + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1'); + const val = headersList[n + 1].toString('latin1'); + if (key.toLowerCase() === 'content-encoding') { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + // "All content-coding values are case-insensitive..." + codings = val.toLowerCase().split(',').map((x) => x.trim()); + } else if (key.toLowerCase() === 'location') { + location = val; + } + + headers.append(key, val); + } + } else { + const keys = Object.keys(headersList); + for (const key of keys) { + const val = headersList[key]; + if (key.toLowerCase() === 'content-encoding') { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + // "All content-coding values are case-insensitive..." + codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse(); + } else if (key.toLowerCase() === 'location') { + location = val; + } + + headers.append(key, val); + } + } + + this.body = new Readable({ read: resume }); + + const decoders = []; + + const willFollow = request.redirect === 'follow' && + location && + redirectStatus.includes(status); + + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { + for (const coding of codings) { + // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 + if (coding === 'x-gzip' || coding === 'gzip') { + decoders.push(zlib.createGunzip({ + // 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. + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + })); + } else if (coding === 'deflate') { + decoders.push(zlib.createInflate()); + } else if (coding === 'br') { + decoders.push(zlib.createBrotliDecompress()); + } else { + decoders.length = 0; + break + } + } + } + + resolve({ + status, + statusText, + headersList: headers[kHeadersList], + body: decoders.length + ? pipeline(this.body, ...decoders, () => { }) + : this.body.on('error', () => {}) + }); + + return true + }, + + onData (chunk) { + if (fetchParams.controller.dump) { + return + } + + // 1. If one or more bytes have been transmitted from response’s + // message body, then: + + // 1. Let bytes be the transmitted bytes. + const bytes = chunk; + + // 2. Let codings be the result of extracting header list values + // given `Content-Encoding` and response’s header list. + // See pullAlgorithm. + + // 3. Increase timingInfo’s encoded body size by bytes’s length. + timingInfo.encodedBodySize += bytes.byteLength; + + // 4. See pullAlgorithm... + + return this.body.push(bytes) + }, + + onComplete () { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort); + } + + fetchParams.controller.ended = true; + + this.body.push(null); + }, + + onError (error) { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort); + } + + this.body?.destroy(error); + + fetchParams.controller.terminate(error); + + reject(error); + }, + + onUpgrade (status, headersList, socket) { + if (status !== 101) { + return + } + + const headers = new Headers(); + + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1'); + const val = headersList[n + 1].toString('latin1'); + + headers.append(key, val); + } + + resolve({ + status, + statusText: STATUS_CODES[status], + headersList: headers[kHeadersList], + socket + }); + + return true + } + } + )) + } + } + + fetch_1 = { + fetch, + Fetch, + fetching, + finalizeAndReportTiming + }; + return fetch_1; + } + + var symbols$2; + var hasRequiredSymbols$2; + + function requireSymbols$2 () { + if (hasRequiredSymbols$2) return symbols$2; + hasRequiredSymbols$2 = 1; + + symbols$2 = { + kState: Symbol('FileReader state'), + kResult: Symbol('FileReader result'), + kError: Symbol('FileReader error'), + kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), + kEvents: Symbol('FileReader events'), + kAborted: Symbol('FileReader aborted') + }; + return symbols$2; + } + + var progressevent; + var hasRequiredProgressevent; + + function requireProgressevent () { + if (hasRequiredProgressevent) return progressevent; + hasRequiredProgressevent = 1; + + const { webidl } = requireWebidl(); + + const kState = Symbol('ProgressEvent state'); + + /** + * @see https://xhr.spec.whatwg.org/#progressevent + */ + class ProgressEvent extends Event { + constructor (type, eventInitDict = {}) { + type = webidl.converters.DOMString(type); + eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}); + + super(type, eventInitDict); + + this[kState] = { + lengthComputable: eventInitDict.lengthComputable, + loaded: eventInitDict.loaded, + total: eventInitDict.total + }; + } + + get lengthComputable () { + webidl.brandCheck(this, ProgressEvent); + + return this[kState].lengthComputable + } + + get loaded () { + webidl.brandCheck(this, ProgressEvent); + + return this[kState].loaded + } + + get total () { + webidl.brandCheck(this, ProgressEvent); + + return this[kState].total + } + } + + webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ + { + key: 'lengthComputable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'loaded', + converter: webidl.converters['unsigned long long'], + defaultValue: 0 + }, + { + key: 'total', + converter: webidl.converters['unsigned long long'], + defaultValue: 0 + }, + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: false + } + ]); + + progressevent = { + ProgressEvent + }; + return progressevent; + } + + var encoding; + var hasRequiredEncoding; + + function requireEncoding () { + if (hasRequiredEncoding) return encoding; + hasRequiredEncoding = 1; + + /** + * @see https://encoding.spec.whatwg.org/#concept-encoding-get + * @param {string|undefined} label + */ + function getEncoding (label) { + if (!label) { + return 'failure' + } + + // 1. Remove any leading and trailing ASCII whitespace from label. + // 2. If label is an ASCII case-insensitive match for any of the + // labels listed in the table below, then return the + // corresponding encoding; otherwise return failure. + switch (label.trim().toLowerCase()) { + case 'unicode-1-1-utf-8': + case 'unicode11utf8': + case 'unicode20utf8': + case 'utf-8': + case 'utf8': + case 'x-unicode20utf8': + return 'UTF-8' + case '866': + case 'cp866': + case 'csibm866': + case 'ibm866': + return 'IBM866' + case 'csisolatin2': + case 'iso-8859-2': + case 'iso-ir-101': + case 'iso8859-2': + case 'iso88592': + case 'iso_8859-2': + case 'iso_8859-2:1987': + case 'l2': + case 'latin2': + return 'ISO-8859-2' + case 'csisolatin3': + case 'iso-8859-3': + case 'iso-ir-109': + case 'iso8859-3': + case 'iso88593': + case 'iso_8859-3': + case 'iso_8859-3:1988': + case 'l3': + case 'latin3': + return 'ISO-8859-3' + case 'csisolatin4': + case 'iso-8859-4': + case 'iso-ir-110': + case 'iso8859-4': + case 'iso88594': + case 'iso_8859-4': + case 'iso_8859-4:1988': + case 'l4': + case 'latin4': + return 'ISO-8859-4' + case 'csisolatincyrillic': + case 'cyrillic': + case 'iso-8859-5': + case 'iso-ir-144': + case 'iso8859-5': + case 'iso88595': + case 'iso_8859-5': + case 'iso_8859-5:1988': + return 'ISO-8859-5' + case 'arabic': + case 'asmo-708': + case 'csiso88596e': + case 'csiso88596i': + case 'csisolatinarabic': + case 'ecma-114': + case 'iso-8859-6': + case 'iso-8859-6-e': + case 'iso-8859-6-i': + case 'iso-ir-127': + case 'iso8859-6': + case 'iso88596': + case 'iso_8859-6': + case 'iso_8859-6:1987': + return 'ISO-8859-6' + case 'csisolatingreek': + case 'ecma-118': + case 'elot_928': + case 'greek': + case 'greek8': + case 'iso-8859-7': + case 'iso-ir-126': + case 'iso8859-7': + case 'iso88597': + case 'iso_8859-7': + case 'iso_8859-7:1987': + case 'sun_eu_greek': + return 'ISO-8859-7' + case 'csiso88598e': + case 'csisolatinhebrew': + case 'hebrew': + case 'iso-8859-8': + case 'iso-8859-8-e': + case 'iso-ir-138': + case 'iso8859-8': + case 'iso88598': + case 'iso_8859-8': + case 'iso_8859-8:1988': + case 'visual': + return 'ISO-8859-8' + case 'csiso88598i': + case 'iso-8859-8-i': + case 'logical': + return 'ISO-8859-8-I' + case 'csisolatin6': + case 'iso-8859-10': + case 'iso-ir-157': + case 'iso8859-10': + case 'iso885910': + case 'l6': + case 'latin6': + return 'ISO-8859-10' + case 'iso-8859-13': + case 'iso8859-13': + case 'iso885913': + return 'ISO-8859-13' + case 'iso-8859-14': + case 'iso8859-14': + case 'iso885914': + return 'ISO-8859-14' + case 'csisolatin9': + case 'iso-8859-15': + case 'iso8859-15': + case 'iso885915': + case 'iso_8859-15': + case 'l9': + return 'ISO-8859-15' + case 'iso-8859-16': + return 'ISO-8859-16' + case 'cskoi8r': + case 'koi': + case 'koi8': + case 'koi8-r': + case 'koi8_r': + return 'KOI8-R' + case 'koi8-ru': + case 'koi8-u': + return 'KOI8-U' + case 'csmacintosh': + case 'mac': + case 'macintosh': + case 'x-mac-roman': + return 'macintosh' + case 'iso-8859-11': + case 'iso8859-11': + case 'iso885911': + case 'tis-620': + case 'windows-874': + return 'windows-874' + case 'cp1250': + case 'windows-1250': + case 'x-cp1250': + return 'windows-1250' + case 'cp1251': + case 'windows-1251': + case 'x-cp1251': + return 'windows-1251' + case 'ansi_x3.4-1968': + case 'ascii': + case 'cp1252': + case 'cp819': + case 'csisolatin1': + case 'ibm819': + case 'iso-8859-1': + case 'iso-ir-100': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'iso_8859-1:1987': + case 'l1': + case 'latin1': + case 'us-ascii': + case 'windows-1252': + case 'x-cp1252': + return 'windows-1252' + case 'cp1253': + case 'windows-1253': + case 'x-cp1253': + return 'windows-1253' + case 'cp1254': + case 'csisolatin5': + case 'iso-8859-9': + case 'iso-ir-148': + case 'iso8859-9': + case 'iso88599': + case 'iso_8859-9': + case 'iso_8859-9:1989': + case 'l5': + case 'latin5': + case 'windows-1254': + case 'x-cp1254': + return 'windows-1254' + case 'cp1255': + case 'windows-1255': + case 'x-cp1255': + return 'windows-1255' + case 'cp1256': + case 'windows-1256': + case 'x-cp1256': + return 'windows-1256' + case 'cp1257': + case 'windows-1257': + case 'x-cp1257': + return 'windows-1257' + case 'cp1258': + case 'windows-1258': + case 'x-cp1258': + return 'windows-1258' + case 'x-mac-cyrillic': + case 'x-mac-ukrainian': + return 'x-mac-cyrillic' + case 'chinese': + case 'csgb2312': + case 'csiso58gb231280': + case 'gb2312': + case 'gb_2312': + case 'gb_2312-80': + case 'gbk': + case 'iso-ir-58': + case 'x-gbk': + return 'GBK' + case 'gb18030': + return 'gb18030' + case 'big5': + case 'big5-hkscs': + case 'cn-big5': + case 'csbig5': + case 'x-x-big5': + return 'Big5' + case 'cseucpkdfmtjapanese': + case 'euc-jp': + case 'x-euc-jp': + return 'EUC-JP' + case 'csiso2022jp': + case 'iso-2022-jp': + return 'ISO-2022-JP' + case 'csshiftjis': + case 'ms932': + case 'ms_kanji': + case 'shift-jis': + case 'shift_jis': + case 'sjis': + case 'windows-31j': + case 'x-sjis': + return 'Shift_JIS' + case 'cseuckr': + case 'csksc56011987': + case 'euc-kr': + case 'iso-ir-149': + case 'korean': + case 'ks_c_5601-1987': + case 'ks_c_5601-1989': + case 'ksc5601': + case 'ksc_5601': + case 'windows-949': + return 'EUC-KR' + case 'csiso2022kr': + case 'hz-gb-2312': + case 'iso-2022-cn': + case 'iso-2022-cn-ext': + case 'iso-2022-kr': + case 'replacement': + return 'replacement' + case 'unicodefffe': + case 'utf-16be': + return 'UTF-16BE' + case 'csunicode': + case 'iso-10646-ucs-2': + case 'ucs-2': + case 'unicode': + case 'unicodefeff': + case 'utf-16': + case 'utf-16le': + return 'UTF-16LE' + case 'x-user-defined': + return 'x-user-defined' + default: return 'failure' + } + } + + encoding = { + getEncoding + }; + return encoding; + } + + var require$$6 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_string_decoder); + + var util$6; + var hasRequiredUtil$3; + + function requireUtil$3 () { + if (hasRequiredUtil$3) return util$6; + hasRequiredUtil$3 = 1; + + const { + kState, + kError, + kResult, + kAborted, + kLastProgressEventFired + } = requireSymbols$2(); + const { ProgressEvent } = requireProgressevent(); + const { getEncoding } = requireEncoding(); + const { DOMException } = requireConstants$3(); + const { serializeAMimeType, parseMIMEType } = requireDataURL(); + const { types } = require$$3$2; + const { StringDecoder } = require$$6; + const { btoa } = require$$7; + + /** @type {PropertyDescriptor} */ + const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false + }; + + /** + * @see https://w3c.github.io/FileAPI/#readOperation + * @param {import('./filereader').FileReader} fr + * @param {import('buffer').Blob} blob + * @param {string} type + * @param {string?} encodingName + */ + function readOperation (fr, blob, type, encodingName) { + // 1. If fr’s state is "loading", throw an InvalidStateError + // DOMException. + if (fr[kState] === 'loading') { + throw new DOMException('Invalid state', 'InvalidStateError') + } + + // 2. Set fr’s state to "loading". + fr[kState] = 'loading'; + + // 3. Set fr’s result to null. + fr[kResult] = null; + + // 4. Set fr’s error to null. + fr[kError] = null; + + // 5. Let stream be the result of calling get stream on blob. + /** @type {import('stream/web').ReadableStream} */ + const stream = blob.stream(); + + // 6. Let reader be the result of getting a reader from stream. + const reader = stream.getReader(); + + // 7. Let bytes be an empty byte sequence. + /** @type {Uint8Array[]} */ + const bytes = []; + + // 8. Let chunkPromise be the result of reading a chunk from + // stream with reader. + let chunkPromise = reader.read(); + + // 9. Let isFirstChunk be true. + let isFirstChunk = true + + // 10. In parallel, while true: + // Note: "In parallel" just means non-blocking + // Note 2: readOperation itself cannot be async as double + // reading the body would then reject the promise, instead + // of throwing an error. + ;(async () => { + while (!fr[kAborted]) { + // 1. Wait for chunkPromise to be fulfilled or rejected. + try { + const { done, value } = await chunkPromise; + + // 2. If chunkPromise is fulfilled, and isFirstChunk is + // true, queue a task to fire a progress event called + // loadstart at fr. + if (isFirstChunk && !fr[kAborted]) { + queueMicrotask(() => { + fireAProgressEvent('loadstart', fr); + }); + } + + // 3. Set isFirstChunk to false. + isFirstChunk = false; + + // 4. If chunkPromise is fulfilled with an object whose + // done property is false and whose value property is + // a Uint8Array object, run these steps: + if (!done && types.isUint8Array(value)) { + // 1. Let bs be the byte sequence represented by the + // Uint8Array object. + + // 2. Append bs to bytes. + bytes.push(value); + + // 3. If roughly 50ms have passed since these steps + // were last invoked, queue a task to fire a + // progress event called progress at fr. + if ( + ( + fr[kLastProgressEventFired] === undefined || + Date.now() - fr[kLastProgressEventFired] >= 50 + ) && + !fr[kAborted] + ) { + fr[kLastProgressEventFired] = Date.now(); + queueMicrotask(() => { + fireAProgressEvent('progress', fr); + }); + } + + // 4. Set chunkPromise to the result of reading a + // chunk from stream with reader. + chunkPromise = reader.read(); + } else if (done) { + // 5. Otherwise, if chunkPromise is fulfilled with an + // object whose done property is true, queue a task + // to run the following steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done'; + + // 2. Let result be the result of package data given + // bytes, type, blob’s type, and encodingName. + try { + const result = packageData(bytes, type, blob.type, encodingName); + + // 4. Else: + + if (fr[kAborted]) { + return + } + + // 1. Set fr’s result to result. + fr[kResult] = result; + + // 2. Fire a progress event called load at the fr. + fireAProgressEvent('load', fr); + } catch (error) { + // 3. If package data threw an exception error: + + // 1. Set fr’s error to error. + fr[kError] = error; + + // 2. Fire a progress event called error at fr. + fireAProgressEvent('error', fr); + } + + // 5. If fr’s state is not "loading", fire a progress + // event called loadend at the fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr); + } + }); + + break + } + } catch (error) { + if (fr[kAborted]) { + return + } + + // 6. Otherwise, if chunkPromise is rejected with an + // error error, queue a task to run the following + // steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done'; + + // 2. Set fr’s error to error. + fr[kError] = error; + + // 3. Fire a progress event called error at fr. + fireAProgressEvent('error', fr); + + // 4. If fr’s state is not "loading", fire a progress + // event called loadend at fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr); + } + }); + + break + } + } + })(); + } + + /** + * @see https://w3c.github.io/FileAPI/#fire-a-progress-event + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e The name of the event + * @param {import('./filereader').FileReader} reader + */ + function fireAProgressEvent (e, reader) { + // The progress event e does not bubble. e.bubbles must be false + // The progress event e is NOT cancelable. e.cancelable must be false + const event = new ProgressEvent(e, { + bubbles: false, + cancelable: false + }); + + reader.dispatchEvent(event); + } + + /** + * @see https://w3c.github.io/FileAPI/#blob-package-data + * @param {Uint8Array[]} bytes + * @param {string} type + * @param {string?} mimeType + * @param {string?} encodingName + */ + function packageData (bytes, type, mimeType, encodingName) { + // 1. A Blob has an associated package data algorithm, given + // bytes, a type, a optional mimeType, and a optional + // encodingName, which switches on type and runs the + // associated steps: + + switch (type) { + case 'DataURL': { + // 1. Return bytes as a DataURL [RFC2397] subject to + // the considerations below: + // * Use mimeType as part of the Data URL if it is + // available in keeping with the Data URL + // specification [RFC2397]. + // * If mimeType is not available return a Data URL + // without a media-type. [RFC2397]. + + // https://datatracker.ietf.org/doc/html/rfc2397#section-3 + // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data + // mediatype := [ type "/" subtype ] *( ";" parameter ) + // data := *urlchar + // parameter := attribute "=" value + let dataURL = 'data:'; + + const parsed = parseMIMEType(mimeType || 'application/octet-stream'); + + if (parsed !== 'failure') { + dataURL += serializeAMimeType(parsed); + } + + dataURL += ';base64,'; + + const decoder = new StringDecoder('latin1'); + + for (const chunk of bytes) { + dataURL += btoa(decoder.write(chunk)); + } + + dataURL += btoa(decoder.end()); + + return dataURL + } + case 'Text': { + // 1. Let encoding be failure + let encoding = 'failure'; + + // 2. If the encodingName is present, set encoding to the + // result of getting an encoding from encodingName. + if (encodingName) { + encoding = getEncoding(encodingName); + } + + // 3. If encoding is failure, and mimeType is present: + if (encoding === 'failure' && mimeType) { + // 1. Let type be the result of parse a MIME type + // given mimeType. + const type = parseMIMEType(mimeType); + + // 2. If type is not failure, set encoding to the result + // of getting an encoding from type’s parameters["charset"]. + if (type !== 'failure') { + encoding = getEncoding(type.parameters.get('charset')); + } + } + + // 4. If encoding is failure, then set encoding to UTF-8. + if (encoding === 'failure') { + encoding = 'UTF-8'; + } + + // 5. Decode bytes using fallback encoding encoding, and + // return the result. + return decode(bytes, encoding) + } + case 'ArrayBuffer': { + // Return a new ArrayBuffer whose contents are bytes. + const sequence = combineByteSequences(bytes); + + return sequence.buffer + } + case 'BinaryString': { + // Return bytes as a binary string, in which every byte + // is represented by a code unit of equal value [0..255]. + let binaryString = ''; + + const decoder = new StringDecoder('latin1'); + + for (const chunk of bytes) { + binaryString += decoder.write(chunk); + } + + binaryString += decoder.end(); + + return binaryString + } + } + } + + /** + * @see https://encoding.spec.whatwg.org/#decode + * @param {Uint8Array[]} ioQueue + * @param {string} encoding + */ + function decode (ioQueue, encoding) { + const bytes = combineByteSequences(ioQueue); + + // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. + const BOMEncoding = BOMSniffing(bytes); + + let slice = 0; + + // 2. If BOMEncoding is non-null: + if (BOMEncoding !== null) { + // 1. Set encoding to BOMEncoding. + encoding = BOMEncoding; + + // 2. Read three bytes from ioQueue, if BOMEncoding is + // UTF-8; otherwise read two bytes. + // (Do nothing with those bytes.) + slice = BOMEncoding === 'UTF-8' ? 3 : 2; + } + + // 3. Process a queue with an instance of encoding’s + // decoder, ioQueue, output, and "replacement". + + // 4. Return output. + + const sliced = bytes.slice(slice); + return new TextDecoder(encoding).decode(sliced) + } + + /** + * @see https://encoding.spec.whatwg.org/#bom-sniff + * @param {Uint8Array} ioQueue + */ + function BOMSniffing (ioQueue) { + // 1. Let BOM be the result of peeking 3 bytes from ioQueue, + // converted to a byte sequence. + const [a, b, c] = ioQueue; + + // 2. For each of the rows in the table below, starting with + // the first one and going down, if BOM starts with the + // bytes given in the first column, then return the + // encoding given in the cell in the second column of that + // row. Otherwise, return null. + if (a === 0xEF && b === 0xBB && c === 0xBF) { + return 'UTF-8' + } else if (a === 0xFE && b === 0xFF) { + return 'UTF-16BE' + } else if (a === 0xFF && b === 0xFE) { + return 'UTF-16LE' + } + + return null + } + + /** + * @param {Uint8Array[]} sequences + */ + function combineByteSequences (sequences) { + const size = sequences.reduce((a, b) => { + return a + b.byteLength + }, 0); + + let offset = 0; + + return sequences.reduce((a, b) => { + a.set(b, offset); + offset += b.byteLength; + return a + }, new Uint8Array(size)) + } + + util$6 = { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent + }; + return util$6; + } + + var filereader; + var hasRequiredFilereader; + + function requireFilereader () { + if (hasRequiredFilereader) return filereader; + hasRequiredFilereader = 1; + + const { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent + } = requireUtil$3(); + const { + kState, + kError, + kResult, + kEvents, + kAborted + } = requireSymbols$2(); + const { webidl } = requireWebidl(); + const { kEnumerableProperty } = util$l; + + class FileReader extends EventTarget { + constructor () { + super(); + + this[kState] = 'empty'; + this[kResult] = null; + this[kError] = null; + this[kEvents] = { + loadend: null, + error: null, + abort: null, + load: null, + progress: null, + loadstart: null + }; + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer + * @param {import('buffer').Blob} blob + */ + readAsArrayBuffer (blob) { + webidl.brandCheck(this, FileReader); + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' }); + + blob = webidl.converters.Blob(blob, { strict: false }); + + // The readAsArrayBuffer(blob) method, when invoked, + // must initiate a read operation for blob with ArrayBuffer. + readOperation(this, blob, 'ArrayBuffer'); + } + + /** + * @see https://w3c.github.io/FileAPI/#readAsBinaryString + * @param {import('buffer').Blob} blob + */ + readAsBinaryString (blob) { + webidl.brandCheck(this, FileReader); + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' }); + + blob = webidl.converters.Blob(blob, { strict: false }); + + // The readAsBinaryString(blob) method, when invoked, + // must initiate a read operation for blob with BinaryString. + readOperation(this, blob, 'BinaryString'); + } + + /** + * @see https://w3c.github.io/FileAPI/#readAsDataText + * @param {import('buffer').Blob} blob + * @param {string?} encoding + */ + readAsText (blob, encoding = undefined) { + webidl.brandCheck(this, FileReader); + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' }); + + blob = webidl.converters.Blob(blob, { strict: false }); + + if (encoding !== undefined) { + encoding = webidl.converters.DOMString(encoding); + } + + // The readAsText(blob, encoding) method, when invoked, + // must initiate a read operation for blob with Text and encoding. + readOperation(this, blob, 'Text', encoding); + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL + * @param {import('buffer').Blob} blob + */ + readAsDataURL (blob) { + webidl.brandCheck(this, FileReader); + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' }); + + blob = webidl.converters.Blob(blob, { strict: false }); + + // The readAsDataURL(blob) method, when invoked, must + // initiate a read operation for blob with DataURL. + readOperation(this, blob, 'DataURL'); + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-abort + */ + abort () { + // 1. If this's state is "empty" or if this's state is + // "done" set this's result to null and terminate + // this algorithm. + if (this[kState] === 'empty' || this[kState] === 'done') { + this[kResult] = null; + return + } + + // 2. If this's state is "loading" set this's state to + // "done" and set this's result to null. + if (this[kState] === 'loading') { + this[kState] = 'done'; + this[kResult] = null; + } + + // 3. If there are any tasks from this on the file reading + // task source in an affiliated task queue, then remove + // those tasks from that task queue. + this[kAborted] = true; + + // 4. Terminate the algorithm for the read method being processed. + // TODO + + // 5. Fire a progress event called abort at this. + fireAProgressEvent('abort', this); + + // 6. If this's state is not "loading", fire a progress + // event called loadend at this. + if (this[kState] !== 'loading') { + fireAProgressEvent('loadend', this); + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate + */ + get readyState () { + webidl.brandCheck(this, FileReader); + + switch (this[kState]) { + case 'empty': return this.EMPTY + case 'loading': return this.LOADING + case 'done': return this.DONE + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-result + */ + get result () { + webidl.brandCheck(this, FileReader); + + // The result attribute’s getter, when invoked, must return + // this's result. + return this[kResult] + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-error + */ + get error () { + webidl.brandCheck(this, FileReader); + + // The error attribute’s getter, when invoked, must return + // this's error. + return this[kError] + } + + get onloadend () { + webidl.brandCheck(this, FileReader); + + return this[kEvents].loadend + } + + set onloadend (fn) { + webidl.brandCheck(this, FileReader); + + if (this[kEvents].loadend) { + this.removeEventListener('loadend', this[kEvents].loadend); + } + + if (typeof fn === 'function') { + this[kEvents].loadend = fn; + this.addEventListener('loadend', fn); + } else { + this[kEvents].loadend = null; + } + } + + get onerror () { + webidl.brandCheck(this, FileReader); + + return this[kEvents].error + } + + set onerror (fn) { + webidl.brandCheck(this, FileReader); + + if (this[kEvents].error) { + this.removeEventListener('error', this[kEvents].error); + } + + if (typeof fn === 'function') { + this[kEvents].error = fn; + this.addEventListener('error', fn); + } else { + this[kEvents].error = null; + } + } + + get onloadstart () { + webidl.brandCheck(this, FileReader); + + return this[kEvents].loadstart + } + + set onloadstart (fn) { + webidl.brandCheck(this, FileReader); + + if (this[kEvents].loadstart) { + this.removeEventListener('loadstart', this[kEvents].loadstart); + } + + if (typeof fn === 'function') { + this[kEvents].loadstart = fn; + this.addEventListener('loadstart', fn); + } else { + this[kEvents].loadstart = null; + } + } + + get onprogress () { + webidl.brandCheck(this, FileReader); + + return this[kEvents].progress + } + + set onprogress (fn) { + webidl.brandCheck(this, FileReader); + + if (this[kEvents].progress) { + this.removeEventListener('progress', this[kEvents].progress); + } + + if (typeof fn === 'function') { + this[kEvents].progress = fn; + this.addEventListener('progress', fn); + } else { + this[kEvents].progress = null; + } + } + + get onload () { + webidl.brandCheck(this, FileReader); + + return this[kEvents].load + } + + set onload (fn) { + webidl.brandCheck(this, FileReader); + + if (this[kEvents].load) { + this.removeEventListener('load', this[kEvents].load); + } + + if (typeof fn === 'function') { + this[kEvents].load = fn; + this.addEventListener('load', fn); + } else { + this[kEvents].load = null; + } + } + + get onabort () { + webidl.brandCheck(this, FileReader); + + return this[kEvents].abort + } + + set onabort (fn) { + webidl.brandCheck(this, FileReader); + + if (this[kEvents].abort) { + this.removeEventListener('abort', this[kEvents].abort); + } + + if (typeof fn === 'function') { + this[kEvents].abort = fn; + this.addEventListener('abort', fn); + } else { + this[kEvents].abort = null; + } + } + } + + // https://w3c.github.io/FileAPI/#dom-filereader-empty + FileReader.EMPTY = FileReader.prototype.EMPTY = 0; + // https://w3c.github.io/FileAPI/#dom-filereader-loading + FileReader.LOADING = FileReader.prototype.LOADING = 1; + // https://w3c.github.io/FileAPI/#dom-filereader-done + FileReader.DONE = FileReader.prototype.DONE = 2; + + Object.defineProperties(FileReader.prototype, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors, + readAsArrayBuffer: kEnumerableProperty, + readAsBinaryString: kEnumerableProperty, + readAsText: kEnumerableProperty, + readAsDataURL: kEnumerableProperty, + abort: kEnumerableProperty, + readyState: kEnumerableProperty, + result: kEnumerableProperty, + error: kEnumerableProperty, + onloadstart: kEnumerableProperty, + onprogress: kEnumerableProperty, + onload: kEnumerableProperty, + onabort: kEnumerableProperty, + onerror: kEnumerableProperty, + onloadend: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'FileReader', + writable: false, + enumerable: false, + configurable: true + } + }); + + Object.defineProperties(FileReader, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors + }); + + filereader = { + FileReader + }; + return filereader; + } + + var symbols$1; + var hasRequiredSymbols$1; + + function requireSymbols$1 () { + if (hasRequiredSymbols$1) return symbols$1; + hasRequiredSymbols$1 = 1; + + symbols$1 = { + kConstruct: Symbol('constructable') + }; + return symbols$1; + } + + var util$5; + var hasRequiredUtil$2; + + function requireUtil$2 () { + if (hasRequiredUtil$2) return util$5; + hasRequiredUtil$2 = 1; + + const assert = require$$3$1; + const { URLSerializer } = requireDataURL(); + const { isValidHeaderName } = requireUtil$4(); + + /** + * @see https://url.spec.whatwg.org/#concept-url-equals + * @param {URL} A + * @param {URL} B + * @param {boolean | undefined} excludeFragment + * @returns {boolean} + */ + function urlEquals (A, B, excludeFragment = false) { + const serializedA = URLSerializer(A, excludeFragment); + + const serializedB = URLSerializer(B, excludeFragment); + + return serializedA === serializedB + } + + /** + * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 + * @param {string} header + */ + function fieldValues (header) { + assert(header !== null); + + const values = []; + + for (let value of header.split(',')) { + value = value.trim(); + + if (!value.length) { + continue + } else if (!isValidHeaderName(value)) { + continue + } + + values.push(value); + } + + return values + } + + util$5 = { + urlEquals, + fieldValues + }; + return util$5; + } + + var cache; + var hasRequiredCache; + + function requireCache () { + if (hasRequiredCache) return cache; + hasRequiredCache = 1; + + const { kConstruct } = requireSymbols$1(); + const { urlEquals, fieldValues: getFieldValues } = requireUtil$2(); + const { kEnumerableProperty, isDisturbed } = util$l; + const { kHeadersList } = symbols$4; + const { webidl } = requireWebidl(); + const { Response, cloneResponse } = requireResponse(); + const { Request } = requireRequest(); + const { kState, kHeaders, kGuard, kRealm } = requireSymbols$3(); + const { fetching } = requireFetch(); + const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = requireUtil$4(); + const assert = require$$3$1; + const { getGlobalDispatcher } = global$1; + + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation + * @typedef {Object} CacheBatchOperation + * @property {'delete' | 'put'} type + * @property {any} request + * @property {any} response + * @property {import('../../types/cache').CacheQueryOptions} options + */ + + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list + * @typedef {[any, any][]} requestResponseList + */ + + class Cache { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list + * @type {requestResponseList} + */ + #relevantRequestResponseList + + constructor () { + if (arguments[0] !== kConstruct) { + webidl.illegalConstructor(); + } + + this.#relevantRequestResponseList = arguments[1]; + } + + async match (request, options = {}) { + webidl.brandCheck(this, Cache); + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' }); + + request = webidl.converters.RequestInfo(request); + options = webidl.converters.CacheQueryOptions(options); + + const p = await this.matchAll(request, options); + + if (p.length === 0) { + return + } + + return p[0] + } + + async matchAll (request = undefined, options = {}) { + webidl.brandCheck(this, Cache); + + if (request !== undefined) request = webidl.converters.RequestInfo(request); + options = webidl.converters.CacheQueryOptions(options); + + // 1. + let r = null; + + // 2. + if (request !== undefined) { + if (request instanceof Request) { + // 2.1.1 + r = request[kState]; + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { + // 2.2.1 + r = new Request(request)[kState]; + } + } + + // 5. + // 5.1 + const responses = []; + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + responses.push(requestResponse[1]); + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options); + + // 5.3.2 + for (const requestResponse of requestResponses) { + responses.push(requestResponse[1]); + } + } + + // 5.4 + // We don't implement CORs so we don't need to loop over the responses, yay! + + // 5.5.1 + const responseList = []; + + // 5.5.2 + for (const response of responses) { + // 5.5.2.1 + const responseObject = new Response(response.body?.source ?? null); + const body = responseObject[kState].body; + responseObject[kState] = response; + responseObject[kState].body = body; + responseObject[kHeaders][kHeadersList] = response.headersList; + responseObject[kHeaders][kGuard] = 'immutable'; + + responseList.push(responseObject); + } + + // 6. + return Object.freeze(responseList) + } + + async add (request) { + webidl.brandCheck(this, Cache); + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }); + + request = webidl.converters.RequestInfo(request); + + // 1. + const requests = [request]; + + // 2. + const responseArrayPromise = this.addAll(requests); + + // 3. + return await responseArrayPromise + } + + async addAll (requests) { + webidl.brandCheck(this, Cache); + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }); + + requests = webidl.converters['sequence'](requests); + + // 1. + const responsePromises = []; + + // 2. + const requestList = []; + + // 3. + for (const request of requests) { + if (typeof request === 'string') { + continue + } + + // 3.1 + const r = request[kState]; + + // 3.2 + if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Expected http/s scheme when method is not GET.' + }) + } + } + + // 4. + /** @type {ReturnType[]} */ + const fetchControllers = []; + + // 5. + for (const request of requests) { + // 5.1 + const r = new Request(request)[kState]; + + // 5.2 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Expected http/s scheme.' + }) + } + + // 5.4 + r.initiator = 'fetch'; + r.destination = 'subresource'; + + // 5.5 + requestList.push(r); + + // 5.6 + const responsePromise = createDeferredPromise(); + + // 5.7 + fetchControllers.push(fetching({ + request: r, + dispatcher: getGlobalDispatcher(), + processResponse (response) { + // 1. + if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Received an invalid status code or the request failed.' + })); + } else if (response.headersList.contains('vary')) { // 2. + // 2.1 + const fieldValues = getFieldValues(response.headersList.get('vary')); + + // 2.2 + for (const fieldValue of fieldValues) { + // 2.2.1 + if (fieldValue === '*') { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'invalid vary field value' + })); + + for (const controller of fetchControllers) { + controller.abort(); + } + + return + } + } + } + }, + processResponseEndOfBody (response) { + // 1. + if (response.aborted) { + responsePromise.reject(new DOMException('aborted', 'AbortError')); + return + } + + // 2. + responsePromise.resolve(response); + } + })); + + // 5.8 + responsePromises.push(responsePromise.promise); + } + + // 6. + const p = Promise.all(responsePromises); + + // 7. + const responses = await p; + + // 7.1 + const operations = []; + + // 7.2 + let index = 0; + + // 7.3 + for (const response of responses) { + // 7.3.1 + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 7.3.2 + request: requestList[index], // 7.3.3 + response // 7.3.4 + }; + + operations.push(operation); // 7.3.5 + + index++; // 7.3.6 + } + + // 7.5 + const cacheJobPromise = createDeferredPromise(); + + // 7.6.1 + let errorData = null; + + // 7.6.2 + try { + this.#batchCacheOperations(operations); + } catch (e) { + errorData = e; + } + + // 7.6.3 + queueMicrotask(() => { + // 7.6.3.1 + if (errorData === null) { + cacheJobPromise.resolve(undefined); + } else { + // 7.6.3.2 + cacheJobPromise.reject(errorData); + } + }); + + // 7.7 + return cacheJobPromise.promise + } + + async put (request, response) { + webidl.brandCheck(this, Cache); + webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' }); + + request = webidl.converters.RequestInfo(request); + response = webidl.converters.Response(response); + + // 1. + let innerRequest = null; + + // 2. + if (request instanceof Request) { + innerRequest = request[kState]; + } else { // 3. + innerRequest = new Request(request)[kState]; + } + + // 4. + if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Expected an http/s scheme when method is not GET' + }) + } + + // 5. + const innerResponse = response[kState]; + + // 6. + if (innerResponse.status === 206) { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got 206 status' + }) + } + + // 7. + if (innerResponse.headersList.contains('vary')) { + // 7.1. + const fieldValues = getFieldValues(innerResponse.headersList.get('vary')); + + // 7.2. + for (const fieldValue of fieldValues) { + // 7.2.1 + if (fieldValue === '*') { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got * vary field value' + }) + } + } + } + + // 8. + if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Response body is locked or disturbed' + }) + } + + // 9. + const clonedResponse = cloneResponse(innerResponse); + + // 10. + const bodyReadPromise = createDeferredPromise(); + + // 11. + if (innerResponse.body != null) { + // 11.1 + const stream = innerResponse.body.stream; + + // 11.2 + const reader = stream.getReader(); + + // 11.3 + readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject); + } else { + bodyReadPromise.resolve(undefined); + } + + // 12. + /** @type {CacheBatchOperation[]} */ + const operations = []; + + // 13. + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 14. + request: innerRequest, // 15. + response: clonedResponse // 16. + }; + + // 17. + operations.push(operation); + + // 19. + const bytes = await bodyReadPromise.promise; + + if (clonedResponse.body != null) { + clonedResponse.body.source = bytes; + } + + // 19.1 + const cacheJobPromise = createDeferredPromise(); + + // 19.2.1 + let errorData = null; + + // 19.2.2 + try { + this.#batchCacheOperations(operations); + } catch (e) { + errorData = e; + } + + // 19.2.3 + queueMicrotask(() => { + // 19.2.3.1 + if (errorData === null) { + cacheJobPromise.resolve(); + } else { // 19.2.3.2 + cacheJobPromise.reject(errorData); + } + }); + + return cacheJobPromise.promise + } + + async delete (request, options = {}) { + webidl.brandCheck(this, Cache); + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' }); + + request = webidl.converters.RequestInfo(request); + options = webidl.converters.CacheQueryOptions(options); + + /** + * @type {Request} + */ + let r = null; + + if (request instanceof Request) { + r = request[kState]; + + if (r.method !== 'GET' && !options.ignoreMethod) { + return false + } + } else { + assert(typeof request === 'string'); + + r = new Request(request)[kState]; + } + + /** @type {CacheBatchOperation[]} */ + const operations = []; + + /** @type {CacheBatchOperation} */ + const operation = { + type: 'delete', + request: r, + options + }; + + operations.push(operation); + + const cacheJobPromise = createDeferredPromise(); + + let errorData = null; + let requestResponses; + + try { + requestResponses = this.#batchCacheOperations(operations); + } catch (e) { + errorData = e; + } + + queueMicrotask(() => { + if (errorData === null) { + cacheJobPromise.resolve(!!requestResponses?.length); + } else { + cacheJobPromise.reject(errorData); + } + }); + + return cacheJobPromise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys + * @param {any} request + * @param {import('../../types/cache').CacheQueryOptions} options + * @returns {readonly Request[]} + */ + async keys (request = undefined, options = {}) { + webidl.brandCheck(this, Cache); + + if (request !== undefined) request = webidl.converters.RequestInfo(request); + options = webidl.converters.CacheQueryOptions(options); + + // 1. + let r = null; + + // 2. + if (request !== undefined) { + // 2.1 + if (request instanceof Request) { + // 2.1.1 + r = request[kState]; + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { // 2.2 + r = new Request(request)[kState]; + } + } + + // 4. + const promise = createDeferredPromise(); + + // 5. + // 5.1 + const requests = []; + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + // 5.2.1.1 + requests.push(requestResponse[0]); + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options); + + // 5.3.2 + for (const requestResponse of requestResponses) { + // 5.3.2.1 + requests.push(requestResponse[0]); + } + } + + // 5.4 + queueMicrotask(() => { + // 5.4.1 + const requestList = []; + + // 5.4.2 + for (const request of requests) { + const requestObject = new Request('https://a'); + requestObject[kState] = request; + requestObject[kHeaders][kHeadersList] = request.headersList; + requestObject[kHeaders][kGuard] = 'immutable'; + requestObject[kRealm] = request.client; + + // 5.4.2.1 + requestList.push(requestObject); + } + + // 5.4.3 + promise.resolve(Object.freeze(requestList)); + }); + + return promise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm + * @param {CacheBatchOperation[]} operations + * @returns {requestResponseList} + */ + #batchCacheOperations (operations) { + // 1. + const cache = this.#relevantRequestResponseList; + + // 2. + const backupCache = [...cache]; + + // 3. + const addedItems = []; + + // 4.1 + const resultList = []; + + try { + // 4.2 + for (const operation of operations) { + // 4.2.1 + if (operation.type !== 'delete' && operation.type !== 'put') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'operation type does not match "delete" or "put"' + }) + } + + // 4.2.2 + if (operation.type === 'delete' && operation.response != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'delete operation should not have an associated response' + }) + } + + // 4.2.3 + if (this.#queryCache(operation.request, operation.options, addedItems).length) { + throw new DOMException('???', 'InvalidStateError') + } + + // 4.2.4 + let requestResponses; + + // 4.2.5 + if (operation.type === 'delete') { + // 4.2.5.1 + requestResponses = this.#queryCache(operation.request, operation.options); + + // TODO: the spec is wrong, this is needed to pass WPTs + if (requestResponses.length === 0) { + return [] + } + + // 4.2.5.2 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse); + assert(idx !== -1); + + // 4.2.5.2.1 + cache.splice(idx, 1); + } + } else if (operation.type === 'put') { // 4.2.6 + // 4.2.6.1 + if (operation.response == null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'put operation should have an associated response' + }) + } + + // 4.2.6.2 + const r = operation.request; + + // 4.2.6.3 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'expected http or https scheme' + }) + } + + // 4.2.6.4 + if (r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'not get method' + }) + } + + // 4.2.6.5 + if (operation.options != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'options must not be defined' + }) + } + + // 4.2.6.6 + requestResponses = this.#queryCache(operation.request); + + // 4.2.6.7 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse); + assert(idx !== -1); + + // 4.2.6.7.1 + cache.splice(idx, 1); + } + + // 4.2.6.8 + cache.push([operation.request, operation.response]); + + // 4.2.6.10 + addedItems.push([operation.request, operation.response]); + } + + // 4.2.7 + resultList.push([operation.request, operation.response]); + } + + // 4.3 + return resultList + } catch (e) { // 5. + // 5.1 + this.#relevantRequestResponseList.length = 0; + + // 5.2 + this.#relevantRequestResponseList = backupCache; + + // 5.3 + throw e + } + } + + /** + * @see https://w3c.github.io/ServiceWorker/#query-cache + * @param {any} requestQuery + * @param {import('../../types/cache').CacheQueryOptions} options + * @param {requestResponseList} targetStorage + * @returns {requestResponseList} + */ + #queryCache (requestQuery, options, targetStorage) { + /** @type {requestResponseList} */ + const resultList = []; + + const storage = targetStorage ?? this.#relevantRequestResponseList; + + for (const requestResponse of storage) { + const [cachedRequest, cachedResponse] = requestResponse; + if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { + resultList.push(requestResponse); + } + } + + return resultList + } + + /** + * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm + * @param {any} requestQuery + * @param {any} request + * @param {any | null} response + * @param {import('../../types/cache').CacheQueryOptions | undefined} options + * @returns {boolean} + */ + #requestMatchesCachedItem (requestQuery, request, response = null, options) { + // if (options?.ignoreMethod === false && request.method === 'GET') { + // return false + // } + + const queryURL = new URL(requestQuery.url); + + const cachedURL = new URL(request.url); + + if (options?.ignoreSearch) { + cachedURL.search = ''; + + queryURL.search = ''; + } + + if (!urlEquals(queryURL, cachedURL, true)) { + return false + } + + if ( + response == null || + options?.ignoreVary || + !response.headersList.contains('vary') + ) { + return true + } + + const fieldValues = getFieldValues(response.headersList.get('vary')); + + for (const fieldValue of fieldValues) { + if (fieldValue === '*') { + return false + } + + const requestValue = request.headersList.get(fieldValue); + const queryValue = requestQuery.headersList.get(fieldValue); + + // If one has the header and the other doesn't, or one has + // a different value than the other, return false + if (requestValue !== queryValue) { + return false + } + } + + return true + } + } + + Object.defineProperties(Cache.prototype, { + [Symbol.toStringTag]: { + value: 'Cache', + configurable: true + }, + match: kEnumerableProperty, + matchAll: kEnumerableProperty, + add: kEnumerableProperty, + addAll: kEnumerableProperty, + put: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty + }); + + const cacheQueryOptionConverters = [ + { + key: 'ignoreSearch', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'ignoreMethod', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'ignoreVary', + converter: webidl.converters.boolean, + defaultValue: false + } + ]; + + webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters); + + webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ + ...cacheQueryOptionConverters, + { + key: 'cacheName', + converter: webidl.converters.DOMString + } + ]); + + webidl.converters.Response = webidl.interfaceConverter(Response); + + webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.RequestInfo + ); + + cache = { + Cache + }; + return cache; + } + + var cachestorage; + var hasRequiredCachestorage; + + function requireCachestorage () { + if (hasRequiredCachestorage) return cachestorage; + hasRequiredCachestorage = 1; + + const { kConstruct } = requireSymbols$1(); + const { Cache } = requireCache(); + const { webidl } = requireWebidl(); + const { kEnumerableProperty } = util$l; + + class CacheStorage { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map + * @type {Map} + */ + async has (cacheName) { + webidl.brandCheck(this, CacheStorage); + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' }); + + cacheName = webidl.converters.DOMString(cacheName); + + // 2.1.1 + // 2.2 + return this.#caches.has(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open + * @param {string} cacheName + * @returns {Promise} + */ + async open (cacheName) { + webidl.brandCheck(this, CacheStorage); + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' }); + + cacheName = webidl.converters.DOMString(cacheName); + + // 2.1 + if (this.#caches.has(cacheName)) { + // await caches.open('v1') !== await caches.open('v1') + + // 2.1.1 + const cache = this.#caches.get(cacheName); + + // 2.1.1.1 + return new Cache(kConstruct, cache) + } + + // 2.2 + const cache = []; + + // 2.3 + this.#caches.set(cacheName, cache); + + // 2.4 + return new Cache(kConstruct, cache) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete + * @param {string} cacheName + * @returns {Promise} + */ + async delete (cacheName) { + webidl.brandCheck(this, CacheStorage); + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' }); + + cacheName = webidl.converters.DOMString(cacheName); + + return this.#caches.delete(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys + * @returns {string[]} + */ + async keys () { + webidl.brandCheck(this, CacheStorage); + + // 2.1 + const keys = this.#caches.keys(); + + // 2.2 + return [...keys] + } + } + + Object.defineProperties(CacheStorage.prototype, { + [Symbol.toStringTag]: { + value: 'CacheStorage', + configurable: true + }, + match: kEnumerableProperty, + has: kEnumerableProperty, + open: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty + }); + + cachestorage = { + CacheStorage + }; + return cachestorage; + } + + var constants$1; + var hasRequiredConstants$1; + + function requireConstants$1 () { + if (hasRequiredConstants$1) return constants$1; + hasRequiredConstants$1 = 1; + + // https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size + const maxAttributeValueSize = 1024; + + // https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size + const maxNameValuePairSize = 4096; + + constants$1 = { + maxAttributeValueSize, + maxNameValuePairSize + }; + return constants$1; + } + + var util$4; + var hasRequiredUtil$1; + + function requireUtil$1 () { + if (hasRequiredUtil$1) return util$4; + hasRequiredUtil$1 = 1; + + const assert = require$$3$1; + const { kHeadersList } = symbols$4; + + function isCTLExcludingHtab (value) { + if (value.length === 0) { + return false + } + + for (const char of value) { + const code = char.charCodeAt(0); + + if ( + (code >= 0x00 || code <= 0x08) || + (code >= 0x0A || code <= 0x1F) || + code === 0x7F + ) { + return false + } + } + } + + /** + CHAR = + token = 1* + separators = "(" | ")" | "<" | ">" | "@" + | "," | ";" | ":" | "\" | <"> + | "/" | "[" | "]" | "?" | "=" + | "{" | "}" | SP | HT + * @param {string} name + */ + function validateCookieName (name) { + for (const char of name) { + const code = char.charCodeAt(0); + + if ( + (code <= 0x20 || code > 0x7F) || + char === '(' || + char === ')' || + char === '>' || + char === '<' || + char === '@' || + char === ',' || + char === ';' || + char === ':' || + char === '\\' || + char === '"' || + char === '/' || + char === '[' || + char === ']' || + char === '?' || + char === '=' || + char === '{' || + char === '}' + ) { + throw new Error('Invalid cookie name') + } + } + } + + /** + cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + ; US-ASCII characters excluding CTLs, + ; whitespace DQUOTE, comma, semicolon, + ; and backslash + * @param {string} value + */ + function validateCookieValue (value) { + for (const char of value) { + const code = char.charCodeAt(0); + + if ( + code < 0x21 || // exclude CTLs (0-31) + code === 0x22 || + code === 0x2C || + code === 0x3B || + code === 0x5C || + code > 0x7E // non-ascii + ) { + throw new Error('Invalid header value') + } + } + } + + /** + * path-value = + * @param {string} path + */ + function validateCookiePath (path) { + for (const char of path) { + const code = char.charCodeAt(0); + + if (code < 0x21 || char === ';') { + throw new Error('Invalid cookie path') + } + } + } + + /** + * I have no idea why these values aren't allowed to be honest, + * but Deno tests these. - Khafra + * @param {string} domain + */ + function validateCookieDomain (domain) { + if ( + domain.startsWith('-') || + domain.endsWith('.') || + domain.endsWith('-') + ) { + throw new Error('Invalid cookie domain') + } + } + + /** + * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 + * @param {number|Date} date + IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT + ; fixed length/zone/capitalization subset of the format + ; see Section 3.3 of [RFC5322] + + day-name = %x4D.6F.6E ; "Mon", case-sensitive + / %x54.75.65 ; "Tue", case-sensitive + / %x57.65.64 ; "Wed", case-sensitive + / %x54.68.75 ; "Thu", case-sensitive + / %x46.72.69 ; "Fri", case-sensitive + / %x53.61.74 ; "Sat", case-sensitive + / %x53.75.6E ; "Sun", case-sensitive + date1 = day SP month SP year + ; e.g., 02 Jun 1982 + + day = 2DIGIT + month = %x4A.61.6E ; "Jan", case-sensitive + / %x46.65.62 ; "Feb", case-sensitive + / %x4D.61.72 ; "Mar", case-sensitive + / %x41.70.72 ; "Apr", case-sensitive + / %x4D.61.79 ; "May", case-sensitive + / %x4A.75.6E ; "Jun", case-sensitive + / %x4A.75.6C ; "Jul", case-sensitive + / %x41.75.67 ; "Aug", case-sensitive + / %x53.65.70 ; "Sep", case-sensitive + / %x4F.63.74 ; "Oct", case-sensitive + / %x4E.6F.76 ; "Nov", case-sensitive + / %x44.65.63 ; "Dec", case-sensitive + year = 4DIGIT + + GMT = %x47.4D.54 ; "GMT", case-sensitive + + time-of-day = hour ":" minute ":" second + ; 00:00:00 - 23:59:60 (leap second) + + hour = 2DIGIT + minute = 2DIGIT + second = 2DIGIT + */ + function toIMFDate (date) { + if (typeof date === 'number') { + date = new Date(date); + } + + const days = [ + 'Sun', 'Mon', 'Tue', 'Wed', + 'Thu', 'Fri', 'Sat' + ]; + + const months = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + ]; + + const dayName = days[date.getUTCDay()]; + const day = date.getUTCDate().toString().padStart(2, '0'); + const month = months[date.getUTCMonth()]; + const year = date.getUTCFullYear(); + const hour = date.getUTCHours().toString().padStart(2, '0'); + const minute = date.getUTCMinutes().toString().padStart(2, '0'); + const second = date.getUTCSeconds().toString().padStart(2, '0'); + + return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT` + } + + /** + max-age-av = "Max-Age=" non-zero-digit *DIGIT + ; In practice, both expires-av and max-age-av + ; are limited to dates representable by the + ; user agent. + * @param {number} maxAge + */ + function validateCookieMaxAge (maxAge) { + if (maxAge < 0) { + throw new Error('Invalid cookie max-age') + } + } + + /** + * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 + * @param {import('./index').Cookie} cookie + */ + function stringify (cookie) { + if (cookie.name.length === 0) { + return null + } + + validateCookieName(cookie.name); + validateCookieValue(cookie.value); + + const out = [`${cookie.name}=${cookie.value}`]; + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 + if (cookie.name.startsWith('__Secure-')) { + cookie.secure = true; + } + + if (cookie.name.startsWith('__Host-')) { + cookie.secure = true; + cookie.domain = null; + cookie.path = '/'; + } + + if (cookie.secure) { + out.push('Secure'); + } + + if (cookie.httpOnly) { + out.push('HttpOnly'); + } + + if (typeof cookie.maxAge === 'number') { + validateCookieMaxAge(cookie.maxAge); + out.push(`Max-Age=${cookie.maxAge}`); + } + + if (cookie.domain) { + validateCookieDomain(cookie.domain); + out.push(`Domain=${cookie.domain}`); + } + + if (cookie.path) { + validateCookiePath(cookie.path); + out.push(`Path=${cookie.path}`); + } + + if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { + out.push(`Expires=${toIMFDate(cookie.expires)}`); + } + + if (cookie.sameSite) { + out.push(`SameSite=${cookie.sameSite}`); + } + + for (const part of cookie.unparsed) { + if (!part.includes('=')) { + throw new Error('Invalid unparsed') + } + + const [key, ...value] = part.split('='); + + out.push(`${key.trim()}=${value.join('=')}`); + } + + return out.join('; ') + } + + let kHeadersListNode; + + function getHeadersList (headers) { + if (headers[kHeadersList]) { + return headers[kHeadersList] + } + + if (!kHeadersListNode) { + kHeadersListNode = Object.getOwnPropertySymbols(headers).find( + (symbol) => symbol.description === 'headers list' + ); + + assert(kHeadersListNode, 'Headers cannot be parsed'); + } + + const headersList = headers[kHeadersListNode]; + assert(headersList); + + return headersList + } + + util$4 = { + isCTLExcludingHtab, + stringify, + getHeadersList + }; + return util$4; + } + + var parse; + var hasRequiredParse; + + function requireParse () { + if (hasRequiredParse) return parse; + hasRequiredParse = 1; + + const { maxNameValuePairSize, maxAttributeValueSize } = requireConstants$1(); + const { isCTLExcludingHtab } = requireUtil$1(); + const { collectASequenceOfCodePointsFast } = requireDataURL(); + const assert = require$$3$1; + + /** + * @description Parses the field-value attributes of a set-cookie header string. + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} header + * @returns if the header is invalid, null will be returned + */ + function parseSetCookie (header) { + // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F + // character (CTL characters excluding HTAB): Abort these steps and + // ignore the set-cookie-string entirely. + if (isCTLExcludingHtab(header)) { + return null + } + + let nameValuePair = ''; + let unparsedAttributes = ''; + let name = ''; + let value = ''; + + // 2. If the set-cookie-string contains a %x3B (";") character: + if (header.includes(';')) { + // 1. The name-value-pair string consists of the characters up to, + // but not including, the first %x3B (";"), and the unparsed- + // attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question). + const position = { position: 0 }; + + nameValuePair = collectASequenceOfCodePointsFast(';', header, position); + unparsedAttributes = header.slice(position.position); + } else { + // Otherwise: + + // 1. The name-value-pair string consists of all the characters + // contained in the set-cookie-string, and the unparsed- + // attributes is the empty string. + nameValuePair = header; + } + + // 3. If the name-value-pair string lacks a %x3D ("=") character, then + // the name string is empty, and the value string is the value of + // name-value-pair. + if (!nameValuePair.includes('=')) { + value = nameValuePair; + } else { + // Otherwise, the name string consists of the characters up to, but + // not including, the first %x3D ("=") character, and the (possibly + // empty) value string consists of the characters after the first + // %x3D ("=") character. + const position = { position: 0 }; + name = collectASequenceOfCodePointsFast( + '=', + nameValuePair, + position + ); + value = nameValuePair.slice(position.position + 1); + } + + // 4. Remove any leading or trailing WSP characters from the name + // string and the value string. + name = name.trim(); + value = value.trim(); + + // 5. If the sum of the lengths of the name string and the value string + // is more than 4096 octets, abort these steps and ignore the set- + // cookie-string entirely. + if (name.length + value.length > maxNameValuePairSize) { + return null + } + + // 6. The cookie-name is the name string, and the cookie-value is the + // value string. + return { + name, value, ...parseUnparsedAttributes(unparsedAttributes) + } + } + + /** + * Parses the remaining attributes of a set-cookie header + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} unparsedAttributes + * @param {[Object.]={}} cookieAttributeList + */ + function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { + // 1. If the unparsed-attributes string is empty, skip the rest of + // these steps. + if (unparsedAttributes.length === 0) { + return cookieAttributeList + } + + // 2. Discard the first character of the unparsed-attributes (which + // will be a %x3B (";") character). + assert(unparsedAttributes[0] === ';'); + unparsedAttributes = unparsedAttributes.slice(1); + + let cookieAv = ''; + + // 3. If the remaining unparsed-attributes contains a %x3B (";") + // character: + if (unparsedAttributes.includes(';')) { + // 1. Consume the characters of the unparsed-attributes up to, but + // not including, the first %x3B (";") character. + cookieAv = collectASequenceOfCodePointsFast( + ';', + unparsedAttributes, + { position: 0 } + ); + unparsedAttributes = unparsedAttributes.slice(cookieAv.length); + } else { + // Otherwise: + + // 1. Consume the remainder of the unparsed-attributes. + cookieAv = unparsedAttributes; + unparsedAttributes = ''; + } + + // Let the cookie-av string be the characters consumed in this step. + + let attributeName = ''; + let attributeValue = ''; + + // 4. If the cookie-av string contains a %x3D ("=") character: + if (cookieAv.includes('=')) { + // 1. The (possibly empty) attribute-name string consists of the + // characters up to, but not including, the first %x3D ("=") + // character, and the (possibly empty) attribute-value string + // consists of the characters after the first %x3D ("=") + // character. + const position = { position: 0 }; + + attributeName = collectASequenceOfCodePointsFast( + '=', + cookieAv, + position + ); + attributeValue = cookieAv.slice(position.position + 1); + } else { + // Otherwise: + + // 1. The attribute-name string consists of the entire cookie-av + // string, and the attribute-value string is empty. + attributeName = cookieAv; + } + + // 5. Remove any leading or trailing WSP characters from the attribute- + // name string and the attribute-value string. + attributeName = attributeName.trim(); + attributeValue = attributeValue.trim(); + + // 6. If the attribute-value is longer than 1024 octets, ignore the + // cookie-av string and return to Step 1 of this algorithm. + if (attributeValue.length > maxAttributeValueSize) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 7. Process the attribute-name and attribute-value according to the + // requirements in the following subsections. (Notice that + // attributes with unrecognized attribute-names are ignored.) + const attributeNameLowercase = attributeName.toLowerCase(); + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 + // If the attribute-name case-insensitively matches the string + // "Expires", the user agent MUST process the cookie-av as follows. + if (attributeNameLowercase === 'expires') { + // 1. Let the expiry-time be the result of parsing the attribute-value + // as cookie-date (see Section 5.1.1). + const expiryTime = new Date(attributeValue); + + // 2. If the attribute-value failed to parse as a cookie date, ignore + // the cookie-av. + + cookieAttributeList.expires = expiryTime; + } else if (attributeNameLowercase === 'max-age') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 + // If the attribute-name case-insensitively matches the string "Max- + // Age", the user agent MUST process the cookie-av as follows. + + // 1. If the first character of the attribute-value is not a DIGIT or a + // "-" character, ignore the cookie-av. + const charCode = attributeValue.charCodeAt(0); + + if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 2. If the remainder of attribute-value contains a non-DIGIT + // character, ignore the cookie-av. + if (!/^\d+$/.test(attributeValue)) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 3. Let delta-seconds be the attribute-value converted to an integer. + const deltaSeconds = Number(attributeValue); + + // 4. Let cookie-age-limit be the maximum age of the cookie (which + // SHOULD be 400 days or less, see Section 4.1.2.2). + + // 5. Set delta-seconds to the smaller of its present value and cookie- + // age-limit. + // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) + + // 6. If delta-seconds is less than or equal to zero (0), let expiry- + // time be the earliest representable date and time. Otherwise, let + // the expiry-time be the current date and time plus delta-seconds + // seconds. + // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds + + // 7. Append an attribute to the cookie-attribute-list with an + // attribute-name of Max-Age and an attribute-value of expiry-time. + cookieAttributeList.maxAge = deltaSeconds; + } else if (attributeNameLowercase === 'domain') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 + // If the attribute-name case-insensitively matches the string "Domain", + // the user agent MUST process the cookie-av as follows. + + // 1. Let cookie-domain be the attribute-value. + let cookieDomain = attributeValue; + + // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be + // cookie-domain without its leading %x2E ("."). + if (cookieDomain[0] === '.') { + cookieDomain = cookieDomain.slice(1); + } + + // 3. Convert the cookie-domain to lower case. + cookieDomain = cookieDomain.toLowerCase(); + + // 4. Append an attribute to the cookie-attribute-list with an + // attribute-name of Domain and an attribute-value of cookie-domain. + cookieAttributeList.domain = cookieDomain; + } else if (attributeNameLowercase === 'path') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 + // If the attribute-name case-insensitively matches the string "Path", + // the user agent MUST process the cookie-av as follows. + + // 1. If the attribute-value is empty or if the first character of the + // attribute-value is not %x2F ("/"): + let cookiePath = ''; + if (attributeValue.length === 0 || attributeValue[0] !== '/') { + // 1. Let cookie-path be the default-path. + cookiePath = '/'; + } else { + // Otherwise: + + // 1. Let cookie-path be the attribute-value. + cookiePath = attributeValue; + } + + // 2. Append an attribute to the cookie-attribute-list with an + // attribute-name of Path and an attribute-value of cookie-path. + cookieAttributeList.path = cookiePath; + } else if (attributeNameLowercase === 'secure') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 + // If the attribute-name case-insensitively matches the string "Secure", + // the user agent MUST append an attribute to the cookie-attribute-list + // with an attribute-name of Secure and an empty attribute-value. + + cookieAttributeList.secure = true; + } else if (attributeNameLowercase === 'httponly') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 + // If the attribute-name case-insensitively matches the string + // "HttpOnly", the user agent MUST append an attribute to the cookie- + // attribute-list with an attribute-name of HttpOnly and an empty + // attribute-value. + + cookieAttributeList.httpOnly = true; + } else if (attributeNameLowercase === 'samesite') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 + // If the attribute-name case-insensitively matches the string + // "SameSite", the user agent MUST process the cookie-av as follows: + + // 1. Let enforcement be "Default". + let enforcement = 'Default'; + + const attributeValueLowercase = attributeValue.toLowerCase(); + // 2. If cookie-av's attribute-value is a case-insensitive match for + // "None", set enforcement to "None". + if (attributeValueLowercase.includes('none')) { + enforcement = 'None'; + } + + // 3. If cookie-av's attribute-value is a case-insensitive match for + // "Strict", set enforcement to "Strict". + if (attributeValueLowercase.includes('strict')) { + enforcement = 'Strict'; + } + + // 4. If cookie-av's attribute-value is a case-insensitive match for + // "Lax", set enforcement to "Lax". + if (attributeValueLowercase.includes('lax')) { + enforcement = 'Lax'; + } + + // 5. Append an attribute to the cookie-attribute-list with an + // attribute-name of "SameSite" and an attribute-value of + // enforcement. + cookieAttributeList.sameSite = enforcement; + } else { + cookieAttributeList.unparsed ??= []; + + cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`); + } + + // 8. Return to Step 1 of this algorithm. + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + parse = { + parseSetCookie, + parseUnparsedAttributes + }; + return parse; + } + + var cookies; + var hasRequiredCookies; + + function requireCookies () { + if (hasRequiredCookies) return cookies; + hasRequiredCookies = 1; + + const { parseSetCookie } = requireParse(); + const { stringify, getHeadersList } = requireUtil$1(); + const { webidl } = requireWebidl(); + const { Headers } = requireHeaders(); + + /** + * @typedef {Object} Cookie + * @property {string} name + * @property {string} value + * @property {Date|number|undefined} expires + * @property {number|undefined} maxAge + * @property {string|undefined} domain + * @property {string|undefined} path + * @property {boolean|undefined} secure + * @property {boolean|undefined} httpOnly + * @property {'Strict'|'Lax'|'None'} sameSite + * @property {string[]} unparsed + */ + + /** + * @param {Headers} headers + * @returns {Record} + */ + function getCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }); + + webidl.brandCheck(headers, Headers, { strict: false }); + + const cookie = headers.get('cookie'); + const out = {}; + + if (!cookie) { + return out + } + + for (const piece of cookie.split(';')) { + const [name, ...value] = piece.split('='); + + out[name.trim()] = value.join('='); + } + + return out + } + + /** + * @param {Headers} headers + * @param {string} name + * @param {{ path?: string, domain?: string }|undefined} attributes + * @returns {void} + */ + function deleteCookie (headers, name, attributes) { + webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' }); + + webidl.brandCheck(headers, Headers, { strict: false }); + + name = webidl.converters.DOMString(name); + attributes = webidl.converters.DeleteCookieAttributes(attributes); + + // Matches behavior of + // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 + setCookie(headers, { + name, + value: '', + expires: new Date(0), + ...attributes + }); + } + + /** + * @param {Headers} headers + * @returns {Cookie[]} + */ + function getSetCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }); + + webidl.brandCheck(headers, Headers, { strict: false }); + + const cookies = getHeadersList(headers).cookies; + + if (!cookies) { + return [] + } + + // In older versions of undici, cookies is a list of name:value. + return cookies.map((pair) => parseSetCookie(Array.isArray(pair) ? pair[1] : pair)) + } + + /** + * @param {Headers} headers + * @param {Cookie} cookie + * @returns {void} + */ + function setCookie (headers, cookie) { + webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }); + + webidl.brandCheck(headers, Headers, { strict: false }); + + cookie = webidl.converters.Cookie(cookie); + + const str = stringify(cookie); + + if (str) { + headers.append('Set-Cookie', stringify(cookie)); + } + } + + webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: null + } + ]); + + webidl.converters.Cookie = webidl.dictionaryConverter([ + { + converter: webidl.converters.DOMString, + key: 'name' + }, + { + converter: webidl.converters.DOMString, + key: 'value' + }, + { + converter: webidl.nullableConverter((value) => { + if (typeof value === 'number') { + return webidl.converters['unsigned long long'](value) + } + + return new Date(value) + }), + key: 'expires', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters['long long']), + key: 'maxAge', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'secure', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'httpOnly', + defaultValue: null + }, + { + converter: webidl.converters.USVString, + key: 'sameSite', + allowedValues: ['Strict', 'Lax', 'None'] + }, + { + converter: webidl.sequenceConverter(webidl.converters.DOMString), + key: 'unparsed', + defaultValue: [] + } + ]); + + cookies = { + getCookies, + deleteCookie, + getSetCookies, + setCookie + }; + return cookies; + } + + var constants; + var hasRequiredConstants; + + function requireConstants () { + if (hasRequiredConstants) return constants; + hasRequiredConstants = 1; + + // This is a Globally Unique Identifier unique used + // to validate that the endpoint accepts websocket + // connections. + // See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 + const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'; + + /** @type {PropertyDescriptor} */ + const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false + }; + + const states = { + CONNECTING: 0, + OPEN: 1, + CLOSING: 2, + CLOSED: 3 + }; + + const opcodes = { + CONTINUATION: 0x0, + TEXT: 0x1, + BINARY: 0x2, + CLOSE: 0x8, + PING: 0x9, + PONG: 0xA + }; + + const maxUnsigned16Bit = 2 ** 16 - 1; // 65535 + + const parserStates = { + INFO: 0, + PAYLOADLENGTH_16: 2, + PAYLOADLENGTH_64: 3, + READ_DATA: 4 + }; + + const emptyBuffer = Buffer.allocUnsafe(0); + + constants = { + uid, + staticPropertyDescriptors, + states, + opcodes, + maxUnsigned16Bit, + parserStates, + emptyBuffer + }; + return constants; + } + + var symbols; + var hasRequiredSymbols; + + function requireSymbols () { + if (hasRequiredSymbols) return symbols; + hasRequiredSymbols = 1; + + symbols = { + kWebSocketURL: Symbol('url'), + kReadyState: Symbol('ready state'), + kController: Symbol('controller'), + kResponse: Symbol('response'), + kBinaryType: Symbol('binary type'), + kSentClose: Symbol('sent close'), + kReceivedClose: Symbol('received close'), + kByteParser: Symbol('byte parser') + }; + return symbols; + } + + var events; + var hasRequiredEvents; + + function requireEvents () { + if (hasRequiredEvents) return events; + hasRequiredEvents = 1; + + const { webidl } = requireWebidl(); + const { kEnumerableProperty } = util$l; + const { MessagePort } = require$$2$1; + + /** + * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent + */ + class MessageEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' }); + + type = webidl.converters.DOMString(type); + eventInitDict = webidl.converters.MessageEventInit(eventInitDict); + + super(type, eventInitDict); + + this.#eventInit = eventInitDict; + } + + get data () { + webidl.brandCheck(this, MessageEvent); + + return this.#eventInit.data + } + + get origin () { + webidl.brandCheck(this, MessageEvent); + + return this.#eventInit.origin + } + + get lastEventId () { + webidl.brandCheck(this, MessageEvent); + + return this.#eventInit.lastEventId + } + + get source () { + webidl.brandCheck(this, MessageEvent); + + return this.#eventInit.source + } + + get ports () { + webidl.brandCheck(this, MessageEvent); + + if (!Object.isFrozen(this.#eventInit.ports)) { + Object.freeze(this.#eventInit.ports); + } + + return this.#eventInit.ports + } + + initMessageEvent ( + type, + bubbles = false, + cancelable = false, + data = null, + origin = '', + lastEventId = '', + source = null, + ports = [] + ) { + webidl.brandCheck(this, MessageEvent); + + webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' }); + + return new MessageEvent(type, { + bubbles, cancelable, data, origin, lastEventId, source, ports + }) + } + } + + /** + * @see https://websockets.spec.whatwg.org/#the-closeevent-interface + */ + class CloseEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' }); + + type = webidl.converters.DOMString(type); + eventInitDict = webidl.converters.CloseEventInit(eventInitDict); + + super(type, eventInitDict); + + this.#eventInit = eventInitDict; + } + + get wasClean () { + webidl.brandCheck(this, CloseEvent); + + return this.#eventInit.wasClean + } + + get code () { + webidl.brandCheck(this, CloseEvent); + + return this.#eventInit.code + } + + get reason () { + webidl.brandCheck(this, CloseEvent); + + return this.#eventInit.reason + } + } - // Don't use 'blue' not visible on cmd.exe - inspect.styles = { - 'special': 'cyan', - 'number': 'yellow', - 'boolean': 'yellow', - 'undefined': 'grey', - 'null': 'bold', - 'string': 'green', - 'date': 'magenta', - // "name": intentionally not styling - 'regexp': 'red' - }; + // https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface + class ErrorEvent extends Event { + #eventInit + constructor (type, eventInitDict) { + webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' }); - function stylizeWithColor(str, styleType) { - var style = inspect.styles[styleType]; + super(type, eventInitDict); - if (style) { - return '\u001b[' + inspect.colors[style][0] + 'm' + str + - '\u001b[' + inspect.colors[style][1] + 'm'; - } else { - return str; - } - } + type = webidl.converters.DOMString(type); + eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}); + this.#eventInit = eventInitDict; + } - function stylizeNoColor(str, styleType) { - return str; - } + get message () { + webidl.brandCheck(this, ErrorEvent); + return this.#eventInit.message + } - function arrayToHash(array) { - var hash = {}; + get filename () { + webidl.brandCheck(this, ErrorEvent); - array.forEach(function(val, idx) { - hash[val] = true; - }); + return this.#eventInit.filename + } - return hash; - } + get lineno () { + webidl.brandCheck(this, ErrorEvent); + return this.#eventInit.lineno + } - function formatValue(ctx, value, recurseTimes) { - // Provide a hook for user-specified inspect functions. - // Check that value is an object with an inspect function on it - if (ctx.customInspect && - value && - isFunction(value.inspect) && - // Filter out the util module, it's inspect function is special - value.inspect !== inspect && - // Also filter out any prototype objects using the circular check. - !(value.constructor && value.constructor.prototype === value)) { - var ret = value.inspect(recurseTimes, ctx); - if (!isString(ret)) { - ret = formatValue(ctx, ret, recurseTimes); - } - return ret; - } + get colno () { + webidl.brandCheck(this, ErrorEvent); - // Primitive types cannot have properties - var primitive = formatPrimitive(ctx, value); - if (primitive) { - return primitive; - } + return this.#eventInit.colno + } - // Look up the keys of the object. - var keys = Object.keys(value); - var visibleKeys = arrayToHash(keys); + get error () { + webidl.brandCheck(this, ErrorEvent); - if (ctx.showHidden) { - keys = Object.getOwnPropertyNames(value); - } + return this.#eventInit.error + } + } - // IE doesn't make error fields non-enumerable - // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx - if (isError(value) - && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { - return formatError(value); - } + Object.defineProperties(MessageEvent.prototype, { + [Symbol.toStringTag]: { + value: 'MessageEvent', + configurable: true + }, + data: kEnumerableProperty, + origin: kEnumerableProperty, + lastEventId: kEnumerableProperty, + source: kEnumerableProperty, + ports: kEnumerableProperty, + initMessageEvent: kEnumerableProperty + }); - // Some type of object without properties can be shortcutted. - if (keys.length === 0) { - if (isFunction(value)) { - var name = value.name ? ': ' + value.name : ''; - return ctx.stylize('[Function' + name + ']', 'special'); - } - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } - if (isDate(value)) { - return ctx.stylize(Date.prototype.toString.call(value), 'date'); - } - if (isError(value)) { - return formatError(value); - } - } + Object.defineProperties(CloseEvent.prototype, { + [Symbol.toStringTag]: { + value: 'CloseEvent', + configurable: true + }, + reason: kEnumerableProperty, + code: kEnumerableProperty, + wasClean: kEnumerableProperty + }); - var base = '', array = false, braces = ['{', '}']; + Object.defineProperties(ErrorEvent.prototype, { + [Symbol.toStringTag]: { + value: 'ErrorEvent', + configurable: true + }, + message: kEnumerableProperty, + filename: kEnumerableProperty, + lineno: kEnumerableProperty, + colno: kEnumerableProperty, + error: kEnumerableProperty + }); - // Make Array say that they are Array - if (isArray$1(value)) { - array = true; - braces = ['[', ']']; - } + webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort); + + webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.MessagePort + ); + + const eventInit = [ + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: false + } + ]; + + webidl.converters.MessageEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'data', + converter: webidl.converters.any, + defaultValue: null + }, + { + key: 'origin', + converter: webidl.converters.USVString, + defaultValue: '' + }, + { + key: 'lastEventId', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'source', + // Node doesn't implement WindowProxy or ServiceWorker, so the only + // valid value for source is a MessagePort. + converter: webidl.nullableConverter(webidl.converters.MessagePort), + defaultValue: null + }, + { + key: 'ports', + converter: webidl.converters['sequence'], + get defaultValue () { + return [] + } + } + ]); + + webidl.converters.CloseEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'wasClean', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'code', + converter: webidl.converters['unsigned short'], + defaultValue: 0 + }, + { + key: 'reason', + converter: webidl.converters.USVString, + defaultValue: '' + } + ]); + + webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'message', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'filename', + converter: webidl.converters.USVString, + defaultValue: '' + }, + { + key: 'lineno', + converter: webidl.converters['unsigned long'], + defaultValue: 0 + }, + { + key: 'colno', + converter: webidl.converters['unsigned long'], + defaultValue: 0 + }, + { + key: 'error', + converter: webidl.converters.any + } + ]); + + events = { + MessageEvent, + CloseEvent, + ErrorEvent + }; + return events; + } - // Make functions say that they are functions - if (isFunction(value)) { - var n = value.name ? ': ' + value.name : ''; - base = ' [Function' + n + ']'; - } + var util$3; + var hasRequiredUtil; - // Make RegExps say that they are RegExps - if (isRegExp(value)) { - base = ' ' + RegExp.prototype.toString.call(value); - } + function requireUtil () { + if (hasRequiredUtil) return util$3; + hasRequiredUtil = 1; - // Make dates with properties first say the date - if (isDate(value)) { - base = ' ' + Date.prototype.toUTCString.call(value); - } + const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = requireSymbols(); + const { states, opcodes } = requireConstants(); + const { MessageEvent, ErrorEvent } = requireEvents(); - // Make error with message first say the error - if (isError(value)) { - base = ' ' + formatError(value); - } + /* globals Blob */ - if (keys.length === 0 && (!array || value.length == 0)) { - return braces[0] + base + braces[1]; - } + /** + * @param {import('./websocket').WebSocket} ws + */ + function isEstablished (ws) { + // If the server's response is validated as provided for above, it is + // said that _The WebSocket Connection is Established_ and that the + // WebSocket Connection is in the OPEN state. + return ws[kReadyState] === states.OPEN + } - if (recurseTimes < 0) { - if (isRegExp(value)) { - return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); - } else { - return ctx.stylize('[Object]', 'special'); - } - } + /** + * @param {import('./websocket').WebSocket} ws + */ + function isClosing (ws) { + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + return ws[kReadyState] === states.CLOSING + } - ctx.seen.push(value); + /** + * @param {import('./websocket').WebSocket} ws + */ + function isClosed (ws) { + return ws[kReadyState] === states.CLOSED + } - var output; - if (array) { - output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); - } else { - output = keys.map(function(key) { - return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); - }); - } + /** + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e + * @param {EventTarget} target + * @param {EventInit | undefined} eventInitDict + */ + function fireEvent (e, target, eventConstructor = Event, eventInitDict) { + // 1. If eventConstructor is not given, then let eventConstructor be Event. + + // 2. Let event be the result of creating an event given eventConstructor, + // in the relevant realm of target. + // 3. Initialize event’s type attribute to e. + const event = new eventConstructor(e, eventInitDict); // eslint-disable-line new-cap + + // 4. Initialize any other IDL attributes of event as described in the + // invocation of this algorithm. + + // 5. Return the result of dispatching event at target, with legacy target + // override flag set if set. + target.dispatchEvent(event); + } - ctx.seen.pop(); + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @param {import('./websocket').WebSocket} ws + * @param {number} type Opcode + * @param {Buffer} data application data + */ + function websocketMessageReceived (ws, type, data) { + // 1. If ready state is not OPEN (1), then return. + if (ws[kReadyState] !== states.OPEN) { + return + } + + // 2. Let dataForEvent be determined by switching on type and binary type: + let dataForEvent; + + if (type === opcodes.TEXT) { + // -> type indicates that the data is Text + // a new DOMString containing data + try { + dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data); + } catch { + failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.'); + return + } + } else if (type === opcodes.BINARY) { + if (ws[kBinaryType] === 'blob') { + // -> type indicates that the data is Binary and binary type is "blob" + // a new Blob object, created in the relevant Realm of the WebSocket + // object, that represents data as its raw data + dataForEvent = new Blob([data]); + } else { + // -> type indicates that the data is Binary and binary type is "arraybuffer" + // a new ArrayBuffer object, created in the relevant Realm of the + // WebSocket object, whose contents are data + dataForEvent = new Uint8Array(data).buffer; + } + } + + // 3. Fire an event named message at the WebSocket object, using MessageEvent, + // with the origin attribute initialized to the serialization of the WebSocket + // object’s url's origin, and the data attribute initialized to dataForEvent. + fireEvent('message', ws, MessageEvent, { + origin: ws[kWebSocketURL].origin, + data: dataForEvent + }); + } - return reduceToSingleString(output, base, braces); - } + /** + * @see https://datatracker.ietf.org/doc/html/rfc6455 + * @see https://datatracker.ietf.org/doc/html/rfc2616 + * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 + * @param {string} protocol + */ + function isValidSubprotocol (protocol) { + // If present, this value indicates one + // or more comma-separated subprotocol the client wishes to speak, + // ordered by preference. The elements that comprise this value + // MUST be non-empty strings with characters in the range U+0021 to + // U+007E not including separator characters as defined in + // [RFC2616] and MUST all be unique strings. + if (protocol.length === 0) { + return false + } + + for (const char of protocol) { + const code = char.charCodeAt(0); + + if ( + code < 0x21 || + code > 0x7E || + char === '(' || + char === ')' || + char === '<' || + char === '>' || + char === '@' || + char === ',' || + char === ';' || + char === ':' || + char === '\\' || + char === '"' || + char === '/' || + char === '[' || + char === ']' || + char === '?' || + char === '=' || + char === '{' || + char === '}' || + code === 32 || // SP + code === 9 // HT + ) { + return false + } + } + + return true + } + /** + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 + * @param {number} code + */ + function isValidStatusCode (code) { + if (code >= 1000 && code < 1015) { + return ( + code !== 1004 && // reserved + code !== 1005 && // "MUST NOT be set as a status code" + code !== 1006 // "MUST NOT be set as a status code" + ) + } + + return code >= 3000 && code <= 4999 + } - function formatPrimitive(ctx, value) { - if (isUndefined(value)) - return ctx.stylize('undefined', 'undefined'); - if (isString(value)) { - var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') - .replace(/'/g, "\\'") - .replace(/\\"/g, '"') + '\''; - return ctx.stylize(simple, 'string'); - } - if (isNumber(value)) - return ctx.stylize('' + value, 'number'); - if (isBoolean(value)) - return ctx.stylize('' + value, 'boolean'); - // For some reason typeof null is "object", so special case here. - if (isNull(value)) - return ctx.stylize('null', 'null'); - } + /** + * @param {import('./websocket').WebSocket} ws + * @param {string|undefined} reason + */ + function failWebsocketConnection (ws, reason) { + const { [kController]: controller, [kResponse]: response } = ws; + controller.abort(); - function formatError(value) { - return '[' + Error.prototype.toString.call(value) + ']'; - } + if (response?.socket && !response.socket.destroyed) { + response.socket.destroy(); + } + if (reason) { + fireEvent('error', ws, ErrorEvent, { + error: new Error(reason) + }); + } + } - function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { - var output = []; - for (var i = 0, l = value.length; i < l; ++i) { - if (hasOwnProperty(value, String(i))) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - String(i), true)); - } else { - output.push(''); - } - } - keys.forEach(function(key) { - if (!key.match(/^\d+$/)) { - output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, - key, true)); - } - }); - return output; + util$3 = { + isEstablished, + isClosing, + isClosed, + fireEvent, + isValidSubprotocol, + isValidStatusCode, + failWebsocketConnection, + websocketMessageReceived + }; + return util$3; } + var connection; + var hasRequiredConnection; + + function requireConnection () { + if (hasRequiredConnection) return connection; + hasRequiredConnection = 1; + + const diagnosticsChannel = require$$1$2; + const { uid, states } = requireConstants(); + const { + kReadyState, + kSentClose, + kByteParser, + kReceivedClose + } = requireSymbols(); + const { fireEvent, failWebsocketConnection } = requireUtil(); + const { CloseEvent } = requireEvents(); + const { makeRequest } = requireRequest(); + const { fetching } = requireFetch(); + const { Headers } = requireHeaders(); + const { getGlobalDispatcher } = global$1; + const { kHeadersList } = symbols$4; + + const channels = {}; + channels.open = diagnosticsChannel.channel('undici:websocket:open'); + channels.close = diagnosticsChannel.channel('undici:websocket:close'); + channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error'); + + /** @type {import('crypto')} */ + let crypto; + try { + crypto = require$$6$1; + } catch { - function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { - var name, str, desc; - desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; - if (desc.get) { - if (desc.set) { - str = ctx.stylize('[Getter/Setter]', 'special'); - } else { - str = ctx.stylize('[Getter]', 'special'); - } - } else { - if (desc.set) { - str = ctx.stylize('[Setter]', 'special'); - } - } - if (!hasOwnProperty(visibleKeys, key)) { - name = '[' + key + ']'; - } - if (!str) { - if (ctx.seen.indexOf(desc.value) < 0) { - if (isNull(recurseTimes)) { - str = formatValue(ctx, desc.value, null); - } else { - str = formatValue(ctx, desc.value, recurseTimes - 1); - } - if (str.indexOf('\n') > -1) { - if (array) { - str = str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n').substr(2); - } else { - str = '\n' + str.split('\n').map(function(line) { - return ' ' + line; - }).join('\n'); - } - } - } else { - str = ctx.stylize('[Circular]', 'special'); - } - } - if (isUndefined(name)) { - if (array && key.match(/^\d+$/)) { - return str; - } - name = JSON.stringify('' + key); - if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { - name = name.substr(1, name.length - 2); - name = ctx.stylize(name, 'name'); - } else { - name = name.replace(/'/g, "\\'") - .replace(/\\"/g, '"') - .replace(/(^"|"$)/g, "'"); - name = ctx.stylize(name, 'string'); - } - } + } - return name + ': ' + str; - } + /** + * @see https://websockets.spec.whatwg.org/#concept-websocket-establish + * @param {URL} url + * @param {string|string[]} protocols + * @param {import('./websocket').WebSocket} ws + * @param {(response: any) => void} onEstablish + * @param {Partial} options + */ + function establishWebSocketConnection (url, protocols, ws, onEstablish, options) { + // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s + // scheme is "ws", and to "https" otherwise. + const requestURL = url; + + requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'; + + // 2. Let request be a new request, whose URL is requestURL, client is client, + // service-workers mode is "none", referrer is "no-referrer", mode is + // "websocket", credentials mode is "include", cache mode is "no-store" , + // and redirect mode is "error". + const request = makeRequest({ + urlList: [requestURL], + serviceWorkers: 'none', + referrer: 'no-referrer', + mode: 'websocket', + credentials: 'include', + cache: 'no-store', + redirect: 'error' + }); + // Note: undici extension, allow setting custom headers. + if (options.headers) { + const headersList = new Headers(options.headers)[kHeadersList]; + + request.headersList = headersList; + } + + // 3. Append (`Upgrade`, `websocket`) to request’s header list. + // 4. Append (`Connection`, `Upgrade`) to request’s header list. + // Note: both of these are handled by undici currently. + // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 + + // 5. Let keyValue be a nonce consisting of a randomly selected + // 16-byte value that has been forgiving-base64-encoded and + // isomorphic encoded. + const keyValue = crypto.randomBytes(16).toString('base64'); + + // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s + // header list. + request.headersList.append('sec-websocket-key', keyValue); + + // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s + // header list. + request.headersList.append('sec-websocket-version', '13'); + + // 8. For each protocol in protocols, combine + // (`Sec-WebSocket-Protocol`, protocol) in request’s header + // list. + for (const protocol of protocols) { + request.headersList.append('sec-websocket-protocol', protocol); + } + + // 9. Let permessageDeflate be a user-agent defined + // "permessage-deflate" extension header value. + // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 + // TODO: enable once permessage-deflate is supported + const permessageDeflate = ''; // 'permessage-deflate; 15' + + // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to + // request’s header list. + // request.headersList.append('sec-websocket-extensions', permessageDeflate) + + // 11. Fetch request with useParallelQueue set to true, and + // processResponse given response being these steps: + const controller = fetching({ + request, + useParallelQueue: true, + dispatcher: options.dispatcher ?? getGlobalDispatcher(), + processResponse (response) { + // 1. If response is a network error or its status is not 101, + // fail the WebSocket connection. + if (response.type === 'error' || response.status !== 101) { + failWebsocketConnection(ws, 'Received network error or non-101 status code.'); + return + } + + // 2. If protocols is not the empty list and extracting header + // list values given `Sec-WebSocket-Protocol` and response’s + // header list results in null, failure, or the empty byte + // sequence, then fail the WebSocket connection. + if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Server did not respond with sent protocols.'); + return + } + + // 3. Follow the requirements stated step 2 to step 6, inclusive, + // of the last set of steps in section 4.1 of The WebSocket + // Protocol to validate response. This either results in fail + // the WebSocket connection or the WebSocket connection is + // established. + + // 2. If the response lacks an |Upgrade| header field or the |Upgrade| + // header field contains a value that is not an ASCII case- + // insensitive match for the value "websocket", the client MUST + // _Fail the WebSocket Connection_. + if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { + failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".'); + return + } + + // 3. If the response lacks a |Connection| header field or the + // |Connection| header field doesn't contain a token that is an + // ASCII case-insensitive match for the value "Upgrade", the client + // MUST _Fail the WebSocket Connection_. + if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { + failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".'); + return + } + + // 4. If the response lacks a |Sec-WebSocket-Accept| header field or + // the |Sec-WebSocket-Accept| contains a value other than the + // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- + // Key| (as a string, not base64-decoded) with the string "258EAFA5- + // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and + // trailing whitespace, the client MUST _Fail the WebSocket + // Connection_. + const secWSAccept = response.headersList.get('Sec-WebSocket-Accept'); + const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64'); + if (secWSAccept !== digest) { + failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.'); + return + } + + // 5. If the response includes a |Sec-WebSocket-Extensions| header + // field and this header field indicates the use of an extension + // that was not present in the client's handshake (the server has + // indicated an extension not requested by the client), the client + // MUST _Fail the WebSocket Connection_. (The parsing of this + // header field to determine which extensions are requested is + // discussed in Section 9.1.) + const secExtension = response.headersList.get('Sec-WebSocket-Extensions'); + + if (secExtension !== null && secExtension !== permessageDeflate) { + failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.'); + return + } + + // 6. If the response includes a |Sec-WebSocket-Protocol| header field + // and this header field indicates the use of a subprotocol that was + // not present in the client's handshake (the server has indicated a + // subprotocol not requested by the client), the client MUST _Fail + // the WebSocket Connection_. + const secProtocol = response.headersList.get('Sec-WebSocket-Protocol'); + + if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.'); + return + } + + response.socket.on('data', onSocketData); + response.socket.on('close', onSocketClose); + response.socket.on('error', onSocketError); + + if (channels.open.hasSubscribers) { + channels.open.publish({ + address: response.socket.address(), + protocol: secProtocol, + extensions: secExtension + }); + } + + onEstablish(response); + } + }); - function reduceToSingleString(output, base, braces) { - var length = output.reduce(function(prev, cur) { - if (cur.indexOf('\n') >= 0) ; - return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; - }, 0); + return controller + } - if (length > 60) { - return braces[0] + - (base === '' ? '' : base + '\n ') + - ' ' + - output.join(',\n ') + - ' ' + - braces[1]; - } + /** + * @param {Buffer} chunk + */ + function onSocketData (chunk) { + if (!this.ws[kByteParser].write(chunk)) { + this.pause(); + } + } - return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; - } + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 + */ + function onSocketClose () { + const { ws } = this; + + // If the TCP connection was closed after the + // WebSocket closing handshake was completed, the WebSocket connection + // is said to have been closed _cleanly_. + const wasClean = ws[kSentClose] && ws[kReceivedClose]; + + let code = 1005; + let reason = ''; + + const result = ws[kByteParser].closingInfo; + + if (result) { + code = result.code ?? 1005; + reason = result.reason; + } else if (!ws[kSentClose]) { + // If _The WebSocket + // Connection is Closed_ and no Close control frame was received by the + // endpoint (such as could occur if the underlying transport connection + // is lost), _The WebSocket Connection Close Code_ is considered to be + // 1006. + code = 1006; + } + + // 1. Change the ready state to CLOSED (3). + ws[kReadyState] = states.CLOSED; + + // 2. If the user agent was required to fail the WebSocket + // connection, or if the WebSocket connection was closed + // after being flagged as full, fire an event named error + // at the WebSocket object. + // TODO + + // 3. Fire an event named close at the WebSocket object, + // using CloseEvent, with the wasClean attribute + // initialized to true if the connection closed cleanly + // and false otherwise, the code attribute initialized to + // the WebSocket connection close code, and the reason + // attribute initialized to the result of applying UTF-8 + // decode without BOM to the WebSocket connection close + // reason. + fireEvent('close', ws, CloseEvent, { + wasClean, code, reason + }); + if (channels.close.hasSubscribers) { + channels.close.publish({ + websocket: ws, + code, + reason + }); + } + } - // NOTE: These type checking functions intentionally don't use `instanceof` - // because it is fragile and can be easily faked with `Object.create()`. - function isArray$1(ar) { - return Array.isArray(ar); - } + function onSocketError (error) { + const { ws } = this; - function isBoolean(arg) { - return typeof arg === 'boolean'; - } + ws[kReadyState] = states.CLOSING; - function isNull(arg) { - return arg === null; - } + if (channels.socketError.hasSubscribers) { + channels.socketError.publish(error); + } - function isNullOrUndefined$1(arg) { - return arg == null; - } + this.destroy(); + } - function isNumber(arg) { - return typeof arg === 'number'; + connection = { + establishWebSocketConnection + }; + return connection; } - function isString(arg) { - return typeof arg === 'string'; - } + var frame; + var hasRequiredFrame; - function isSymbol(arg) { - return typeof arg === 'symbol'; - } + function requireFrame () { + if (hasRequiredFrame) return frame; + hasRequiredFrame = 1; - function isUndefined(arg) { - return arg === void 0; - } + const { maxUnsigned16Bit } = requireConstants(); - function isRegExp(re) { - return isObject(re) && objectToString(re) === '[object RegExp]'; - } + /** @type {import('crypto')} */ + let crypto; + try { + crypto = require$$6$1; + } catch { - function isObject(arg) { - return typeof arg === 'object' && arg !== null; - } + } - function isDate(d) { - return isObject(d) && objectToString(d) === '[object Date]'; - } + class WebsocketFrameSend { + /** + * @param {Buffer|undefined} data + */ + constructor (data) { + this.frameData = data; + this.maskKey = crypto.randomBytes(4); + } + + createFrame (opcode) { + const bodyLength = this.frameData?.byteLength ?? 0; + + /** @type {number} */ + let payloadLength = bodyLength; // 0-125 + let offset = 6; + + if (bodyLength > maxUnsigned16Bit) { + offset += 8; // payload length is next 8 bytes + payloadLength = 127; + } else if (bodyLength > 125) { + offset += 2; // payload length is next 2 bytes + payloadLength = 126; + } + + const buffer = Buffer.allocUnsafe(bodyLength + offset); + + // Clear first 2 bytes, everything else is overwritten + buffer[0] = buffer[1] = 0; + buffer[0] |= 0x80; // FIN + buffer[0] = (buffer[0] & 0xF0) + opcode; // opcode + + /*! ws. MIT License. Einar Otto Stangvik */ + buffer[offset - 4] = this.maskKey[0]; + buffer[offset - 3] = this.maskKey[1]; + buffer[offset - 2] = this.maskKey[2]; + buffer[offset - 1] = this.maskKey[3]; + + buffer[1] = payloadLength; + + if (payloadLength === 126) { + buffer.writeUInt16BE(bodyLength, 2); + } else if (payloadLength === 127) { + // Clear extended payload length + buffer[2] = buffer[3] = 0; + buffer.writeUIntBE(bodyLength, 4, 6); + } + + buffer[1] |= 0x80; // MASK + + // mask body + for (let i = 0; i < bodyLength; i++) { + buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4]; + } + + return buffer + } + } - function isError(e) { - return isObject(e) && - (objectToString(e) === '[object Error]' || e instanceof Error); + frame = { + WebsocketFrameSend + }; + return frame; } - function isFunction(arg) { - return typeof arg === 'function'; - } + var receiver; + var hasRequiredReceiver; + + function requireReceiver () { + if (hasRequiredReceiver) return receiver; + hasRequiredReceiver = 1; + + const { Writable } = require$$0$1; + const diagnosticsChannel = require$$1$2; + const { parserStates, opcodes, states, emptyBuffer } = requireConstants(); + const { kReadyState, kSentClose, kResponse, kReceivedClose } = requireSymbols(); + const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = requireUtil(); + const { WebsocketFrameSend } = requireFrame(); + + // This code was influenced by ws released under the MIT license. + // Copyright (c) 2011 Einar Otto Stangvik + // Copyright (c) 2013 Arnout Kazemier and contributors + // Copyright (c) 2016 Luigi Pinca and contributors + + const channels = {}; + channels.ping = diagnosticsChannel.channel('undici:websocket:ping'); + channels.pong = diagnosticsChannel.channel('undici:websocket:pong'); + + class ByteParser extends Writable { + #buffers = [] + #byteOffset = 0 + + #state = parserStates.INFO + + #info = {} + #fragments = [] + + constructor (ws) { + super(); + + this.ws = ws; + } + + /** + * @param {Buffer} chunk + * @param {() => void} callback + */ + _write (chunk, _, callback) { + this.#buffers.push(chunk); + this.#byteOffset += chunk.length; + + this.run(callback); + } + + /** + * Runs whenever a new chunk is received. + * Callback is called whenever there are no more chunks buffering, + * or not enough bytes are buffered to parse. + */ + run (callback) { + while (true) { + if (this.#state === parserStates.INFO) { + // If there aren't enough bytes to parse the payload length, etc. + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2); + + this.#info.fin = (buffer[0] & 0x80) !== 0; + this.#info.opcode = buffer[0] & 0x0F; + + // If we receive a fragmented message, we use the type of the first + // frame to parse the full message as binary/text, when it's terminated + this.#info.originalOpcode ??= this.#info.opcode; + + this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION; + + if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) { + // Only text and binary frames can be fragmented + failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.'); + return + } + + const payloadLength = buffer[1] & 0x7F; + + if (payloadLength <= 125) { + this.#info.payloadLength = payloadLength; + this.#state = parserStates.READ_DATA; + } else if (payloadLength === 126) { + this.#state = parserStates.PAYLOADLENGTH_16; + } else if (payloadLength === 127) { + this.#state = parserStates.PAYLOADLENGTH_64; + } + + if (this.#info.fragmented && payloadLength > 125) { + // A fragmented frame can't be fragmented itself + failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.'); + return + } else if ( + (this.#info.opcode === opcodes.PING || + this.#info.opcode === opcodes.PONG || + this.#info.opcode === opcodes.CLOSE) && + payloadLength > 125 + ) { + // Control frames can have a payload length of 125 bytes MAX + failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.'); + return + } else if (this.#info.opcode === opcodes.CLOSE) { + if (payloadLength === 1) { + failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.'); + return + } + + const body = this.consume(payloadLength); + + this.#info.closeInfo = this.parseCloseBody(false, body); + + if (!this.ws[kSentClose]) { + // If an endpoint receives a Close frame and did not previously send a + // Close frame, the endpoint MUST send a Close frame in response. (When + // sending a Close frame in response, the endpoint typically echos the + // status code it received.) + const body = Buffer.allocUnsafe(2); + body.writeUInt16BE(this.#info.closeInfo.code, 0); + const closeFrame = new WebsocketFrameSend(body); + + this.ws[kResponse].socket.write( + closeFrame.createFrame(opcodes.CLOSE), + (err) => { + if (!err) { + this.ws[kSentClose] = true; + } + } + ); + } + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this.ws[kReadyState] = states.CLOSING; + this.ws[kReceivedClose] = true; + + this.end(); + + return + } else if (this.#info.opcode === opcodes.PING) { + // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in + // response, unless it already received a Close frame. + // A Pong frame sent in response to a Ping frame must have identical + // "Application data" + + const body = this.consume(payloadLength); + + if (!this.ws[kReceivedClose]) { + const frame = new WebsocketFrameSend(body); + + this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)); + + if (channels.ping.hasSubscribers) { + channels.ping.publish({ + payload: body + }); + } + } + + this.#state = parserStates.INFO; + + if (this.#byteOffset > 0) { + continue + } else { + callback(); + return + } + } else if (this.#info.opcode === opcodes.PONG) { + // A Pong frame MAY be sent unsolicited. This serves as a + // unidirectional heartbeat. A response to an unsolicited Pong frame is + // not expected. + + const body = this.consume(payloadLength); + + if (channels.pong.hasSubscribers) { + channels.pong.publish({ + payload: body + }); + } + + if (this.#byteOffset > 0) { + continue + } else { + callback(); + return + } + } + } else if (this.#state === parserStates.PAYLOADLENGTH_16) { + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2); + + this.#info.payloadLength = buffer.readUInt16BE(0); + this.#state = parserStates.READ_DATA; + } else if (this.#state === parserStates.PAYLOADLENGTH_64) { + if (this.#byteOffset < 8) { + return callback() + } + + const buffer = this.consume(8); + const upper = buffer.readUInt32BE(0); + + // 2^31 is the maxinimum bytes an arraybuffer can contain + // on 32-bit systems. Although, on 64-bit systems, this is + // 2^53-1 bytes. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e + if (upper > 2 ** 31 - 1) { + failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.'); + return + } + + const lower = buffer.readUInt32BE(4); + + this.#info.payloadLength = (upper << 8) + lower; + this.#state = parserStates.READ_DATA; + } else if (this.#state === parserStates.READ_DATA) { + if (this.#byteOffset < this.#info.payloadLength) { + // If there is still more data in this chunk that needs to be read + return callback() + } else if (this.#byteOffset >= this.#info.payloadLength) { + // If the server sent multiple frames in a single chunk + + const body = this.consume(this.#info.payloadLength); + + this.#fragments.push(body); + + // If the frame is unfragmented, or a fragmented frame was terminated, + // a message was received + if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) { + const fullMessage = Buffer.concat(this.#fragments); + + websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage); + + this.#info = {}; + this.#fragments.length = 0; + } + + this.#state = parserStates.INFO; + } + } + + if (this.#byteOffset > 0) { + continue + } else { + callback(); + break + } + } + } + + /** + * Take n bytes from the buffered Buffers + * @param {number} n + * @returns {Buffer|null} + */ + consume (n) { + if (n > this.#byteOffset) { + return null + } else if (n === 0) { + return emptyBuffer + } + + if (this.#buffers[0].length === n) { + this.#byteOffset -= this.#buffers[0].length; + return this.#buffers.shift() + } + + const buffer = Buffer.allocUnsafe(n); + let offset = 0; + + while (offset !== n) { + const next = this.#buffers[0]; + const { length } = next; + + if (length + offset === n) { + buffer.set(this.#buffers.shift(), offset); + break + } else if (length + offset > n) { + buffer.set(next.subarray(0, n - offset), offset); + this.#buffers[0] = next.subarray(n - offset); + break + } else { + buffer.set(this.#buffers.shift(), offset); + offset += next.length; + } + } + + this.#byteOffset -= n; + + return buffer + } + + parseCloseBody (onlyCode, data) { + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + /** @type {number|undefined} */ + let code; + + if (data.length >= 2) { + // _The WebSocket Connection Close Code_ is + // defined as the status code (Section 7.4) contained in the first Close + // control frame received by the application + code = data.readUInt16BE(0); + } + + if (onlyCode) { + if (!isValidStatusCode(code)) { + return null + } + + return { code } + } + + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + /** @type {Buffer} */ + let reason = data.subarray(2); + + // Remove BOM + if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { + reason = reason.subarray(3); + } + + if (code !== undefined && !isValidStatusCode(code)) { + return null + } + + try { + // TODO: optimize this + reason = new TextDecoder('utf-8', { fatal: true }).decode(reason); + } catch { + return null + } + + return { code, reason } + } + + get closingInfo () { + return this.#info.closeInfo + } + } - function isPrimitive(arg) { - return arg === null || - typeof arg === 'boolean' || - typeof arg === 'number' || - typeof arg === 'string' || - typeof arg === 'symbol' || // ES6 symbol - typeof arg === 'undefined'; + receiver = { + ByteParser + }; + return receiver; } - function isBuffer(maybeBuf) { - return Buffer$1.isBuffer(maybeBuf); - } + var websocket; + var hasRequiredWebsocket; + + function requireWebsocket () { + if (hasRequiredWebsocket) return websocket; + hasRequiredWebsocket = 1; + + const { webidl } = requireWebidl(); + const { DOMException } = requireConstants$3(); + const { URLSerializer } = requireDataURL(); + const { getGlobalOrigin } = requireGlobal(); + const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = requireConstants(); + const { + kWebSocketURL, + kReadyState, + kController, + kBinaryType, + kResponse, + kSentClose, + kByteParser + } = requireSymbols(); + const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = requireUtil(); + const { establishWebSocketConnection } = requireConnection(); + const { WebsocketFrameSend } = requireFrame(); + const { ByteParser } = requireReceiver(); + const { kEnumerableProperty, isBlobLike } = util$l; + const { getGlobalDispatcher } = global$1; + const { types } = require$$3$2; + + let experimentalWarned = false; + + // https://websockets.spec.whatwg.org/#interface-definition + class WebSocket extends EventTarget { + #events = { + open: null, + error: null, + close: null, + message: null + } + + #bufferedAmount = 0 + #protocol = '' + #extensions = '' + + /** + * @param {string} url + * @param {string|string[]} protocols + */ + constructor (url, protocols = []) { + super(); + + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' }); + + if (!experimentalWarned) { + experimentalWarned = true; + browser$1$1.emitWarning('WebSockets are experimental, expect them to change at any time.', { + code: 'UNDICI-WS' + }); + } + + const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols); + + url = webidl.converters.USVString(url); + protocols = options.protocols; + + // 1. Let baseURL be this's relevant settings object's API base URL. + const baseURL = getGlobalOrigin(); + + // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. + let urlRecord; + + try { + urlRecord = new URL(url, baseURL); + } catch (e) { + // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. + throw new DOMException(e, 'SyntaxError') + } + + // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws". + if (urlRecord.protocol === 'http:') { + urlRecord.protocol = 'ws:'; + } else if (urlRecord.protocol === 'https:') { + // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss". + urlRecord.protocol = 'wss:'; + } + + // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException. + if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { + throw new DOMException( + `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, + 'SyntaxError' + ) + } + + // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" + // DOMException. + if (urlRecord.hash || urlRecord.href.endsWith('#')) { + throw new DOMException('Got fragment', 'SyntaxError') + } + + // 8. If protocols is a string, set protocols to a sequence consisting + // of just that string. + if (typeof protocols === 'string') { + protocols = [protocols]; + } + + // 9. If any of the values in protocols occur more than once or otherwise + // fail to match the requirements for elements that comprise the value + // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket + // protocol, then throw a "SyntaxError" DOMException. + if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + // 10. Set this's url to urlRecord. + this[kWebSocketURL] = new URL(urlRecord.href); + + // 11. Let client be this's relevant settings object. + + // 12. Run this step in parallel: + + // 1. Establish a WebSocket connection given urlRecord, protocols, + // and client. + this[kController] = establishWebSocketConnection( + urlRecord, + protocols, + this, + (response) => this.#onConnectionEstablished(response), + options + ); + + // Each WebSocket object has an associated ready state, which is a + // number representing the state of the connection. Initially it must + // be CONNECTING (0). + this[kReadyState] = WebSocket.CONNECTING; + + // The extensions attribute must initially return the empty string. + + // The protocol attribute must initially return the empty string. + + // Each WebSocket object has an associated binary type, which is a + // BinaryType. Initially it must be "blob". + this[kBinaryType] = 'blob'; + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-close + * @param {number|undefined} code + * @param {string|undefined} reason + */ + close (code = undefined, reason = undefined) { + webidl.brandCheck(this, WebSocket); + + if (code !== undefined) { + code = webidl.converters['unsigned short'](code, { clamp: true }); + } + + if (reason !== undefined) { + reason = webidl.converters.USVString(reason); + } + + // 1. If code is present, but is neither an integer equal to 1000 nor an + // integer in the range 3000 to 4999, inclusive, throw an + // "InvalidAccessError" DOMException. + if (code !== undefined) { + if (code !== 1000 && (code < 3000 || code > 4999)) { + throw new DOMException('invalid code', 'InvalidAccessError') + } + } + + let reasonByteLength = 0; + + // 2. If reason is present, then run these substeps: + if (reason !== undefined) { + // 1. Let reasonBytes be the result of encoding reason. + // 2. If reasonBytes is longer than 123 bytes, then throw a + // "SyntaxError" DOMException. + reasonByteLength = Buffer.byteLength(reason); + + if (reasonByteLength > 123) { + throw new DOMException( + `Reason must be less than 123 bytes; received ${reasonByteLength}`, + 'SyntaxError' + ) + } + } + + // 3. Run the first matching steps from the following list: + if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) ; else if (!isEstablished(this)) { + // If the WebSocket connection is not yet established + // Fail the WebSocket connection and set this's ready state + // to CLOSING (2). + failWebsocketConnection(this, 'Connection was closed before it was established.'); + this[kReadyState] = WebSocket.CLOSING; + } else if (!isClosing(this)) { + // If the WebSocket closing handshake has not yet been started + // Start the WebSocket closing handshake and set this's ready + // state to CLOSING (2). + // - If neither code nor reason is present, the WebSocket Close + // message must not have a body. + // - If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + // - If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + + const frame = new WebsocketFrameSend(); + + // If neither code nor reason is present, the WebSocket Close + // message must not have a body. + + // If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + if (code !== undefined && reason === undefined) { + frame.frameData = Buffer.allocUnsafe(2); + frame.frameData.writeUInt16BE(code, 0); + } else if (code !== undefined && reason !== undefined) { + // If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength); + frame.frameData.writeUInt16BE(code, 0); + // the body MAY contain UTF-8-encoded data with value /reason/ + frame.frameData.write(reason, 2, 'utf-8'); + } else { + frame.frameData = emptyBuffer; + } + + /** @type {import('stream').Duplex} */ + const socket = this[kResponse].socket; + + socket.write(frame.createFrame(opcodes.CLOSE), (err) => { + if (!err) { + this[kSentClose] = true; + } + }); + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this[kReadyState] = states.CLOSING; + } else { + // Otherwise + // Set this's ready state to CLOSING (2). + this[kReadyState] = WebSocket.CLOSING; + } + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-send + * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data + */ + send (data) { + webidl.brandCheck(this, WebSocket); + + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' }); + + data = webidl.converters.WebSocketSendData(data); + + // 1. If this's ready state is CONNECTING, then throw an + // "InvalidStateError" DOMException. + if (this[kReadyState] === WebSocket.CONNECTING) { + throw new DOMException('Sent before connected.', 'InvalidStateError') + } + + // 2. Run the appropriate set of steps from the following list: + // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 + // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + + if (!isEstablished(this) || isClosing(this)) { + return + } + + /** @type {import('stream').Duplex} */ + const socket = this[kResponse].socket; + + // If data is a string + if (typeof data === 'string') { + // If the WebSocket connection is established and the WebSocket + // closing handshake has not yet started, then the user agent + // must send a WebSocket Message comprised of the data argument + // using a text frame opcode; if the data cannot be sent, e.g. + // because it would need to be buffered but the buffer is full, + // the user agent must flag the WebSocket as full and then close + // the WebSocket connection. Any invocation of this method with a + // string argument that does not throw an exception must increase + // the bufferedAmount attribute by the number of bytes needed to + // express the argument as UTF-8. + + const value = Buffer.from(data); + const frame = new WebsocketFrameSend(value); + const buffer = frame.createFrame(opcodes.TEXT); + + this.#bufferedAmount += value.byteLength; + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength; + }); + } else if (types.isArrayBuffer(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need + // to be buffered but the buffer is full, the user agent must flag + // the WebSocket as full and then close the WebSocket connection. + // The data to be sent is the data stored in the buffer described + // by the ArrayBuffer object. Any invocation of this method with an + // ArrayBuffer argument that does not throw an exception must + // increase the bufferedAmount attribute by the length of the + // ArrayBuffer in bytes. + + const value = Buffer.from(data); + const frame = new WebsocketFrameSend(value); + const buffer = frame.createFrame(opcodes.BINARY); + + this.#bufferedAmount += value.byteLength; + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength; + }); + } else if (ArrayBuffer.isView(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The + // data to be sent is the data stored in the section of the buffer + // described by the ArrayBuffer object that data references. Any + // invocation of this method with this kind of argument that does + // not throw an exception must increase the bufferedAmount attribute + // by the length of data’s buffer in bytes. + + const ab = Buffer.from(data, data.byteOffset, data.byteLength); + + const frame = new WebsocketFrameSend(ab); + const buffer = frame.createFrame(opcodes.BINARY); + + this.#bufferedAmount += ab.byteLength; + socket.write(buffer, () => { + this.#bufferedAmount -= ab.byteLength; + }); + } else if (isBlobLike(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The data + // to be sent is the raw data represented by the Blob object. Any + // invocation of this method with a Blob argument that does not throw + // an exception must increase the bufferedAmount attribute by the size + // of the Blob object’s raw data, in bytes. + + const frame = new WebsocketFrameSend(); + + data.arrayBuffer().then((ab) => { + const value = Buffer.from(ab); + frame.frameData = value; + const buffer = frame.createFrame(opcodes.BINARY); + + this.#bufferedAmount += value.byteLength; + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength; + }); + }); + } + } + + get readyState () { + webidl.brandCheck(this, WebSocket); + + // The readyState getter steps are to return this's ready state. + return this[kReadyState] + } + + get bufferedAmount () { + webidl.brandCheck(this, WebSocket); + + return this.#bufferedAmount + } + + get url () { + webidl.brandCheck(this, WebSocket); + + // The url getter steps are to return this's url, serialized. + return URLSerializer(this[kWebSocketURL]) + } + + get extensions () { + webidl.brandCheck(this, WebSocket); + + return this.#extensions + } + + get protocol () { + webidl.brandCheck(this, WebSocket); + + return this.#protocol + } + + get onopen () { + webidl.brandCheck(this, WebSocket); + + return this.#events.open + } + + set onopen (fn) { + webidl.brandCheck(this, WebSocket); + + if (this.#events.open) { + this.removeEventListener('open', this.#events.open); + } + + if (typeof fn === 'function') { + this.#events.open = fn; + this.addEventListener('open', fn); + } else { + this.#events.open = null; + } + } + + get onerror () { + webidl.brandCheck(this, WebSocket); + + return this.#events.error + } + + set onerror (fn) { + webidl.brandCheck(this, WebSocket); + + if (this.#events.error) { + this.removeEventListener('error', this.#events.error); + } + + if (typeof fn === 'function') { + this.#events.error = fn; + this.addEventListener('error', fn); + } else { + this.#events.error = null; + } + } + + get onclose () { + webidl.brandCheck(this, WebSocket); + + return this.#events.close + } + + set onclose (fn) { + webidl.brandCheck(this, WebSocket); + + if (this.#events.close) { + this.removeEventListener('close', this.#events.close); + } + + if (typeof fn === 'function') { + this.#events.close = fn; + this.addEventListener('close', fn); + } else { + this.#events.close = null; + } + } + + get onmessage () { + webidl.brandCheck(this, WebSocket); - function objectToString(o) { - return Object.prototype.toString.call(o); - } + return this.#events.message + } + + set onmessage (fn) { + webidl.brandCheck(this, WebSocket); + + if (this.#events.message) { + this.removeEventListener('message', this.#events.message); + } + + if (typeof fn === 'function') { + this.#events.message = fn; + this.addEventListener('message', fn); + } else { + this.#events.message = null; + } + } + + get binaryType () { + webidl.brandCheck(this, WebSocket); + + return this[kBinaryType] + } + + set binaryType (type) { + webidl.brandCheck(this, WebSocket); + + if (type !== 'blob' && type !== 'arraybuffer') { + this[kBinaryType] = 'blob'; + } else { + this[kBinaryType] = type; + } + } + + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + */ + #onConnectionEstablished (response) { + // processResponse is called when the "response’s header list has been received and initialized." + // once this happens, the connection is open + this[kResponse] = response; + + const parser = new ByteParser(this); + parser.on('drain', function onParserDrain () { + this.ws[kResponse].socket.resume(); + }); + + response.socket.ws = this; + this[kByteParser] = parser; + + // 1. Change the ready state to OPEN (1). + this[kReadyState] = states.OPEN; + + // 2. Change the extensions attribute’s value to the extensions in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 + const extensions = response.headersList.get('sec-websocket-extensions'); + + if (extensions !== null) { + this.#extensions = extensions; + } + + // 3. Change the protocol attribute’s value to the subprotocol in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 + const protocol = response.headersList.get('sec-websocket-protocol'); + + if (protocol !== null) { + this.#protocol = protocol; + } + + // 4. Fire an event named open at the WebSocket object. + fireEvent('open', this); + } + } + // https://websockets.spec.whatwg.org/#dom-websocket-connecting + WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING; + // https://websockets.spec.whatwg.org/#dom-websocket-open + WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN; + // https://websockets.spec.whatwg.org/#dom-websocket-closing + WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING; + // https://websockets.spec.whatwg.org/#dom-websocket-closed + WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED; + + Object.defineProperties(WebSocket.prototype, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors, + url: kEnumerableProperty, + readyState: kEnumerableProperty, + bufferedAmount: kEnumerableProperty, + onopen: kEnumerableProperty, + onerror: kEnumerableProperty, + onclose: kEnumerableProperty, + close: kEnumerableProperty, + onmessage: kEnumerableProperty, + binaryType: kEnumerableProperty, + send: kEnumerableProperty, + extensions: kEnumerableProperty, + protocol: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocket', + writable: false, + enumerable: false, + configurable: true + } + }); - function pad(n) { - return n < 10 ? '0' + n.toString(10) : n.toString(10); - } + Object.defineProperties(WebSocket, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors + }); + webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.DOMString + ); - var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', - 'Oct', 'Nov', 'Dec']; + webidl.converters['DOMString or sequence'] = function (V) { + if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { + return webidl.converters['sequence'](V) + } - // 26 Feb 16:19:34 - function timestamp() { - var d = new Date(); - var time = [pad(d.getHours()), - pad(d.getMinutes()), - pad(d.getSeconds())].join(':'); - return [d.getDate(), months[d.getMonth()], time].join(' '); - } + return webidl.converters.DOMString(V) + }; + // This implements the propsal made in https://github.com/whatwg/websockets/issues/42 + webidl.converters.WebSocketInit = webidl.dictionaryConverter([ + { + key: 'protocols', + converter: webidl.converters['DOMString or sequence'], + get defaultValue () { + return [] + } + }, + { + key: 'dispatcher', + converter: (V) => V, + get defaultValue () { + return getGlobalDispatcher() + } + }, + { + key: 'headers', + converter: webidl.nullableConverter(webidl.converters.HeadersInit) + } + ]); + + webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { + if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) { + return webidl.converters.WebSocketInit(V) + } + + return { protocols: webidl.converters['DOMString or sequence'](V) } + }; - // log is just a thin wrapper to console.log that prepends a timestamp - function log() { - console.log('%s - %s', timestamp(), format.apply(null, arguments)); - } + webidl.converters.WebSocketSendData = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } - function _extend(origin, add) { - // Don't do anything if add isn't an object - if (!add || !isObject(add)) return origin; + if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) { + return webidl.converters.BufferSource(V) + } + } - var keys = Object.keys(add); - var i = keys.length; - while (i--) { - origin[keys[i]] = add[keys[i]]; - } - return origin; + return webidl.converters.USVString(V) + }; + + websocket = { + WebSocket + }; + return websocket; } - function hasOwnProperty(obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop); + + const Client = client; + const Dispatcher = dispatcher; + const errors = errors$1; + const Pool = pool; + const BalancedPool = balancedPool; + const Agent = agent; + const util$2 = util$l; + const { InvalidArgumentError } = errors; + const api = api$1; + const buildConnector = connect$2; + const MockClient = mockClient; + const MockAgent = mockAgent; + const MockPool = mockPool; + const mockErrors = mockErrors$1; + const ProxyAgent = proxyAgent; + const { getGlobalDispatcher, setGlobalDispatcher } = global$1; + const DecoratorHandler = DecoratorHandler_1; + const RedirectHandler = RedirectHandler_1; + const createRedirectInterceptor = redirectInterceptor; + + let hasCrypto; + try { + + hasCrypto = true; + } catch { + hasCrypto = false; } - var kCustomPromisifiedSymbol = typeof Symbol !== 'undefined' ? Symbol('util.promisify.custom') : undefined; + Object.assign(Dispatcher.prototype, api); - function promisify(original) { - if (typeof original !== 'function') - throw new TypeError('The "original" argument must be of type Function'); + undici$1.Dispatcher = Dispatcher; + undici$1.Client = Client; + undici$1.Pool = Pool; + undici$1.BalancedPool = BalancedPool; + undici$1.Agent = Agent; + undici$1.ProxyAgent = ProxyAgent; - if (kCustomPromisifiedSymbol && original[kCustomPromisifiedSymbol]) { - var fn = original[kCustomPromisifiedSymbol]; - if (typeof fn !== 'function') { - throw new TypeError('The "util.promisify.custom" argument must be of type Function'); + undici$1.DecoratorHandler = DecoratorHandler; + undici$1.RedirectHandler = RedirectHandler; + undici$1.createRedirectInterceptor = createRedirectInterceptor; + + undici$1.buildConnector = buildConnector; + undici$1.errors = errors; + + function makeDispatcher (fn) { + return (url, opts, handler) => { + if (typeof opts === 'function') { + handler = opts; + opts = null; } - Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return fn; - } - function fn() { - var promiseResolve, promiseReject; - var promise = new Promise(function (resolve, reject) { - promiseResolve = resolve; - promiseReject = reject; - }); + if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { + throw new InvalidArgumentError('invalid url') + } - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); + if (opts != null && typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') } - args.push(function (err, value) { - if (err) { - promiseReject(err); - } else { - promiseResolve(value); + + if (opts && opts.path != null) { + if (typeof opts.path !== 'string') { + throw new InvalidArgumentError('invalid opts.path') } - }); - try { - original.apply(this, args); - } catch (err) { - promiseReject(err); - } + let path = opts.path; + if (!opts.path.startsWith('/')) { + path = `/${path}`; + } - return promise; - } + url = new URL(util$2.parseOrigin(url).origin + path); + } else { + if (!opts) { + opts = typeof url === 'object' ? url : {}; + } - Object.setPrototypeOf(fn, Object.getPrototypeOf(original)); + url = util$2.parseURL(url); + } - if (kCustomPromisifiedSymbol) Object.defineProperty(fn, kCustomPromisifiedSymbol, { - value: fn, enumerable: false, writable: false, configurable: true - }); - return Object.defineProperties( - fn, - getOwnPropertyDescriptors(original) - ); - } + const { agent, dispatcher = getGlobalDispatcher() } = opts; - promisify.custom = kCustomPromisifiedSymbol; + if (agent) { + throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') + } - function callbackifyOnRejected(reason, cb) { - // `!reason` guard inspired by bluebird (Ref: https://goo.gl/t5IS6M). - // Because `null` is a special error value in callbacks which means "no error - // occurred", we error-wrap so the callback consumer can distinguish between - // "the promise rejected with null" or "the promise fulfilled with undefined". - if (!reason) { - var newReason = new Error('Promise was rejected with a falsy value'); - newReason.reason = reason; - reason = newReason; + return fn.call(dispatcher, { + ...opts, + origin: url.origin, + path: url.search ? `${url.pathname}${url.search}` : url.pathname, + method: opts.method || (opts.body ? 'PUT' : 'GET') + }, handler) } - return cb(reason); } - function callbackify(original) { - if (typeof original !== 'function') { - throw new TypeError('The "original" argument must be of type Function'); - } + undici$1.setGlobalDispatcher = setGlobalDispatcher; + undici$1.getGlobalDispatcher = getGlobalDispatcher; - // We DO NOT return the promise as it gives the user a false sense that - // the promise is actually somehow related to the callback's execution - // and that the callback throwing will reject the promise. - function callbackified() { - var args = []; - for (var i = 0; i < arguments.length; i++) { - args.push(arguments[i]); + if (util$2.nodeMajor > 16 || (util$2.nodeMajor === 16 && util$2.nodeMinor >= 8)) { + let fetchImpl = null; + undici$1.fetch = async function fetch (resource) { + if (!fetchImpl) { + fetchImpl = requireFetch().fetch; } - var maybeCb = args.pop(); - if (typeof maybeCb !== 'function') { - throw new TypeError('The last argument must be of type Function'); - } - var self = this; - var cb = function() { - return maybeCb.apply(self, arguments); - }; - // In true node style we process the callback on `nextTick` with all the - // implications (stack, `uncaughtException`, `async_hooks`) - original.apply(this, args) - .then(function(ret) { browser$1$1.nextTick(cb.bind(null, null, ret)); }, - function(rej) { browser$1$1.nextTick(callbackifyOnRejected.bind(null, rej, cb)); }); - } - - Object.setPrototypeOf(callbackified, Object.getPrototypeOf(original)); - Object.defineProperties(callbackified, getOwnPropertyDescriptors(original)); - return callbackified; - } - - var _polyfillNode_util = { - inherits: inherits$1, - _extend: _extend, - log: log, - isBuffer: isBuffer, - isPrimitive: isPrimitive, - isFunction: isFunction, - isError: isError, - isDate: isDate, - isObject: isObject, - isRegExp: isRegExp, - isUndefined: isUndefined, - isSymbol: isSymbol, - isString: isString, - isNumber: isNumber, - isNullOrUndefined: isNullOrUndefined$1, - isNull: isNull, - isBoolean: isBoolean, - isArray: isArray$1, - inspect: inspect, - deprecate: deprecate, - format: format, - debuglog: debuglog, - promisify: promisify, - callbackify: callbackify, - }; - - var _polyfillNode_util$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - _extend: _extend, - callbackify: callbackify, - debuglog: debuglog, - default: _polyfillNode_util, - deprecate: deprecate, - format: format, - inherits: inherits$1, - inspect: inspect, - isArray: isArray$1, - isBoolean: isBoolean, - isBuffer: isBuffer, - isDate: isDate, - isError: isError, - isFunction: isFunction, - isNull: isNull, - isNullOrUndefined: isNullOrUndefined$1, - isNumber: isNumber, - isObject: isObject, - isPrimitive: isPrimitive, - isRegExp: isRegExp, - isString: isString, - isSymbol: isSymbol, - isUndefined: isUndefined, - log: log, - promisify: promisify - }); + try { + return await fetchImpl(...arguments) + } catch (err) { + if (typeof err === 'object') { + Error.captureStackTrace(err, this); + } - var require$$3 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_util$1); + throw err + } + }; + undici$1.Headers = requireHeaders().Headers; + undici$1.Response = requireResponse().Response; + undici$1.Request = requireRequest().Request; + undici$1.FormData = requireFormdata().FormData; + undici$1.File = requireFile().File; + undici$1.FileReader = requireFilereader().FileReader; - var require$$4 = /*@__PURE__*/getAugmentedNamespace(index_esm2017$3); + const { setGlobalOrigin, getGlobalOrigin } = requireGlobal(); - var browser$1 = {exports: {}}; + undici$1.setGlobalOrigin = setGlobalOrigin; + undici$1.getGlobalOrigin = getGlobalOrigin; - (function (module, exports) { + const { CacheStorage } = requireCachestorage(); + const { kConstruct } = requireSymbols$1(); - // ref: https://github.com/tc39/proposal-global - var getGlobal = function () { - // the only reliable means to get the global object is - // `Function('return this')()` - // However, this causes CSP violations in Chrome apps. - if (typeof self !== 'undefined') { return self; } - if (typeof window !== 'undefined') { return window; } - if (typeof commonjsGlobal !== 'undefined') { return commonjsGlobal; } - throw new Error('unable to locate global object'); - }; + // Cache & CacheStorage are tightly coupled with fetch. Even if it may run + // in an older version of Node, it doesn't have any use without fetch. + undici$1.caches = new CacheStorage(kConstruct); + } - var globalObject = getGlobal(); + if (util$2.nodeMajor >= 16) { + const { deleteCookie, getCookies, getSetCookies, setCookie } = requireCookies(); - module.exports = exports = globalObject.fetch; + undici$1.deleteCookie = deleteCookie; + undici$1.getCookies = getCookies; + undici$1.getSetCookies = getSetCookies; + undici$1.setCookie = setCookie; - // Needed for TypeScript and Webpack. - if (globalObject.fetch) { - exports.default = globalObject.fetch.bind(globalObject); - } + const { parseMIMEType, serializeAMimeType } = requireDataURL(); - exports.Headers = globalObject.Headers; - exports.Request = globalObject.Request; - exports.Response = globalObject.Response; - } (browser$1, browser$1.exports)); + undici$1.parseMIMEType = parseMIMEType; + undici$1.serializeAMimeType = serializeAMimeType; + } - var browserExports = browser$1.exports; + if (util$2.nodeMajor >= 18 && hasCrypto) { + const { WebSocket } = requireWebsocket(); - var _polyfillNode_crypto = {}; + undici$1.WebSocket = WebSocket; + } - var _polyfillNode_crypto$1 = /*#__PURE__*/Object.freeze({ - __proto__: null, - default: _polyfillNode_crypto - }); + undici$1.request = makeDispatcher(api.request); + undici$1.stream = makeDispatcher(api.stream); + undici$1.pipeline = makeDispatcher(api.pipeline); + undici$1.connect = makeDispatcher(api.connect); + undici$1.upgrade = makeDispatcher(api.upgrade); - var require$$6 = /*@__PURE__*/getAugmentedNamespace(_polyfillNode_crypto$1); + undici$1.MockClient = MockClient; + undici$1.MockPool = MockPool; + undici$1.MockAgent = MockAgent; + undici$1.mockErrors = mockErrors; Object.defineProperty(index_node_cjs, '__esModule', { value: true }); - var app = require$$0; - var component = require$$1; - var logger = require$$2; - var util$1 = require$$3; - var util = require$$4; - var nodeFetch = browserExports; - var crypto = require$$6; - - function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; } + var app = require$$0$2; + var component = require$$1$4; + var logger = index_cjs$1; + var util$1 = require$$3$2; + var util = require$$4$1; + var undici = undici$1; + var crypto = require$$6$1; - var nodeFetch__default = /*#__PURE__*/_interopDefaultLegacy(nodeFetch); - - const version$1 = "4.2.0"; + const version$1 = "4.4.0"; /** * @license @@ -6076,7 +40376,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; User.FIRST_PARTY = new User('first-party-uid'); User.MOCK_USER = new User('mock-user'); - const version = "10.4.0"; + const version = "10.7.0"; /** * @license @@ -7617,10 +41917,10 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; */ /** Initializes the HTTP connection for the REST API. */ function newConnection(databaseInfo) { - // node-fetch is meant to be API compatible with `fetch`, but its type doesn't + // undici is meant to be API compatible with `fetch`, but its type doesn't // match 100%. // eslint-disable-next-line @typescript-eslint/no-explicit-any - return new FetchConnection(databaseInfo, nodeFetch__default["default"]); + return new FetchConnection(databaseInfo, undici.fetch); } /** @@ -7664,6 +41964,12 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * See the License for the specific language governing permissions and * limitations under the License. */ + /** + * A utility class for generating unique alphanumeric IDs of a specified length. + * + * @internal + * Exported internally for testing purposes. + */ class AutoId { static newId() { // Alphanumeric characters @@ -8739,12 +43045,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; getFilters() { return [this]; } - getFirstInequalityField() { - if (this.isInequality()) { - return this.field; - } - return null; - } } class CompositeFilter extends Filter { constructor(filters, op) { @@ -8782,24 +43082,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; getFilters() { return Object.assign([], this.filters); } - getFirstInequalityField() { - const found = this.findFirstMatchingFilter(filter => filter.isInequality()); - if (found !== null) { - return found.field; - } - return null; - } - // Performs a depth-first search to find and return the first FieldFilter in the composite filter - // that satisfies the predicate. Returns `null` if none of the FieldFilters satisfy the - // predicate. - findFirstMatchingFilter(predicate) { - for (const fieldFilter of this.getFlattenedFilters()) { - if (predicate(fieldFilter)) { - return fieldFilter; - } - } - return null; - } } function compositeFilterIsConjunction(compositeFilter) { return compositeFilter.op === "and" /* CompositeOperator.AND */; @@ -10118,19 +44400,18 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; function newQueryForPath(path) { return new QueryImpl(path); } - function getFirstOrderByField(query) { - return query.explicitOrderBy.length > 0 - ? query.explicitOrderBy[0].field - : null; - } - function getInequalityFilterField(query) { - for (const filter of query.filters) { - const result = filter.getFirstInequalityField(); - if (result !== null) { - return result; - } - } - return null; + // Returns the sorted set of inequality filter fields used in this query. + function getInequalityFilterFields(query) { + let result = new SortedSet(FieldPath$1.comparator); + query.filters.forEach((filter) => { + const subFilters = filter.getFlattenedFilters(); + subFilters.forEach((filter) => { + if (filter.isInequality()) { + result = result.add(filter.field); + } + }); + }); + return result; } /** * Creates a new Query for a collection group query that matches all documents @@ -10157,34 +44438,31 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; const queryImpl = debugCast(query); if (queryImpl.memoizedNormalizedOrderBy === null) { queryImpl.memoizedNormalizedOrderBy = []; - const inequalityField = getInequalityFilterField(queryImpl); - const firstOrderByField = getFirstOrderByField(queryImpl); - if (inequalityField !== null && firstOrderByField === null) { - // In order to implicitly add key ordering, we must also add the - // inequality filter field for it to be a valid query. - // Note that the default inequality field and key ordering is ascending. - if (!inequalityField.isKeyField()) { - queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(inequalityField)); - } - queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), "asc" /* Direction.ASCENDING */)); - } - else { - let foundKeyOrdering = false; - for (const orderBy of queryImpl.explicitOrderBy) { - queryImpl.memoizedNormalizedOrderBy.push(orderBy); - if (orderBy.field.isKeyField()) { - foundKeyOrdering = true; - } - } - if (!foundKeyOrdering) { - // The order of the implicit key ordering always matches the last - // explicit order-by - const lastDirection = queryImpl.explicitOrderBy.length > 0 - ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1] - .dir - : "asc" /* Direction.ASCENDING */; - queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection)); + const fieldsNormalized = new Set(); + // Any explicit order by fields should be added as is. + for (const orderBy of queryImpl.explicitOrderBy) { + queryImpl.memoizedNormalizedOrderBy.push(orderBy); + fieldsNormalized.add(orderBy.field.canonicalString()); + } + // The order of the implicit ordering always matches the last explicit order by. + const lastDirection = queryImpl.explicitOrderBy.length > 0 + ? queryImpl.explicitOrderBy[queryImpl.explicitOrderBy.length - 1].dir + : "asc" /* Direction.ASCENDING */; + // Any inequality fields not explicitly ordered should be implicitly ordered in a lexicographical + // order. When there are multiple inequality filters on the same field, the field should be added + // only once. + // Note: `SortedSet` sorts the key field before other fields. However, we want the key + // field to be sorted last. + const inequalityFields = getInequalityFilterFields(queryImpl); + inequalityFields.forEach(field => { + if (!fieldsNormalized.has(field.canonicalString()) && + !field.isKeyField()) { + queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(field, lastDirection)); } + }); + // Add the document key field to the last if it is not explicitly ordered. + if (!fieldsNormalized.has(FieldPath$1.keyField().canonicalString())) { + queryImpl.memoizedNormalizedOrderBy.push(new OrderBy(FieldPath$1.keyField(), lastDirection)); } } return queryImpl.memoizedNormalizedOrderBy; @@ -10237,8 +44515,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } } function queryWithAddedFilter(query, filter) { - filter.getFirstInequalityField(); - getInequalityFilterField(query); const newFilters = query.filters.concat([filter]); return new QueryImpl(query.path, query.collectionGroup, query.explicitOrderBy.slice(), newFilters, query.limit, query.limitType, query.startAt, query.endAt); } @@ -11890,17 +46166,15 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; class AggregateField { /** * Create a new AggregateField - * @param _aggregateType Specifies the type of aggregation operation to perform. + * @param aggregateType Specifies the type of aggregation operation to perform. * @param _internalFieldPath Optionally specifies the field that is aggregated. * @internal */ - constructor( - // TODO (sum/avg) make aggregateType public when the feature is supported - _aggregateType = 'count', _internalFieldPath) { - this._aggregateType = _aggregateType; + constructor(aggregateType = 'count', _internalFieldPath) { this._internalFieldPath = _internalFieldPath; /** A type string to uniquely identify instances of this class. */ this.type = 'AggregateField'; + this.aggregateType = aggregateType; } } /** @@ -13663,7 +47937,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; 'calling orderBy().'); } const orderBy = new OrderBy(fieldPath, direction); - validateNewOrderBy(query, orderBy); return orderBy; } /** @@ -13831,21 +48104,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } } function validateNewFieldFilter(query, fieldFilter) { - if (fieldFilter.isInequality()) { - const existingInequality = getInequalityFilterField(query); - const newInequality = fieldFilter.field; - if (existingInequality !== null && - !existingInequality.isEqual(newInequality)) { - throw new FirestoreError(Code.INVALID_ARGUMENT, 'Invalid query. All where filters with an inequality' + - ' (<, <=, !=, not-in, >, or >=) must be on the same field. But you have' + - ` inequality filters on '${existingInequality.toString()}'` + - ` and '${newInequality.toString()}'`); - } - const firstOrderByField = getFirstOrderByField(query); - if (firstOrderByField !== null) { - validateOrderByAndInequalityMatch(query, newInequality, firstOrderByField); - } - } const conflictingOp = findOpInsideFilters(query.filters, conflictingOps(fieldFilter.op)); if (conflictingOp !== null) { // Special case when it's a duplicate op to give a slightly clearer error message. @@ -13879,24 +48137,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; } return null; } - function validateNewOrderBy(query, orderBy) { - if (getFirstOrderByField(query) === null) { - // This is the first order by. It must match any inequality. - const inequalityField = getInequalityFilterField(query); - if (inequalityField !== null) { - validateOrderByAndInequalityMatch(query, inequalityField, orderBy.field); - } - } - } - function validateOrderByAndInequalityMatch(baseQuery, inequality, orderBy) { - if (!orderBy.isEqual(inequality)) { - throw new FirestoreError(Code.INVALID_ARGUMENT, `Invalid query. You have a where filter with an inequality ` + - `(<, <=, !=, not-in, >, or >=) on field '${inequality.toString()}' ` + - `and so you must also use '${inequality.toString()}' ` + - `as your first argument to orderBy(), but your first orderBy() ` + - `is on field '${orderBy.toString()}' instead.`); - } - } function validateQueryFilterConstraint(functionName, queryConstraint) { if (!(queryConstraint instanceof QueryFieldFilterConstraint) && !(queryConstraint instanceof QueryCompositeFilterConstraint)) { @@ -14245,7 +48485,7 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * set of the given query, without actually downloading the documents. * * Using this function to perform aggregations is efficient because only the - * final aggregation values, not the documents' data, is downloaded. This + * final aggregation values, not the documents' data, are downloaded. This * function can even perform aggregations of the documents if the result set * would be prohibitively large to download entirely (e.g. thousands of documents). * @@ -14265,13 +48505,12 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * const totalHours: number = aggregateSnapshot.data().totalHours; * const averageScore: number | null = aggregateSnapshot.data().averageScore; * ``` - * @internal TODO (sum/avg) remove when public */ function getAggregate(query, aggregateSpec) { const firestore = cast(query.firestore, Firestore); const datastore = getDatastore(firestore); const internalAggregates = mapToArray(aggregateSpec, (aggregate, alias) => { - return new AggregateImpl(alias, aggregate._aggregateType, aggregate._internalFieldPath); + return new AggregateImpl(alias, aggregate.aggregateType, aggregate._internalFieldPath); }); // Run the aggregation and convert the results return invokeRunAggregationQueryRpc(datastore, query._query, internalAggregates).then(aggregateResult => convertToAggregateQuerySnapshot(firestore, query, aggregateResult)); @@ -14285,7 +48524,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * Create an AggregateField object that can be used to compute the sum of * a specified field over a range of documents in the result set of a query. * @param field Specifies the field to sum across the result set. - * @internal TODO (sum/avg) remove when public */ function sum(field) { return new AggregateField('sum', fieldPathFromArgument$1('sum', field)); @@ -14294,7 +48532,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * Create an AggregateField object that can be used to compute the average of * a specified field over a range of documents in the result set of a query. * @param field Specifies the field to average across the result set. - * @internal TODO (sum/avg) remove when public */ function average(field) { return new AggregateField('avg', fieldPathFromArgument$1('average', field)); @@ -14302,7 +48539,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; /** * Create an AggregateField object that can be used to compute the count of * documents in the result set of a query. - * @internal TODO (sum/avg) remove when public */ function count() { return new AggregateField('count'); @@ -14312,13 +48548,12 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; * * @param left Compare this AggregateField to the `right`. * @param right Compare this AggregateField to the `left`. - * @internal TODO (sum/avg) remove when public */ function aggregateFieldEqual(left, right) { var _a, _b; return (left instanceof AggregateField && right instanceof AggregateField && - left._aggregateType === right._aggregateType && + left.aggregateType === right.aggregateType && ((_a = left._internalFieldPath) === null || _a === void 0 ? void 0 : _a.canonicalString()) === ((_b = right._internalFieldPath) === null || _b === void 0 ? void 0 : _b.canonicalString())); } @@ -15425,6 +49660,6 @@ sap.ui.define(['exports'], (function (exports) { 'use strict'; exports.doc = index_cjs.doc; exports.getDoc = index_cjs.getDoc; exports.getFirestore = index_cjs.getFirestore; - exports.initializeApp = index_cjs$1.initializeApp; + exports.initializeApp = index_cjs$2.initializeApp; })); diff --git a/packages/ui5-tooling-modules/test/__snap__/ui5-app/bundledefs/react.js b/packages/ui5-tooling-modules/test/__snap__/ui5-app/bundledefs/react.js index 6300cf329..1ba0167b2 100644 --- a/packages/ui5-tooling-modules/test/__snap__/ui5-app/bundledefs/react.js +++ b/packages/ui5-tooling-modules/test/__snap__/ui5-app/bundledefs/react.js @@ -2,1793 +2,37 @@ sap.ui.define((function () { 'use strict'; var react = {exports: {}}; - var react_development = {exports: {}}; + var react_production_min = {}; - react_development.exports; - (function (module, exports) { - { - (function () { - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); - } - var ReactVersion = "18.2.0"; - var REACT_ELEMENT_TYPE = Symbol.for("react.element"); - var REACT_PORTAL_TYPE = Symbol.for("react.portal"); - var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); - var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); - var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); - var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); - var REACT_CONTEXT_TYPE = Symbol.for("react.context"); - var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); - var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); - var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); - var REACT_MEMO_TYPE = Symbol.for("react.memo"); - var REACT_LAZY_TYPE = Symbol.for("react.lazy"); - var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); - var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; - var FAUX_ITERATOR_SYMBOL = "@@iterator"; - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== "object") { - return null; - } - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (typeof maybeIterator === "function") { - return maybeIterator; - } - return null; - } - var ReactCurrentDispatcher = { - current: null - }; - var ReactCurrentBatchConfig = { - transition: null - }; - var ReactCurrentActQueue = { - current: null, - isBatchingLegacy: false, - didScheduleLegacyUpdate: false - }; - var ReactCurrentOwner = { - current: null - }; - var ReactDebugCurrentFrame = {}; - var currentExtraStackFrame = null; - function setExtraStackFrame(stack) { - { - currentExtraStackFrame = stack; - } - } - { - ReactDebugCurrentFrame.setExtraStackFrame = function (stack) { - { - currentExtraStackFrame = stack; - } - }; - ReactDebugCurrentFrame.getCurrentStack = null; - ReactDebugCurrentFrame.getStackAddendum = function () { - var stack = ""; - if (currentExtraStackFrame) { - stack += currentExtraStackFrame; - } - var impl = ReactDebugCurrentFrame.getCurrentStack; - if (impl) { - stack += impl() || ""; - } - return stack; - }; - } - var enableScopeAPI = false; - var enableCacheElement = false; - var enableTransitionTracing = false; - var enableLegacyHidden = false; - var enableDebugTracing = false; - var ReactSharedInternals = { - ReactCurrentDispatcher: ReactCurrentDispatcher, - ReactCurrentBatchConfig: ReactCurrentBatchConfig, - ReactCurrentOwner: ReactCurrentOwner - }; - { - ReactSharedInternals.ReactDebugCurrentFrame = ReactDebugCurrentFrame; - ReactSharedInternals.ReactCurrentActQueue = ReactCurrentActQueue; - } - function warn(format) { - { - { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - printWarning("warn", format, args); - } - } - } - function error(format) { - { - { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - printWarning("error", format, args); - } - } - } - function printWarning(level, format, args) { - { - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame.getStackAddendum(); - if (stack !== "") { - format += "%s"; - args = args.concat([stack]); - } - var argsWithFormat = args.map(function (item) { - return String(item); - }); - argsWithFormat.unshift("Warning: " + format); - Function.prototype.apply.call(console[level], console, argsWithFormat); - } - } - var didWarnStateUpdateForUnmountedComponent = {}; - function warnNoop(publicInstance, callerName) { - { - var _constructor = publicInstance.constructor; - var componentName = _constructor && (_constructor.displayName || _constructor.name) || "ReactClass"; - var warningKey = componentName + "." + callerName; - if (didWarnStateUpdateForUnmountedComponent[warningKey]) { - return; - } - error("Can't call %s on a component that is not yet mounted. " + "This is a no-op, but it might indicate a bug in your application. " + "Instead, assign to `this.state` directly or define a `state = {};` " + "class property with the desired state in the %s component.", callerName, componentName); - didWarnStateUpdateForUnmountedComponent[warningKey] = true; - } - } - var ReactNoopUpdateQueue = { - isMounted: function (publicInstance) { - return false; - }, - enqueueForceUpdate: function (publicInstance, callback, callerName) { - warnNoop(publicInstance, "forceUpdate"); - }, - enqueueReplaceState: function (publicInstance, completeState, callback, callerName) { - warnNoop(publicInstance, "replaceState"); - }, - enqueueSetState: function (publicInstance, partialState, callback, callerName) { - warnNoop(publicInstance, "setState"); - } - }; - var assign = Object.assign; - var emptyObject = {}; - { - Object.freeze(emptyObject); - } - function Component(props, context, updater) { - this.props = props; - this.context = context; - this.refs = emptyObject; - this.updater = updater || ReactNoopUpdateQueue; - } - Component.prototype.isReactComponent = {}; - Component.prototype.setState = function (partialState, callback) { - if (typeof partialState !== "object" && typeof partialState !== "function" && partialState != null) { - throw new Error("setState(...): takes an object of state variables to update or a " + "function which returns an object of state variables."); - } - this.updater.enqueueSetState(this, partialState, callback, "setState"); - }; - Component.prototype.forceUpdate = function (callback) { - this.updater.enqueueForceUpdate(this, callback, "forceUpdate"); - }; - { - var deprecatedAPIs = { - isMounted: ["isMounted", "Instead, make sure to clean up subscriptions and pending requests in " + "componentWillUnmount to prevent memory leaks."], - replaceState: ["replaceState", "Refactor your code to use setState instead (see " + "https://github.com/facebook/react/issues/3236)."] - }; - var defineDeprecationWarning = function (methodName, info) { - Object.defineProperty(Component.prototype, methodName, { - get: function () { - warn("%s(...) is deprecated in plain JavaScript React classes. %s", info[0], info[1]); - return undefined; - } - }); - }; - for (var fnName in deprecatedAPIs) { - if (deprecatedAPIs.hasOwnProperty(fnName)) { - defineDeprecationWarning(fnName, deprecatedAPIs[fnName]); - } - } - } - function ComponentDummy() {} - ComponentDummy.prototype = Component.prototype; - function PureComponent(props, context, updater) { - this.props = props; - this.context = context; - this.refs = emptyObject; - this.updater = updater || ReactNoopUpdateQueue; - } - var pureComponentPrototype = PureComponent.prototype = new ComponentDummy(); - pureComponentPrototype.constructor = PureComponent; - assign(pureComponentPrototype, Component.prototype); - pureComponentPrototype.isPureReactComponent = true; - function createRef() { - var refObject = { - current: null - }; - { - Object.seal(refObject); - } - return refObject; - } - var isArrayImpl = Array.isArray; - function isArray(a) { - return isArrayImpl(a); - } - function typeName(value) { - { - var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; - var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; - return type; - } - } - function willCoercionThrow(value) { - { - try { - testStringCoercion(value); - return false; - } catch (e) { - return true; - } - } - } - function testStringCoercion(value) { - return "" + value; - } - function checkKeyStringCoercion(value) { - { - if (willCoercionThrow(value)) { - error("The provided key is an unsupported type %s." + " This value must be coerced to a string before before using it here.", typeName(value)); - return testStringCoercion(value); - } - } - } - function getWrappedName(outerType, innerType, wrapperName) { - var displayName = outerType.displayName; - if (displayName) { - return displayName; - } - var functionName = innerType.displayName || innerType.name || ""; - return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; - } - function getContextName(type) { - return type.displayName || "Context"; - } - function getComponentNameFromType(type) { - if (type == null) { - return null; - } - { - if (typeof type.tag === "number") { - error("Received an unexpected object in getComponentNameFromType(). " + "This is likely a bug in React. Please file an issue."); - } - } - if (typeof type === "function") { - return type.displayName || type.name || null; - } - if (typeof type === "string") { - return type; - } - switch (type) { - case REACT_FRAGMENT_TYPE: - return "Fragment"; - case REACT_PORTAL_TYPE: - return "Portal"; - case REACT_PROFILER_TYPE: - return "Profiler"; - case REACT_STRICT_MODE_TYPE: - return "StrictMode"; - case REACT_SUSPENSE_TYPE: - return "Suspense"; - case REACT_SUSPENSE_LIST_TYPE: - return "SuspenseList"; - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type; - return getContextName(context) + ".Consumer"; - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName(provider._context) + ".Provider"; - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, "ForwardRef"); - case REACT_MEMO_TYPE: - var outerName = type.displayName || null; - if (outerName !== null) { - return outerName; - } - return getComponentNameFromType(type.type) || "Memo"; - case REACT_LAZY_TYPE: - { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return getComponentNameFromType(init(payload)); - } catch (x) { - return null; - } - } - } - } - return null; - } - var hasOwnProperty = Object.prototype.hasOwnProperty; - var RESERVED_PROPS = { - key: true, - ref: true, - __self: true, - __source: true - }; - var specialPropKeyWarningShown, specialPropRefWarningShown, didWarnAboutStringRefs; - { - didWarnAboutStringRefs = {}; - } - function hasValidRef(config) { - { - if (hasOwnProperty.call(config, "ref")) { - var getter = Object.getOwnPropertyDescriptor(config, "ref").get; - if (getter && getter.isReactWarning) { - return false; - } - } - } - return config.ref !== undefined; - } - function hasValidKey(config) { - { - if (hasOwnProperty.call(config, "key")) { - var getter = Object.getOwnPropertyDescriptor(config, "key").get; - if (getter && getter.isReactWarning) { - return false; - } - } - } - return config.key !== undefined; - } - function defineKeyPropWarningGetter(props, displayName) { - var warnAboutAccessingKey = function () { - { - if (!specialPropKeyWarningShown) { - specialPropKeyWarningShown = true; - error("%s: `key` is not a prop. Trying to access it will result " + "in `undefined` being returned. If you need to access the same " + "value within the child component, you should pass it as a different " + "prop. (https://reactjs.org/link/special-props)", displayName); - } - } - }; - warnAboutAccessingKey.isReactWarning = true; - Object.defineProperty(props, "key", { - get: warnAboutAccessingKey, - configurable: true - }); - } - function defineRefPropWarningGetter(props, displayName) { - var warnAboutAccessingRef = function () { - { - if (!specialPropRefWarningShown) { - specialPropRefWarningShown = true; - error("%s: `ref` is not a prop. Trying to access it will result " + "in `undefined` being returned. If you need to access the same " + "value within the child component, you should pass it as a different " + "prop. (https://reactjs.org/link/special-props)", displayName); - } - } - }; - warnAboutAccessingRef.isReactWarning = true; - Object.defineProperty(props, "ref", { - get: warnAboutAccessingRef, - configurable: true - }); - } - function warnIfStringRefCannotBeAutoConverted(config) { - { - if (typeof config.ref === "string" && ReactCurrentOwner.current && config.__self && ReactCurrentOwner.current.stateNode !== config.__self) { - var componentName = getComponentNameFromType(ReactCurrentOwner.current.type); - if (!didWarnAboutStringRefs[componentName]) { - error("Component \"%s\" contains the string ref \"%s\". " + "Support for string refs will be removed in a future major release. " + "This case cannot be automatically converted to an arrow function. " + "We ask you to manually fix this case by using useRef() or createRef() instead. " + "Learn more about using refs safely here: " + "https://reactjs.org/link/strict-mode-string-ref", componentName, config.ref); - didWarnAboutStringRefs[componentName] = true; - } - } - } - } - var ReactElement = function (type, key, ref, self, source, owner, props) { - var element = { - $$typeof: REACT_ELEMENT_TYPE, - type: type, - key: key, - ref: ref, - props: props, - _owner: owner - }; - { - element._store = {}; - Object.defineProperty(element._store, "validated", { - configurable: false, - enumerable: false, - writable: true, - value: false - }); - Object.defineProperty(element, "_self", { - configurable: false, - enumerable: false, - writable: false, - value: self - }); - Object.defineProperty(element, "_source", { - configurable: false, - enumerable: false, - writable: false, - value: source - }); - if (Object.freeze) { - Object.freeze(element.props); - Object.freeze(element); - } - } - return element; - }; - function createElement(type, config, children) { - var propName; - var props = {}; - var key = null; - var ref = null; - var self = null; - var source = null; - if (config != null) { - if (hasValidRef(config)) { - ref = config.ref; - { - warnIfStringRefCannotBeAutoConverted(config); - } - } - if (hasValidKey(config)) { - { - checkKeyStringCoercion(config.key); - } - key = "" + config.key; - } - self = config.__self === undefined ? null : config.__self; - source = config.__source === undefined ? null : config.__source; - for (propName in config) { - if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { - props[propName] = config[propName]; - } - } - } - var childrenLength = arguments.length - 2; - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = Array(childrenLength); - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 2]; - } - { - if (Object.freeze) { - Object.freeze(childArray); - } - } - props.children = childArray; - } - if (type && type.defaultProps) { - var defaultProps = type.defaultProps; - for (propName in defaultProps) { - if (props[propName] === undefined) { - props[propName] = defaultProps[propName]; - } - } - } - { - if (key || ref) { - var displayName = typeof type === "function" ? type.displayName || type.name || "Unknown" : type; - if (key) { - defineKeyPropWarningGetter(props, displayName); - } - if (ref) { - defineRefPropWarningGetter(props, displayName); - } - } - } - return ReactElement(type, key, ref, self, source, ReactCurrentOwner.current, props); - } - function cloneAndReplaceKey(oldElement, newKey) { - var newElement = ReactElement(oldElement.type, newKey, oldElement.ref, oldElement._self, oldElement._source, oldElement._owner, oldElement.props); - return newElement; - } - function cloneElement(element, config, children) { - if (element === null || element === undefined) { - throw new Error("React.cloneElement(...): The argument must be a React element, but you passed " + element + "."); - } - var propName; - var props = assign({}, element.props); - var key = element.key; - var ref = element.ref; - var self = element._self; - var source = element._source; - var owner = element._owner; - if (config != null) { - if (hasValidRef(config)) { - ref = config.ref; - owner = ReactCurrentOwner.current; - } - if (hasValidKey(config)) { - { - checkKeyStringCoercion(config.key); - } - key = "" + config.key; - } - var defaultProps; - if (element.type && element.type.defaultProps) { - defaultProps = element.type.defaultProps; - } - for (propName in config) { - if (hasOwnProperty.call(config, propName) && !RESERVED_PROPS.hasOwnProperty(propName)) { - if (config[propName] === undefined && defaultProps !== undefined) { - props[propName] = defaultProps[propName]; - } else { - props[propName] = config[propName]; - } - } - } - } - var childrenLength = arguments.length - 2; - if (childrenLength === 1) { - props.children = children; - } else if (childrenLength > 1) { - var childArray = Array(childrenLength); - for (var i = 0; i < childrenLength; i++) { - childArray[i] = arguments[i + 2]; - } - props.children = childArray; - } - return ReactElement(element.type, key, ref, self, source, owner, props); - } - function isValidElement(object) { - return typeof object === "object" && object !== null && object.$$typeof === REACT_ELEMENT_TYPE; - } - var SEPARATOR = "."; - var SUBSEPARATOR = ":"; - function escape(key) { - var escapeRegex = /[=:]/g; - var escaperLookup = { - "=": "=0", - ":": "=2" - }; - var escapedString = key.replace(escapeRegex, function (match) { - return escaperLookup[match]; - }); - return "$" + escapedString; - } - var didWarnAboutMaps = false; - var userProvidedKeyEscapeRegex = /\/+/g; - function escapeUserProvidedKey(text) { - return text.replace(userProvidedKeyEscapeRegex, "$&/"); - } - function getElementKey(element, index) { - if (typeof element === "object" && element !== null && element.key != null) { - { - checkKeyStringCoercion(element.key); - } - return escape("" + element.key); - } - return index.toString(36); - } - function mapIntoArray(children, array, escapedPrefix, nameSoFar, callback) { - var type = typeof children; - if (type === "undefined" || type === "boolean") { - children = null; - } - var invokeCallback = false; - if (children === null) { - invokeCallback = true; - } else { - switch (type) { - case "string": - case "number": - invokeCallback = true; - break; - case "object": - switch (children.$$typeof) { - case REACT_ELEMENT_TYPE: - case REACT_PORTAL_TYPE: - invokeCallback = true; - } - } - } - if (invokeCallback) { - var _child = children; - var mappedChild = callback(_child); - var childKey = nameSoFar === "" ? SEPARATOR + getElementKey(_child, 0) : nameSoFar; - if (isArray(mappedChild)) { - var escapedChildKey = ""; - if (childKey != null) { - escapedChildKey = escapeUserProvidedKey(childKey) + "/"; - } - mapIntoArray(mappedChild, array, escapedChildKey, "", function (c) { - return c; - }); - } else if (mappedChild != null) { - if (isValidElement(mappedChild)) { - { - if (mappedChild.key && (!_child || _child.key !== mappedChild.key)) { - checkKeyStringCoercion(mappedChild.key); - } - } - mappedChild = cloneAndReplaceKey(mappedChild, escapedPrefix + (mappedChild.key && (!_child || _child.key !== mappedChild.key) ? escapeUserProvidedKey("" + mappedChild.key) + "/" : "") + childKey); - } - array.push(mappedChild); - } - return 1; - } - var child; - var nextName; - var subtreeCount = 0; - var nextNamePrefix = nameSoFar === "" ? SEPARATOR : nameSoFar + SUBSEPARATOR; - if (isArray(children)) { - for (var i = 0; i < children.length; i++) { - child = children[i]; - nextName = nextNamePrefix + getElementKey(child, i); - subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); - } - } else { - var iteratorFn = getIteratorFn(children); - if (typeof iteratorFn === "function") { - var iterableChildren = children; - { - if (iteratorFn === iterableChildren.entries) { - if (!didWarnAboutMaps) { - warn("Using Maps as children is not supported. " + "Use an array of keyed ReactElements instead."); - } - didWarnAboutMaps = true; - } - } - var iterator = iteratorFn.call(iterableChildren); - var step; - var ii = 0; - while (!(step = iterator.next()).done) { - child = step.value; - nextName = nextNamePrefix + getElementKey(child, ii++); - subtreeCount += mapIntoArray(child, array, escapedPrefix, nextName, callback); - } - } else if (type === "object") { - var childrenString = String(children); - throw new Error("Objects are not valid as a React child (found: " + (childrenString === "[object Object]" ? "object with keys {" + Object.keys(children).join(", ") + "}" : childrenString) + "). " + "If you meant to render a collection of children, use an array " + "instead."); - } - } - return subtreeCount; - } - function mapChildren(children, func, context) { - if (children == null) { - return children; - } - var result = []; - var count = 0; - mapIntoArray(children, result, "", "", function (child) { - return func.call(context, child, count++); - }); - return result; - } - function countChildren(children) { - var n = 0; - mapChildren(children, function () { - n++; - }); - return n; - } - function forEachChildren(children, forEachFunc, forEachContext) { - mapChildren(children, function () { - forEachFunc.apply(this, arguments); - }, forEachContext); - } - function toArray(children) { - return mapChildren(children, function (child) { - return child; - }) || []; - } - function onlyChild(children) { - if (!isValidElement(children)) { - throw new Error("React.Children.only expected to receive a single React element child."); - } - return children; - } - function createContext(defaultValue) { - var context = { - $$typeof: REACT_CONTEXT_TYPE, - _currentValue: defaultValue, - _currentValue2: defaultValue, - _threadCount: 0, - Provider: null, - Consumer: null, - _defaultValue: null, - _globalName: null - }; - context.Provider = { - $$typeof: REACT_PROVIDER_TYPE, - _context: context - }; - var hasWarnedAboutUsingNestedContextConsumers = false; - var hasWarnedAboutUsingConsumerProvider = false; - var hasWarnedAboutDisplayNameOnConsumer = false; - { - var Consumer = { - $$typeof: REACT_CONTEXT_TYPE, - _context: context - }; - Object.defineProperties(Consumer, { - Provider: { - get: function () { - if (!hasWarnedAboutUsingConsumerProvider) { - hasWarnedAboutUsingConsumerProvider = true; - error("Rendering is not supported and will be removed in " + "a future major release. Did you mean to render instead?"); - } - return context.Provider; - }, - set: function (_Provider) { - context.Provider = _Provider; - } - }, - _currentValue: { - get: function () { - return context._currentValue; - }, - set: function (_currentValue) { - context._currentValue = _currentValue; - } - }, - _currentValue2: { - get: function () { - return context._currentValue2; - }, - set: function (_currentValue2) { - context._currentValue2 = _currentValue2; - } - }, - _threadCount: { - get: function () { - return context._threadCount; - }, - set: function (_threadCount) { - context._threadCount = _threadCount; - } - }, - Consumer: { - get: function () { - if (!hasWarnedAboutUsingNestedContextConsumers) { - hasWarnedAboutUsingNestedContextConsumers = true; - error("Rendering is not supported and will be removed in " + "a future major release. Did you mean to render instead?"); - } - return context.Consumer; - } - }, - displayName: { - get: function () { - return context.displayName; - }, - set: function (displayName) { - if (!hasWarnedAboutDisplayNameOnConsumer) { - warn("Setting `displayName` on Context.Consumer has no effect. " + "You should set it directly on the context with Context.displayName = '%s'.", displayName); - hasWarnedAboutDisplayNameOnConsumer = true; - } - } - } - }); - context.Consumer = Consumer; - } - { - context._currentRenderer = null; - context._currentRenderer2 = null; - } - return context; - } - var Uninitialized = -1; - var Pending = 0; - var Resolved = 1; - var Rejected = 2; - function lazyInitializer(payload) { - if (payload._status === Uninitialized) { - var ctor = payload._result; - var thenable = ctor(); - thenable.then(function (moduleObject) { - if (payload._status === Pending || payload._status === Uninitialized) { - var resolved = payload; - resolved._status = Resolved; - resolved._result = moduleObject; - } - }, function (error) { - if (payload._status === Pending || payload._status === Uninitialized) { - var rejected = payload; - rejected._status = Rejected; - rejected._result = error; - } - }); - if (payload._status === Uninitialized) { - var pending = payload; - pending._status = Pending; - pending._result = thenable; - } - } - if (payload._status === Resolved) { - var moduleObject = payload._result; - { - if (moduleObject === undefined) { - error("lazy: Expected the result of a dynamic imp" + "ort() call. " + "Instead received: %s\n\nYour code should look like: \n " + "const MyComponent = lazy(() => imp" + "ort('./MyComponent'))\n\n" + "Did you accidentally put curly braces around the import?", moduleObject); - } - } - { - if (!(("default" in moduleObject))) { - error("lazy: Expected the result of a dynamic imp" + "ort() call. " + "Instead received: %s\n\nYour code should look like: \n " + "const MyComponent = lazy(() => imp" + "ort('./MyComponent'))", moduleObject); - } - } - return moduleObject.default; - } else { - throw payload._result; - } - } - function lazy(ctor) { - var payload = { - _status: Uninitialized, - _result: ctor - }; - var lazyType = { - $$typeof: REACT_LAZY_TYPE, - _payload: payload, - _init: lazyInitializer - }; - { - var defaultProps; - var propTypes; - Object.defineProperties(lazyType, { - defaultProps: { - configurable: true, - get: function () { - return defaultProps; - }, - set: function (newDefaultProps) { - error("React.lazy(...): It is not supported to assign `defaultProps` to " + "a lazy component import. Either specify them where the component " + "is defined, or create a wrapping component around it."); - defaultProps = newDefaultProps; - Object.defineProperty(lazyType, "defaultProps", { - enumerable: true - }); - } - }, - propTypes: { - configurable: true, - get: function () { - return propTypes; - }, - set: function (newPropTypes) { - error("React.lazy(...): It is not supported to assign `propTypes` to " + "a lazy component import. Either specify them where the component " + "is defined, or create a wrapping component around it."); - propTypes = newPropTypes; - Object.defineProperty(lazyType, "propTypes", { - enumerable: true - }); - } - } - }); - } - return lazyType; - } - function forwardRef(render) { - { - if (render != null && render.$$typeof === REACT_MEMO_TYPE) { - error("forwardRef requires a render function but received a `memo` " + "component. Instead of forwardRef(memo(...)), use " + "memo(forwardRef(...))."); - } else if (typeof render !== "function") { - error("forwardRef requires a render function but was given %s.", render === null ? "null" : typeof render); - } else { - if (render.length !== 0 && render.length !== 2) { - error("forwardRef render functions accept exactly two parameters: props and ref. %s", render.length === 1 ? "Did you forget to use the ref parameter?" : "Any additional parameter will be undefined."); - } - } - if (render != null) { - if (render.defaultProps != null || render.propTypes != null) { - error("forwardRef render functions do not support propTypes or defaultProps. " + "Did you accidentally pass a React component?"); - } - } - } - var elementType = { - $$typeof: REACT_FORWARD_REF_TYPE, - render: render - }; - { - var ownName; - Object.defineProperty(elementType, "displayName", { - enumerable: false, - configurable: true, - get: function () { - return ownName; - }, - set: function (name) { - ownName = name; - if (!render.name && !render.displayName) { - render.displayName = name; - } - } - }); - } - return elementType; - } - var REACT_MODULE_REFERENCE; - { - REACT_MODULE_REFERENCE = Symbol.for("react.module.reference"); - } - function isValidElementType(type) { - if (typeof type === "string" || typeof type === "function") { - return true; - } - if (type === REACT_FRAGMENT_TYPE || type === REACT_PROFILER_TYPE || enableDebugTracing || type === REACT_STRICT_MODE_TYPE || type === REACT_SUSPENSE_TYPE || type === REACT_SUSPENSE_LIST_TYPE || enableLegacyHidden || type === REACT_OFFSCREEN_TYPE || enableScopeAPI || enableCacheElement || enableTransitionTracing) { - return true; - } - if (typeof type === "object" && type !== null) { - if (type.$$typeof === REACT_LAZY_TYPE || type.$$typeof === REACT_MEMO_TYPE || type.$$typeof === REACT_PROVIDER_TYPE || type.$$typeof === REACT_CONTEXT_TYPE || type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_MODULE_REFERENCE || type.getModuleId !== undefined) { - return true; - } - } - return false; - } - function memo(type, compare) { - { - if (!isValidElementType(type)) { - error("memo: The first argument must be a component. Instead " + "received: %s", type === null ? "null" : typeof type); - } - } - var elementType = { - $$typeof: REACT_MEMO_TYPE, - type: type, - compare: compare === undefined ? null : compare - }; - { - var ownName; - Object.defineProperty(elementType, "displayName", { - enumerable: false, - configurable: true, - get: function () { - return ownName; - }, - set: function (name) { - ownName = name; - if (!type.name && !type.displayName) { - type.displayName = name; - } - } - }); - } - return elementType; - } - function resolveDispatcher() { - var dispatcher = ReactCurrentDispatcher.current; - { - if (dispatcher === null) { - error("Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for" + " one of the following reasons:\n" + "1. You might have mismatching versions of React and the renderer (such as React DOM)\n" + "2. You might be breaking the Rules of Hooks\n" + "3. You might have more than one copy of React in the same app\n" + "See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem."); - } - } - return dispatcher; - } - function useContext(Context) { - var dispatcher = resolveDispatcher(); - { - if (Context._context !== undefined) { - var realContext = Context._context; - if (realContext.Consumer === Context) { - error("Calling useContext(Context.Consumer) is not supported, may cause bugs, and will be " + "removed in a future major release. Did you mean to call useContext(Context) instead?"); - } else if (realContext.Provider === Context) { - error("Calling useContext(Context.Provider) is not supported. " + "Did you mean to call useContext(Context) instead?"); - } - } - } - return dispatcher.useContext(Context); - } - function useState(initialState) { - var dispatcher = resolveDispatcher(); - return dispatcher.useState(initialState); - } - function useReducer(reducer, initialArg, init) { - var dispatcher = resolveDispatcher(); - return dispatcher.useReducer(reducer, initialArg, init); - } - function useRef(initialValue) { - var dispatcher = resolveDispatcher(); - return dispatcher.useRef(initialValue); - } - function useEffect(create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useEffect(create, deps); - } - function useInsertionEffect(create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useInsertionEffect(create, deps); - } - function useLayoutEffect(create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useLayoutEffect(create, deps); - } - function useCallback(callback, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useCallback(callback, deps); - } - function useMemo(create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useMemo(create, deps); - } - function useImperativeHandle(ref, create, deps) { - var dispatcher = resolveDispatcher(); - return dispatcher.useImperativeHandle(ref, create, deps); - } - function useDebugValue(value, formatterFn) { - { - var dispatcher = resolveDispatcher(); - return dispatcher.useDebugValue(value, formatterFn); - } - } - function useTransition() { - var dispatcher = resolveDispatcher(); - return dispatcher.useTransition(); - } - function useDeferredValue(value) { - var dispatcher = resolveDispatcher(); - return dispatcher.useDeferredValue(value); - } - function useId() { - var dispatcher = resolveDispatcher(); - return dispatcher.useId(); - } - function useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot) { - var dispatcher = resolveDispatcher(); - return dispatcher.useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot); - } - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; - function disabledLog() {} - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - } - disabledDepth++; - } - } - function reenableLogs() { - { - disabledDepth--; - if (disabledDepth === 0) { - var props = { - configurable: true, - enumerable: true, - writable: true - }; - Object.defineProperties(console, { - log: assign({}, props, { - value: prevLog - }), - info: assign({}, props, { - value: prevInfo - }), - warn: assign({}, props, { - value: prevWarn - }), - error: assign({}, props, { - value: prevError - }), - group: assign({}, props, { - value: prevGroup - }), - groupCollapsed: assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: assign({}, props, { - value: prevGroupEnd - }) - }); - } - if (disabledDepth < 0) { - error("disabledDepth fell below zero. " + "This is a bug in React. Please file an issue."); - } - } - } - var ReactCurrentDispatcher$1 = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === undefined) { - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = match && match[1] || ""; - } - } - return "\n" + prefix + name; - } - } - var reentry = false; - var componentFrameCache; - { - var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - function describeNativeComponentFrame(fn, construct) { - if (!fn || reentry) { - return ""; - } - { - var frame = componentFrameCache.get(fn); - if (frame !== undefined) { - return frame; - } - } - var control; - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = undefined; - var previousDispatcher; - { - previousDispatcher = ReactCurrentDispatcher$1.current; - ReactCurrentDispatcher$1.current = null; - disableLogs(); - } - try { - if (construct) { - var Fake = function () { - throw Error(); - }; - Object.defineProperty(Fake.prototype, "props", { - set: function () { - throw Error(); - } - }); - if (typeof Reflect === "object" && Reflect.construct) { - try { - Reflect.construct(Fake, []); - } catch (x) { - control = x; - } - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x) { - control = x; - } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x) { - control = x; - } - fn(); - } - } catch (sample) { - if (sample && control && typeof sample.stack === "string") { - var sampleLines = sample.stack.split("\n"); - var controlLines = control.stack.split("\n"); - var s = sampleLines.length - 1; - var c = controlLines.length - 1; - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - c--; - } - for (; s >= 1 && c >= 0; (s--, c--)) { - if (sampleLines[s] !== controlLines[c]) { - if (s !== 1 || c !== 1) { - do { - s--; - c--; - if (c < 0 || sampleLines[s] !== controlLines[c]) { - var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); - if (fn.displayName && _frame.includes("")) { - _frame = _frame.replace("", fn.displayName); - } - { - if (typeof fn === "function") { - componentFrameCache.set(fn, _frame); - } - } - return _frame; - } - } while (s >= 1 && c >= 0); - } - break; - } - } - } - } finally { - reentry = false; - { - ReactCurrentDispatcher$1.current = previousDispatcher; - reenableLogs(); - } - Error.prepareStackTrace = previousPrepareStackTrace; - } - var name = fn ? fn.displayName || fn.name : ""; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; - { - if (typeof fn === "function") { - componentFrameCache.set(fn, syntheticFrame); - } - } - return syntheticFrame; - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false); - } - } - function shouldConstruct(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - if (type == null) { - return ""; - } - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct(type)); - } - } - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - case REACT_MEMO_TYPE: - return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - case REACT_LAZY_TYPE: - { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); - } catch (x) {} - } - } - } - return ""; - } - var loggedTypeFailures = {}; - var ReactDebugCurrentFrame$1 = ReactSharedInternals.ReactDebugCurrentFrame; - function setCurrentlyValidatingElement(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - ReactDebugCurrentFrame$1.setExtraStackFrame(stack); - } else { - ReactDebugCurrentFrame$1.setExtraStackFrame(null); - } - } - } - function checkPropTypes(typeSpecs, values, location, componentName, element) { - { - var has = Function.call.bind(hasOwnProperty); - for (var typeSpecName in typeSpecs) { - if (has(typeSpecs, typeSpecName)) { - var error$1 = void 0; - try { - if (typeof typeSpecs[typeSpecName] !== "function") { - var err = Error((componentName || "React class") + ": " + location + " type `" + typeSpecName + "` is invalid; " + "it must be a function, usually from the `prop-types` package, but received `" + typeof typeSpecs[typeSpecName] + "`." + "This often happens because of typos such as `PropTypes.function` instead of `PropTypes.func`."); - err.name = "Invariant Violation"; - throw err; - } - error$1 = typeSpecs[typeSpecName](values, typeSpecName, componentName, location, null, "SECRET_DO_NOT_PASS_THIS_OR_YOU_WILL_BE_FIRED"); - } catch (ex) { - error$1 = ex; - } - if (error$1 && !(error$1 instanceof Error)) { - setCurrentlyValidatingElement(element); - error("%s: type specification of %s" + " `%s` is invalid; the type checker " + "function must return `null` or an `Error` but returned a %s. " + "You may have forgotten to pass an argument to the type checker " + "creator (arrayOf, instanceOf, objectOf, oneOf, oneOfType, and " + "shape all require an argument).", componentName || "React class", location, typeSpecName, typeof error$1); - setCurrentlyValidatingElement(null); - } - if (error$1 instanceof Error && !((error$1.message in loggedTypeFailures))) { - loggedTypeFailures[error$1.message] = true; - setCurrentlyValidatingElement(element); - error("Failed %s type: %s", location, error$1.message); - setCurrentlyValidatingElement(null); - } - } - } - } - } - function setCurrentlyValidatingElement$1(element) { - { - if (element) { - var owner = element._owner; - var stack = describeUnknownElementTypeFrameInDEV(element.type, element._source, owner ? owner.type : null); - setExtraStackFrame(stack); - } else { - setExtraStackFrame(null); - } - } - } - var propTypesMisspellWarningShown; - { - propTypesMisspellWarningShown = false; - } - function getDeclarationErrorAddendum() { - if (ReactCurrentOwner.current) { - var name = getComponentNameFromType(ReactCurrentOwner.current.type); - if (name) { - return "\n\nCheck the render method of `" + name + "`."; - } - } - return ""; - } - function getSourceInfoErrorAddendum(source) { - if (source !== undefined) { - var fileName = source.fileName.replace(/^.*[\\\/]/, ""); - var lineNumber = source.lineNumber; - return "\n\nCheck your code at " + fileName + ":" + lineNumber + "."; - } - return ""; - } - function getSourceInfoErrorAddendumForProps(elementProps) { - if (elementProps !== null && elementProps !== undefined) { - return getSourceInfoErrorAddendum(elementProps.__source); - } - return ""; - } - var ownerHasKeyUseWarning = {}; - function getCurrentComponentErrorInfo(parentType) { - var info = getDeclarationErrorAddendum(); - if (!info) { - var parentName = typeof parentType === "string" ? parentType : parentType.displayName || parentType.name; - if (parentName) { - info = "\n\nCheck the top-level render call using <" + parentName + ">."; - } - } - return info; - } - function validateExplicitKey(element, parentType) { - if (!element._store || element._store.validated || element.key != null) { - return; - } - element._store.validated = true; - var currentComponentErrorInfo = getCurrentComponentErrorInfo(parentType); - if (ownerHasKeyUseWarning[currentComponentErrorInfo]) { - return; - } - ownerHasKeyUseWarning[currentComponentErrorInfo] = true; - var childOwner = ""; - if (element && element._owner && element._owner !== ReactCurrentOwner.current) { - childOwner = " It was passed a child from " + getComponentNameFromType(element._owner.type) + "."; - } - { - setCurrentlyValidatingElement$1(element); - error("Each child in a list should have a unique \"key\" prop." + "%s%s See https://reactjs.org/link/warning-keys for more information.", currentComponentErrorInfo, childOwner); - setCurrentlyValidatingElement$1(null); - } - } - function validateChildKeys(node, parentType) { - if (typeof node !== "object") { - return; - } - if (isArray(node)) { - for (var i = 0; i < node.length; i++) { - var child = node[i]; - if (isValidElement(child)) { - validateExplicitKey(child, parentType); - } - } - } else if (isValidElement(node)) { - if (node._store) { - node._store.validated = true; - } - } else if (node) { - var iteratorFn = getIteratorFn(node); - if (typeof iteratorFn === "function") { - if (iteratorFn !== node.entries) { - var iterator = iteratorFn.call(node); - var step; - while (!(step = iterator.next()).done) { - if (isValidElement(step.value)) { - validateExplicitKey(step.value, parentType); - } - } - } - } - } - } - function validatePropTypes(element) { - { - var type = element.type; - if (type === null || type === undefined || typeof type === "string") { - return; - } - var propTypes; - if (typeof type === "function") { - propTypes = type.propTypes; - } else if (typeof type === "object" && (type.$$typeof === REACT_FORWARD_REF_TYPE || type.$$typeof === REACT_MEMO_TYPE)) { - propTypes = type.propTypes; - } else { - return; - } - if (propTypes) { - var name = getComponentNameFromType(type); - checkPropTypes(propTypes, element.props, "prop", name, element); - } else if (type.PropTypes !== undefined && !propTypesMisspellWarningShown) { - propTypesMisspellWarningShown = true; - var _name = getComponentNameFromType(type); - error("Component %s declared `PropTypes` instead of `propTypes`. Did you misspell the property assignment?", _name || "Unknown"); - } - if (typeof type.getDefaultProps === "function" && !type.getDefaultProps.isReactClassApproved) { - error("getDefaultProps is only used on classic React.createClass " + "definitions. Use a static property named `defaultProps` instead."); - } - } - } - function validateFragmentProps(fragment) { - { - var keys = Object.keys(fragment.props); - for (var i = 0; i < keys.length; i++) { - var key = keys[i]; - if (key !== "children" && key !== "key") { - setCurrentlyValidatingElement$1(fragment); - error("Invalid prop `%s` supplied to `React.Fragment`. " + "React.Fragment can only have `key` and `children` props.", key); - setCurrentlyValidatingElement$1(null); - break; - } - } - if (fragment.ref !== null) { - setCurrentlyValidatingElement$1(fragment); - error("Invalid attribute `ref` supplied to `React.Fragment`."); - setCurrentlyValidatingElement$1(null); - } - } - } - function createElementWithValidation(type, props, children) { - var validType = isValidElementType(type); - if (!validType) { - var info = ""; - if (type === undefined || typeof type === "object" && type !== null && Object.keys(type).length === 0) { - info += " You likely forgot to export your component from the file " + "it's defined in, or you might have mixed up default and named imports."; - } - var sourceInfo = getSourceInfoErrorAddendumForProps(props); - if (sourceInfo) { - info += sourceInfo; - } else { - info += getDeclarationErrorAddendum(); - } - var typeString; - if (type === null) { - typeString = "null"; - } else if (isArray(type)) { - typeString = "array"; - } else if (type !== undefined && type.$$typeof === REACT_ELEMENT_TYPE) { - typeString = "<" + (getComponentNameFromType(type.type) || "Unknown") + " />"; - info = " Did you accidentally export a JSX literal instead of a component?"; - } else { - typeString = typeof type; - } - { - error("React.createElement: type is invalid -- expected a string (for " + "built-in components) or a class/function (for composite " + "components) but got: %s.%s", typeString, info); - } - } - var element = createElement.apply(this, arguments); - if (element == null) { - return element; - } - if (validType) { - for (var i = 2; i < arguments.length; i++) { - validateChildKeys(arguments[i], type); - } - } - if (type === REACT_FRAGMENT_TYPE) { - validateFragmentProps(element); - } else { - validatePropTypes(element); - } - return element; - } - var didWarnAboutDeprecatedCreateFactory = false; - function createFactoryWithValidation(type) { - var validatedFactory = createElementWithValidation.bind(null, type); - validatedFactory.type = type; - { - if (!didWarnAboutDeprecatedCreateFactory) { - didWarnAboutDeprecatedCreateFactory = true; - warn("React.createFactory() is deprecated and will be removed in " + "a future major release. Consider using JSX " + "or use React.createElement() directly instead."); - } - Object.defineProperty(validatedFactory, "type", { - enumerable: false, - get: function () { - warn("Factory.type is deprecated. Access the class directly " + "before passing it to createFactory."); - Object.defineProperty(this, "type", { - value: type - }); - return type; - } - }); - } - return validatedFactory; - } - function cloneElementWithValidation(element, props, children) { - var newElement = cloneElement.apply(this, arguments); - for (var i = 2; i < arguments.length; i++) { - validateChildKeys(arguments[i], newElement.type); - } - validatePropTypes(newElement); - return newElement; - } - function startTransition(scope, options) { - var prevTransition = ReactCurrentBatchConfig.transition; - ReactCurrentBatchConfig.transition = {}; - var currentTransition = ReactCurrentBatchConfig.transition; - { - ReactCurrentBatchConfig.transition._updatedFibers = new Set(); - } - try { - scope(); - } finally { - ReactCurrentBatchConfig.transition = prevTransition; - { - if (prevTransition === null && currentTransition._updatedFibers) { - var updatedFibersCount = currentTransition._updatedFibers.size; - if (updatedFibersCount > 10) { - warn("Detected a large number of updates inside startTransition. " + "If this is due to a subscription please re-write it to use React provided hooks. " + "Otherwise concurrent mode guarantees are off the table."); - } - currentTransition._updatedFibers.clear(); - } - } - } - } - var didWarnAboutMessageChannel = false; - var enqueueTaskImpl = null; - function enqueueTask(task) { - if (enqueueTaskImpl === null) { - try { - var requireString = ("require" + Math.random()).slice(0, 7); - var nodeRequire = module && module[requireString]; - enqueueTaskImpl = nodeRequire.call(module, "timers").setImmediate; - } catch (_err) { - enqueueTaskImpl = function (callback) { - { - if (didWarnAboutMessageChannel === false) { - didWarnAboutMessageChannel = true; - if (typeof MessageChannel === "undefined") { - error("This browser does not have a MessageChannel implementation, " + "so enqueuing tasks via await act(async () => ...) will fail. " + "Please file an issue at https://github.com/facebook/react/issues " + "if you encounter this warning."); - } - } - } - var channel = new MessageChannel(); - channel.port1.onmessage = callback; - channel.port2.postMessage(undefined); - }; - } - } - return enqueueTaskImpl(task); - } - var actScopeDepth = 0; - var didWarnNoAwaitAct = false; - function act(callback) { - { - var prevActScopeDepth = actScopeDepth; - actScopeDepth++; - if (ReactCurrentActQueue.current === null) { - ReactCurrentActQueue.current = []; - } - var prevIsBatchingLegacy = ReactCurrentActQueue.isBatchingLegacy; - var result; - try { - ReactCurrentActQueue.isBatchingLegacy = true; - result = callback(); - if (!prevIsBatchingLegacy && ReactCurrentActQueue.didScheduleLegacyUpdate) { - var queue = ReactCurrentActQueue.current; - if (queue !== null) { - ReactCurrentActQueue.didScheduleLegacyUpdate = false; - flushActQueue(queue); - } - } - } catch (error) { - popActScope(prevActScopeDepth); - throw error; - } finally { - ReactCurrentActQueue.isBatchingLegacy = prevIsBatchingLegacy; - } - if (result !== null && typeof result === "object" && typeof result.then === "function") { - var thenableResult = result; - var wasAwaited = false; - var thenable = { - then: function (resolve, reject) { - wasAwaited = true; - thenableResult.then(function (returnValue) { - popActScope(prevActScopeDepth); - if (actScopeDepth === 0) { - recursivelyFlushAsyncActWork(returnValue, resolve, reject); - } else { - resolve(returnValue); - } - }, function (error) { - popActScope(prevActScopeDepth); - reject(error); - }); - } - }; - { - if (!didWarnNoAwaitAct && typeof Promise !== "undefined") { - Promise.resolve().then(function () {}).then(function () { - if (!wasAwaited) { - didWarnNoAwaitAct = true; - error("You called act(async () => ...) without await. " + "This could lead to unexpected testing behaviour, " + "interleaving multiple act calls and mixing their " + "scopes. " + "You should - await act(async () => ...);"); - } - }); - } - } - return thenable; - } else { - var returnValue = result; - popActScope(prevActScopeDepth); - if (actScopeDepth === 0) { - var _queue = ReactCurrentActQueue.current; - if (_queue !== null) { - flushActQueue(_queue); - ReactCurrentActQueue.current = null; - } - var _thenable = { - then: function (resolve, reject) { - if (ReactCurrentActQueue.current === null) { - ReactCurrentActQueue.current = []; - recursivelyFlushAsyncActWork(returnValue, resolve, reject); - } else { - resolve(returnValue); - } - } - }; - return _thenable; - } else { - var _thenable2 = { - then: function (resolve, reject) { - resolve(returnValue); - } - }; - return _thenable2; - } - } - } - } - function popActScope(prevActScopeDepth) { - { - if (prevActScopeDepth !== actScopeDepth - 1) { - error("You seem to have overlapping act() calls, this is not supported. " + "Be sure to await previous act() calls before making a new one. "); - } - actScopeDepth = prevActScopeDepth; - } - } - function recursivelyFlushAsyncActWork(returnValue, resolve, reject) { - { - var queue = ReactCurrentActQueue.current; - if (queue !== null) { - try { - flushActQueue(queue); - enqueueTask(function () { - if (queue.length === 0) { - ReactCurrentActQueue.current = null; - resolve(returnValue); - } else { - recursivelyFlushAsyncActWork(returnValue, resolve, reject); - } - }); - } catch (error) { - reject(error); - } - } else { - resolve(returnValue); - } - } - } - var isFlushing = false; - function flushActQueue(queue) { - { - if (!isFlushing) { - isFlushing = true; - var i = 0; - try { - for (; i < queue.length; i++) { - var callback = queue[i]; - do { - callback = callback(true); - } while (callback !== null); - } - queue.length = 0; - } catch (error) { - queue = queue.slice(i + 1); - throw error; - } finally { - isFlushing = false; - } - } - } - } - var createElement$1 = createElementWithValidation; - var cloneElement$1 = cloneElementWithValidation; - var createFactory = createFactoryWithValidation; - var Children = { - map: mapChildren, - forEach: forEachChildren, - count: countChildren, - toArray: toArray, - only: onlyChild - }; - exports.Children = Children; - exports.Component = Component; - exports.Fragment = REACT_FRAGMENT_TYPE; - exports.Profiler = REACT_PROFILER_TYPE; - exports.PureComponent = PureComponent; - exports.StrictMode = REACT_STRICT_MODE_TYPE; - exports.Suspense = REACT_SUSPENSE_TYPE; - exports.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED = ReactSharedInternals; - exports.cloneElement = cloneElement$1; - exports.createContext = createContext; - exports.createElement = createElement$1; - exports.createFactory = createFactory; - exports.createRef = createRef; - exports.forwardRef = forwardRef; - exports.isValidElement = isValidElement; - exports.lazy = lazy; - exports.memo = memo; - exports.startTransition = startTransition; - exports.unstable_act = act; - exports.useCallback = useCallback; - exports.useContext = useContext; - exports.useDebugValue = useDebugValue; - exports.useDeferredValue = useDeferredValue; - exports.useEffect = useEffect; - exports.useId = useId; - exports.useImperativeHandle = useImperativeHandle; - exports.useInsertionEffect = useInsertionEffect; - exports.useLayoutEffect = useLayoutEffect; - exports.useMemo = useMemo; - exports.useReducer = useReducer; - exports.useRef = useRef; - exports.useState = useState; - exports.useSyncExternalStore = useSyncExternalStore; - exports.useTransition = useTransition; - exports.version = ReactVersion; - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === "function") { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); - } - })(); - } - })(react_development, react_development.exports); - var react_developmentExports = react_development.exports; + /** + * @license React + * react.production.min.js + * + * Copyright (c) Facebook, Inc. and its affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + var l=Symbol.for("react.element"),n=Symbol.for("react.portal"),p$1=Symbol.for("react.fragment"),q=Symbol.for("react.strict_mode"),r=Symbol.for("react.profiler"),t=Symbol.for("react.provider"),u=Symbol.for("react.context"),v$1=Symbol.for("react.forward_ref"),w=Symbol.for("react.suspense"),x=Symbol.for("react.memo"),y=Symbol.for("react.lazy"),z$1=Symbol.iterator;function A$1(a){if(null===a||"object"!==typeof a)return null;a=z$1&&a[z$1]||a["@@iterator"];return "function"===typeof a?a:null} + var B$1={isMounted:function(){return !1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},C$1=Object.assign,D$1={};function E$1(a,b,e){this.props=a;this.context=b;this.refs=D$1;this.updater=e||B$1;}E$1.prototype.isReactComponent={}; + E$1.prototype.setState=function(a,b){if("object"!==typeof a&&"function"!==typeof a&&null!=a)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,a,b,"setState");};E$1.prototype.forceUpdate=function(a){this.updater.enqueueForceUpdate(this,a,"forceUpdate");};function F(){}F.prototype=E$1.prototype;function G$1(a,b,e){this.props=a;this.context=b;this.refs=D$1;this.updater=e||B$1;}var H$1=G$1.prototype=new F; + H$1.constructor=G$1;C$1(H$1,E$1.prototype);H$1.isPureReactComponent=!0;var I$1=Array.isArray,J=Object.prototype.hasOwnProperty,K$1={current:null},L$1={key:!0,ref:!0,__self:!0,__source:!0}; + function M$1(a,b,e){var d,c={},k=null,h=null;if(null!=b)for(d in void 0!==b.ref&&(h=b.ref),void 0!==b.key&&(k=""+b.key),b)J.call(b,d)&&!L$1.hasOwnProperty(d)&&(c[d]=b[d]);var g=arguments.length-2;if(1===g)c.children=e;else if(1 0) { - var parentIndex = index - 1 >>> 1; - var parent = heap[parentIndex]; - - if (compare(parent, node) > 0) { - // The parent is larger. Swap positions. - heap[parentIndex] = node; - heap[index] = parent; - index = parentIndex; - } else { - // The parent is smaller. Exit. - return; - } - } - } - - function siftDown(heap, node, i) { - var index = i; - var length = heap.length; - var halfLength = length >>> 1; - - while (index < halfLength) { - var leftIndex = (index + 1) * 2 - 1; - var left = heap[leftIndex]; - var rightIndex = leftIndex + 1; - var right = heap[rightIndex]; // If the left or right node is smaller, swap with the smaller of those. - - if (compare(left, node) < 0) { - if (rightIndex < length && compare(right, left) < 0) { - heap[index] = right; - heap[rightIndex] = node; - index = rightIndex; - } else { - heap[index] = left; - heap[leftIndex] = node; - index = leftIndex; - } - } else if (rightIndex < length && compare(right, node) < 0) { - heap[index] = right; - heap[rightIndex] = node; - index = rightIndex; - } else { - // Neither child is smaller. Exit. - return; - } - } - } - - function compare(a, b) { - // Compare sort index first, then task id. - var diff = a.sortIndex - b.sortIndex; - return diff !== 0 ? diff : a.id - b.id; - } - - // TODO: Use symbols? - var ImmediatePriority = 1; - var UserBlockingPriority = 2; - var NormalPriority = 3; - var LowPriority = 4; - var IdlePriority = 5; - - function markTaskErrored(task, ms) { - } - - /* eslint-disable no-var */ - - var hasPerformanceNow = typeof performance === 'object' && typeof performance.now === 'function'; - - if (hasPerformanceNow) { - var localPerformance = performance; - - exports.unstable_now = function () { - return localPerformance.now(); - }; - } else { - var localDate = Date; - var initialTime = localDate.now(); - - exports.unstable_now = function () { - return localDate.now() - initialTime; - }; - } // Max 31 bit integer. The max integer size in V8 for 32-bit systems. - // Math.pow(2, 30) - 1 - // 0b111111111111111111111111111111 - - - var maxSigned31BitInt = 1073741823; // Times out immediately - - var IMMEDIATE_PRIORITY_TIMEOUT = -1; // Eventually times out - - var USER_BLOCKING_PRIORITY_TIMEOUT = 250; - var NORMAL_PRIORITY_TIMEOUT = 5000; - var LOW_PRIORITY_TIMEOUT = 10000; // Never times out - - var IDLE_PRIORITY_TIMEOUT = maxSigned31BitInt; // Tasks are stored on a min heap - - var taskQueue = []; - var timerQueue = []; // Incrementing id counter. Used to maintain insertion order. - - var taskIdCounter = 1; // Pausing the scheduler is useful for debugging. - var currentTask = null; - var currentPriorityLevel = NormalPriority; // This is set while performing work, to prevent re-entrance. - - var isPerformingWork = false; - var isHostCallbackScheduled = false; - var isHostTimeoutScheduled = false; // Capture local references to native APIs, in case a polyfill overrides them. - - var localSetTimeout = typeof setTimeout === 'function' ? setTimeout : null; - var localClearTimeout = typeof clearTimeout === 'function' ? clearTimeout : null; - var localSetImmediate = typeof setImmediate !== 'undefined' ? setImmediate : null; // IE and Node.js + jsdom - - typeof navigator !== 'undefined' && navigator.scheduling !== undefined && navigator.scheduling.isInputPending !== undefined ? navigator.scheduling.isInputPending.bind(navigator.scheduling) : null; - - function advanceTimers(currentTime) { - // Check for tasks that are no longer delayed and add them to the queue. - var timer = peek(timerQueue); - - while (timer !== null) { - if (timer.callback === null) { - // Timer was cancelled. - pop(timerQueue); - } else if (timer.startTime <= currentTime) { - // Timer fired. Transfer to the task queue. - pop(timerQueue); - timer.sortIndex = timer.expirationTime; - push(taskQueue, timer); - } else { - // Remaining timers are pending. - return; - } - - timer = peek(timerQueue); - } - } - - function handleTimeout(currentTime) { - isHostTimeoutScheduled = false; - advanceTimers(currentTime); - - if (!isHostCallbackScheduled) { - if (peek(taskQueue) !== null) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } else { - var firstTimer = peek(timerQueue); - - if (firstTimer !== null) { - requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); - } - } - } - } - - function flushWork(hasTimeRemaining, initialTime) { - - - isHostCallbackScheduled = false; - - if (isHostTimeoutScheduled) { - // We scheduled a timeout but it's no longer needed. Cancel it. - isHostTimeoutScheduled = false; - cancelHostTimeout(); - } - - isPerformingWork = true; - var previousPriorityLevel = currentPriorityLevel; - - try { - var currentTime; if (enableProfiling) ; else { - // No catch in prod code path. - return workLoop(hasTimeRemaining, initialTime); - } - } finally { - currentTask = null; - currentPriorityLevel = previousPriorityLevel; - isPerformingWork = false; - } - } - - function workLoop(hasTimeRemaining, initialTime) { - var currentTime = initialTime; - advanceTimers(currentTime); - currentTask = peek(taskQueue); - - while (currentTask !== null && !(enableSchedulerDebugging )) { - if (currentTask.expirationTime > currentTime && (!hasTimeRemaining || shouldYieldToHost())) { - // This currentTask hasn't expired, and we've reached the deadline. - break; - } - - var callback = currentTask.callback; - - if (typeof callback === 'function') { - currentTask.callback = null; - currentPriorityLevel = currentTask.priorityLevel; - var didUserCallbackTimeout = currentTask.expirationTime <= currentTime; - - var continuationCallback = callback(didUserCallbackTimeout); - currentTime = exports.unstable_now(); - - if (typeof continuationCallback === 'function') { - currentTask.callback = continuationCallback; - } else { - - if (currentTask === peek(taskQueue)) { - pop(taskQueue); - } - } - - advanceTimers(currentTime); - } else { - pop(taskQueue); - } - - currentTask = peek(taskQueue); - } // Return whether there's additional work - - - if (currentTask !== null) { - return true; - } else { - var firstTimer = peek(timerQueue); - - if (firstTimer !== null) { - requestHostTimeout(handleTimeout, firstTimer.startTime - currentTime); - } - - return false; - } - } - - function unstable_runWithPriority(priorityLevel, eventHandler) { - switch (priorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - case LowPriority: - case IdlePriority: - break; - - default: - priorityLevel = NormalPriority; - } - - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = priorityLevel; - - try { - return eventHandler(); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - } - - function unstable_next(eventHandler) { - var priorityLevel; - - switch (currentPriorityLevel) { - case ImmediatePriority: - case UserBlockingPriority: - case NormalPriority: - // Shift down to normal priority - priorityLevel = NormalPriority; - break; - - default: - // Anything lower than normal priority should remain at the current level. - priorityLevel = currentPriorityLevel; - break; - } - - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = priorityLevel; - - try { - return eventHandler(); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - } - - function unstable_wrapCallback(callback) { - var parentPriorityLevel = currentPriorityLevel; - return function () { - // This is a fork of runWithPriority, inlined for performance. - var previousPriorityLevel = currentPriorityLevel; - currentPriorityLevel = parentPriorityLevel; - - try { - return callback.apply(this, arguments); - } finally { - currentPriorityLevel = previousPriorityLevel; - } - }; - } - - function unstable_scheduleCallback(priorityLevel, callback, options) { - var currentTime = exports.unstable_now(); - var startTime; - - if (typeof options === 'object' && options !== null) { - var delay = options.delay; - - if (typeof delay === 'number' && delay > 0) { - startTime = currentTime + delay; - } else { - startTime = currentTime; - } - } else { - startTime = currentTime; - } - - var timeout; - - switch (priorityLevel) { - case ImmediatePriority: - timeout = IMMEDIATE_PRIORITY_TIMEOUT; - break; - - case UserBlockingPriority: - timeout = USER_BLOCKING_PRIORITY_TIMEOUT; - break; - - case IdlePriority: - timeout = IDLE_PRIORITY_TIMEOUT; - break; - - case LowPriority: - timeout = LOW_PRIORITY_TIMEOUT; - break; - - case NormalPriority: - default: - timeout = NORMAL_PRIORITY_TIMEOUT; - break; - } - - var expirationTime = startTime + timeout; - var newTask = { - id: taskIdCounter++, - callback: callback, - priorityLevel: priorityLevel, - startTime: startTime, - expirationTime: expirationTime, - sortIndex: -1 - }; - - if (startTime > currentTime) { - // This is a delayed task. - newTask.sortIndex = startTime; - push(timerQueue, newTask); - - if (peek(taskQueue) === null && newTask === peek(timerQueue)) { - // All tasks are delayed, and this is the task with the earliest delay. - if (isHostTimeoutScheduled) { - // Cancel an existing timeout. - cancelHostTimeout(); - } else { - isHostTimeoutScheduled = true; - } // Schedule a timeout. - - - requestHostTimeout(handleTimeout, startTime - currentTime); - } - } else { - newTask.sortIndex = expirationTime; - push(taskQueue, newTask); - // wait until the next time we yield. - - - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } - } - - return newTask; - } - - function unstable_pauseExecution() { - } - - function unstable_continueExecution() { - - if (!isHostCallbackScheduled && !isPerformingWork) { - isHostCallbackScheduled = true; - requestHostCallback(flushWork); - } - } - - function unstable_getFirstCallbackNode() { - return peek(taskQueue); - } - - function unstable_cancelCallback(task) { - // remove from the queue because you can't remove arbitrary nodes from an - // array based heap, only the first one.) - - - task.callback = null; - } - - function unstable_getCurrentPriorityLevel() { - return currentPriorityLevel; - } - - var isMessageLoopRunning = false; - var scheduledHostCallback = null; - var taskTimeoutID = -1; // Scheduler periodically yields in case there is other work on the main - // thread, like user events. By default, it yields multiple times per frame. - // It does not attempt to align with frame boundaries, since most tasks don't - // need to be frame aligned; for those that do, use requestAnimationFrame. - - var frameInterval = frameYieldMs; - var startTime = -1; - - function shouldYieldToHost() { - var timeElapsed = exports.unstable_now() - startTime; - - if (timeElapsed < frameInterval) { - // The main thread has only been blocked for a really short amount of time; - // smaller than a single frame. Don't yield yet. - return false; - } // The main thread has been blocked for a non-negligible amount of time. We - - - return true; - } - - function requestPaint() { - - } - - function forceFrameRate(fps) { - if (fps < 0 || fps > 125) { - // Using console['error'] to evade Babel and ESLint - console['error']('forceFrameRate takes a positive int between 0 and 125, ' + 'forcing frame rates higher than 125 fps is not supported'); - return; - } - - if (fps > 0) { - frameInterval = Math.floor(1000 / fps); - } else { - // reset the framerate - frameInterval = frameYieldMs; - } - } - - var performWorkUntilDeadline = function () { - if (scheduledHostCallback !== null) { - var currentTime = exports.unstable_now(); // Keep track of the start time so we can measure how long the main thread - // has been blocked. - - startTime = currentTime; - var hasTimeRemaining = true; // If a scheduler task throws, exit the current browser task so the - // error can be observed. - // - // Intentionally not using a try-catch, since that makes some debugging - // techniques harder. Instead, if `scheduledHostCallback` errors, then - // `hasMoreWork` will remain true, and we'll continue the work loop. - - var hasMoreWork = true; - - try { - hasMoreWork = scheduledHostCallback(hasTimeRemaining, currentTime); - } finally { - if (hasMoreWork) { - // If there's more work, schedule the next message event at the end - // of the preceding one. - schedulePerformWorkUntilDeadline(); - } else { - isMessageLoopRunning = false; - scheduledHostCallback = null; - } - } - } else { - isMessageLoopRunning = false; - } // Yielding to the browser will give it a chance to paint, so we can - }; - - var schedulePerformWorkUntilDeadline; - - if (typeof localSetImmediate === 'function') { - // Node.js and old IE. - // There's a few reasons for why we prefer setImmediate. - // - // Unlike MessageChannel, it doesn't prevent a Node.js process from exiting. - // (Even though this is a DOM fork of the Scheduler, you could get here - // with a mix of Node.js 15+, which has a MessageChannel, and jsdom.) - // https://github.com/facebook/react/issues/20756 - // - // But also, it runs earlier which is the semantic we want. - // If other browsers ever implement it, it's better to use it. - // Although both of these would be inferior to native scheduling. - schedulePerformWorkUntilDeadline = function () { - localSetImmediate(performWorkUntilDeadline); - }; - } else if (typeof MessageChannel !== 'undefined') { - // DOM and Worker environments. - // We prefer MessageChannel because of the 4ms setTimeout clamping. - var channel = new MessageChannel(); - var port = channel.port2; - channel.port1.onmessage = performWorkUntilDeadline; - - schedulePerformWorkUntilDeadline = function () { - port.postMessage(null); - }; - } else { - // We should only fallback here in non-browser environments. - schedulePerformWorkUntilDeadline = function () { - localSetTimeout(performWorkUntilDeadline, 0); - }; - } - - function requestHostCallback(callback) { - scheduledHostCallback = callback; - - if (!isMessageLoopRunning) { - isMessageLoopRunning = true; - schedulePerformWorkUntilDeadline(); - } - } - - function requestHostTimeout(callback, ms) { - taskTimeoutID = localSetTimeout(function () { - callback(exports.unstable_now()); - }, ms); - } - - function cancelHostTimeout() { - localClearTimeout(taskTimeoutID); - taskTimeoutID = -1; - } - - var unstable_requestPaint = requestPaint; - var unstable_Profiling = null; - - exports.unstable_IdlePriority = IdlePriority; - exports.unstable_ImmediatePriority = ImmediatePriority; - exports.unstable_LowPriority = LowPriority; - exports.unstable_NormalPriority = NormalPriority; - exports.unstable_Profiling = unstable_Profiling; - exports.unstable_UserBlockingPriority = UserBlockingPriority; - exports.unstable_cancelCallback = unstable_cancelCallback; - exports.unstable_continueExecution = unstable_continueExecution; - exports.unstable_forceFrameRate = forceFrameRate; - exports.unstable_getCurrentPriorityLevel = unstable_getCurrentPriorityLevel; - exports.unstable_getFirstCallbackNode = unstable_getFirstCallbackNode; - exports.unstable_next = unstable_next; - exports.unstable_pauseExecution = unstable_pauseExecution; - exports.unstable_requestPaint = unstable_requestPaint; - exports.unstable_runWithPriority = unstable_runWithPriority; - exports.unstable_scheduleCallback = unstable_scheduleCallback; - exports.unstable_shouldYield = shouldYieldToHost; - exports.unstable_wrapCallback = unstable_wrapCallback; - /* global __REACT_DEVTOOLS_GLOBAL_HOOK__ */ - if ( - typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' && - typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop === - 'function' - ) { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(new Error()); - } - - })(); - } - } (scheduler_development)); + function f(a,b){var c=a.length;a.push(b);a:for(;0>>1,e=a[d];if(0>>1;dg(C,c))ng(x,C)?(a[d]=x,a[n]=c,d=n):(a[d]=C,a[m]=c,d=m);else if(ng(x,c))a[d]=x,a[n]=c,d=n;else break a}}return b} + function g(a,b){var c=a.sortIndex-b.sortIndex;return 0!==c?c:a.id-b.id}if("object"===typeof performance&&"function"===typeof performance.now){var l=performance;exports.unstable_now=function(){return l.now()};}else {var p=Date,q=p.now();exports.unstable_now=function(){return p.now()-q};}var r=[],t=[],u=1,v=null,y=3,z=!1,A=!1,B=!1,D="function"===typeof setTimeout?setTimeout:null,E="function"===typeof clearTimeout?clearTimeout:null,F="undefined"!==typeof setImmediate?setImmediate:null; + "undefined"!==typeof navigator&&void 0!==navigator.scheduling&&void 0!==navigator.scheduling.isInputPending&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function G(a){for(var b=h(t);null!==b;){if(null===b.callback)k(t);else if(b.startTime<=a)k(t),b.sortIndex=b.expirationTime,f(r,b);else break;b=h(t);}}function H(a){B=!1;G(a);if(!A)if(null!==h(r))A=!0,I(J);else {var b=h(t);null!==b&&K(H,b.startTime-a);}} + function J(a,b){A=!1;B&&(B=!1,E(L),L=-1);z=!0;var c=y;try{G(b);for(v=h(r);null!==v&&(!(v.expirationTime>b)||a&&!M());){var d=v.callback;if("function"===typeof d){v.callback=null;y=v.priorityLevel;var e=d(v.expirationTime<=b);b=exports.unstable_now();"function"===typeof e?v.callback=e:v===h(r)&&k(r);G(b);}else k(r);v=h(r);}if(null!==v)var w=!0;else {var m=h(t);null!==m&&K(H,m.startTime-b);w=!1;}return w}finally{v=null,y=c,z=!1;}}var N=!1,O=null,L=-1,P=5,Q=-1; + function M(){return exports.unstable_now()-Qa||125d?(a.sortIndex=c,f(t,a),null===h(r)&&a===h(t)&&(B?(E(L),L=-1):B=!0,K(H,c-d))):(a.sortIndex=e,f(r,a),A||z||(A=!0,I(J)));return a}; + exports.unstable_shouldYield=M;exports.unstable_wrapCallback=function(a){var b=y;return function(){var c=y;y=b;try{return a.apply(this,arguments)}finally{y=c;}}}; + } (scheduler_production_min)); { - scheduler.exports = scheduler_development; + scheduler.exports = scheduler_production_min; } var schedulerExports = scheduler.exports; - { - (function () { - if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== "undefined" && typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart === "function") { - __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(new Error()); - } - var React = reactExports; - var Scheduler = schedulerExports; - var ReactSharedInternals = React.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED; - var suppressWarning = false; - function setSuppressWarning(newSuppressWarning) { - { - suppressWarning = newSuppressWarning; - } - } - function warn(format) { - { - if (!suppressWarning) { - for (var _len = arguments.length, args = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { - args[_key - 1] = arguments[_key]; - } - printWarning("warn", format, args); - } - } - } - function error(format) { - { - if (!suppressWarning) { - for (var _len2 = arguments.length, args = new Array(_len2 > 1 ? _len2 - 1 : 0), _key2 = 1; _key2 < _len2; _key2++) { - args[_key2 - 1] = arguments[_key2]; - } - printWarning("error", format, args); - } - } - } - function printWarning(level, format, args) { - { - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var stack = ReactDebugCurrentFrame.getStackAddendum(); - if (stack !== "") { - format += "%s"; - args = args.concat([stack]); - } - var argsWithFormat = args.map(function (item) { - return String(item); - }); - argsWithFormat.unshift("Warning: " + format); - Function.prototype.apply.call(console[level], console, argsWithFormat); - } - } - var FunctionComponent = 0; - var ClassComponent = 1; - var IndeterminateComponent = 2; - var HostRoot = 3; - var HostPortal = 4; - var HostComponent = 5; - var HostText = 6; - var Fragment = 7; - var Mode = 8; - var ContextConsumer = 9; - var ContextProvider = 10; - var ForwardRef = 11; - var Profiler = 12; - var SuspenseComponent = 13; - var MemoComponent = 14; - var SimpleMemoComponent = 15; - var LazyComponent = 16; - var IncompleteClassComponent = 17; - var DehydratedFragment = 18; - var SuspenseListComponent = 19; - var ScopeComponent = 21; - var OffscreenComponent = 22; - var LegacyHiddenComponent = 23; - var CacheComponent = 24; - var TracingMarkerComponent = 25; - var enableClientRenderFallbackOnTextMismatch = true; - var enableNewReconciler = false; - var enableLazyContextPropagation = false; - var enableLegacyHidden = false; - var enableSuspenseAvoidThisFallback = false; - var disableCommentsAsDOMContainers = true; - var enableCustomElementPropertySupport = false; - var warnAboutStringRefs = false; - var enableSchedulingProfiler = true; - var enableProfilerTimer = true; - var enableProfilerCommitHooks = true; - var allNativeEvents = new Set(); - var registrationNameDependencies = {}; - var possibleRegistrationNames = {}; - function registerTwoPhaseEvent(registrationName, dependencies) { - registerDirectEvent(registrationName, dependencies); - registerDirectEvent(registrationName + "Capture", dependencies); - } - function registerDirectEvent(registrationName, dependencies) { - { - if (registrationNameDependencies[registrationName]) { - error("EventRegistry: More than one plugin attempted to publish the same " + "registration name, `%s`.", registrationName); - } - } - registrationNameDependencies[registrationName] = dependencies; - { - var lowerCasedName = registrationName.toLowerCase(); - possibleRegistrationNames[lowerCasedName] = registrationName; - if (registrationName === "onDoubleClick") { - possibleRegistrationNames.ondblclick = registrationName; - } - } - for (var i = 0; i < dependencies.length; i++) { - allNativeEvents.add(dependencies[i]); - } - } - var canUseDOM = !!(typeof window !== "undefined" && typeof window.document !== "undefined" && typeof window.document.createElement !== "undefined"); - var hasOwnProperty = Object.prototype.hasOwnProperty; - function typeName(value) { - { - var hasToStringTag = typeof Symbol === "function" && Symbol.toStringTag; - var type = hasToStringTag && value[Symbol.toStringTag] || value.constructor.name || "Object"; - return type; - } - } - function willCoercionThrow(value) { - { - try { - testStringCoercion(value); - return false; - } catch (e) { - return true; - } - } - } - function testStringCoercion(value) { - return "" + value; - } - function checkAttributeStringCoercion(value, attributeName) { - { - if (willCoercionThrow(value)) { - error("The provided `%s` attribute is an unsupported type %s." + " This value must be coerced to a string before before using it here.", attributeName, typeName(value)); - return testStringCoercion(value); - } - } - } - function checkKeyStringCoercion(value) { - { - if (willCoercionThrow(value)) { - error("The provided key is an unsupported type %s." + " This value must be coerced to a string before before using it here.", typeName(value)); - return testStringCoercion(value); - } - } - } - function checkPropStringCoercion(value, propName) { - { - if (willCoercionThrow(value)) { - error("The provided `%s` prop is an unsupported type %s." + " This value must be coerced to a string before before using it here.", propName, typeName(value)); - return testStringCoercion(value); - } - } - } - function checkCSSPropertyStringCoercion(value, propName) { - { - if (willCoercionThrow(value)) { - error("The provided `%s` CSS property is an unsupported type %s." + " This value must be coerced to a string before before using it here.", propName, typeName(value)); - return testStringCoercion(value); - } - } - } - function checkHtmlStringCoercion(value) { - { - if (willCoercionThrow(value)) { - error("The provided HTML markup uses a value of unsupported type %s." + " This value must be coerced to a string before before using it here.", typeName(value)); - return testStringCoercion(value); - } - } - } - function checkFormFieldValueStringCoercion(value) { - { - if (willCoercionThrow(value)) { - error("Form field values (value, checked, defaultValue, or defaultChecked props)" + " must be strings, not %s." + " This value must be coerced to a string before before using it here.", typeName(value)); - return testStringCoercion(value); - } - } - } - var RESERVED = 0; - var STRING = 1; - var BOOLEANISH_STRING = 2; - var BOOLEAN = 3; - var OVERLOADED_BOOLEAN = 4; - var NUMERIC = 5; - var POSITIVE_NUMERIC = 6; - var ATTRIBUTE_NAME_START_CHAR = ":A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD"; - var ATTRIBUTE_NAME_CHAR = ATTRIBUTE_NAME_START_CHAR + "\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040"; - var VALID_ATTRIBUTE_NAME_REGEX = new RegExp("^[" + ATTRIBUTE_NAME_START_CHAR + "][" + ATTRIBUTE_NAME_CHAR + "]*$"); - var illegalAttributeNameCache = {}; - var validatedAttributeNameCache = {}; - function isAttributeNameSafe(attributeName) { - if (hasOwnProperty.call(validatedAttributeNameCache, attributeName)) { - return true; - } - if (hasOwnProperty.call(illegalAttributeNameCache, attributeName)) { - return false; - } - if (VALID_ATTRIBUTE_NAME_REGEX.test(attributeName)) { - validatedAttributeNameCache[attributeName] = true; - return true; - } - illegalAttributeNameCache[attributeName] = true; - { - error("Invalid attribute name: `%s`", attributeName); - } - return false; - } - function shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag) { - if (propertyInfo !== null) { - return propertyInfo.type === RESERVED; - } - if (isCustomComponentTag) { - return false; - } - if (name.length > 2 && (name[0] === "o" || name[0] === "O") && (name[1] === "n" || name[1] === "N")) { - return true; - } - return false; - } - function shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag) { - if (propertyInfo !== null && propertyInfo.type === RESERVED) { - return false; - } - switch (typeof value) { - case "function": - case "symbol": - return true; - case "boolean": - { - if (isCustomComponentTag) { - return false; - } - if (propertyInfo !== null) { - return !propertyInfo.acceptsBooleans; - } else { - var prefix = name.toLowerCase().slice(0, 5); - return prefix !== "data-" && prefix !== "aria-"; - } - } - default: - return false; - } - } - function shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag) { - if (value === null || typeof value === "undefined") { - return true; - } - if (shouldRemoveAttributeWithWarning(name, value, propertyInfo, isCustomComponentTag)) { - return true; - } - if (isCustomComponentTag) { - return false; - } - if (propertyInfo !== null) { - switch (propertyInfo.type) { - case BOOLEAN: - return !value; - case OVERLOADED_BOOLEAN: - return value === false; - case NUMERIC: - return isNaN(value); - case POSITIVE_NUMERIC: - return isNaN(value) || value < 1; - } - } - return false; - } - function getPropertyInfo(name) { - return properties.hasOwnProperty(name) ? properties[name] : null; - } - function PropertyInfoRecord(name, type, mustUseProperty, attributeName, attributeNamespace, sanitizeURL, removeEmptyString) { - this.acceptsBooleans = type === BOOLEANISH_STRING || type === BOOLEAN || type === OVERLOADED_BOOLEAN; - this.attributeName = attributeName; - this.attributeNamespace = attributeNamespace; - this.mustUseProperty = mustUseProperty; - this.propertyName = name; - this.type = type; - this.sanitizeURL = sanitizeURL; - this.removeEmptyString = removeEmptyString; - } - var properties = {}; - var reservedProps = ["children", "dangerouslySetInnerHTML", "defaultValue", "defaultChecked", "innerHTML", "suppressContentEditableWarning", "suppressHydrationWarning", "style"]; - reservedProps.forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, RESERVED, false, name, null, false, false); - }); - [["acceptCharset", "accept-charset"], ["className", "class"], ["htmlFor", "for"], ["httpEquiv", "http-equiv"]].forEach(function (_ref) { - var name = _ref[0], attributeName = _ref[1]; - properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, null, false, false); - }); - ["contentEditable", "draggable", "spellCheck", "value"].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, name.toLowerCase(), null, false, false); - }); - ["autoReverse", "externalResourcesRequired", "focusable", "preserveAlpha"].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, BOOLEANISH_STRING, false, name, null, false, false); - }); - ["allowFullScreen", "async", "autoFocus", "autoPlay", "controls", "default", "defer", "disabled", "disablePictureInPicture", "disableRemotePlayback", "formNoValidate", "hidden", "loop", "noModule", "noValidate", "open", "playsInline", "readOnly", "required", "reversed", "scoped", "seamless", "itemScope"].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, BOOLEAN, false, name.toLowerCase(), null, false, false); - }); - ["checked", "multiple", "muted", "selected"].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, BOOLEAN, true, name, null, false, false); - }); - ["capture", "download"].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, OVERLOADED_BOOLEAN, false, name, null, false, false); - }); - ["cols", "rows", "size", "span"].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, POSITIVE_NUMERIC, false, name, null, false, false); - }); - ["rowSpan", "start"].forEach(function (name) { - properties[name] = new PropertyInfoRecord(name, NUMERIC, false, name.toLowerCase(), null, false, false); - }); - var CAMELIZE = /[\-\:]([a-z])/g; - var capitalize = function (token) { - return token[1].toUpperCase(); - }; - ["accent-height", "alignment-baseline", "arabic-form", "baseline-shift", "cap-height", "clip-path", "clip-rule", "color-interpolation", "color-interpolation-filters", "color-profile", "color-rendering", "dominant-baseline", "enable-background", "fill-opacity", "fill-rule", "flood-color", "flood-opacity", "font-family", "font-size", "font-size-adjust", "font-stretch", "font-style", "font-variant", "font-weight", "glyph-name", "glyph-orientation-horizontal", "glyph-orientation-vertical", "horiz-adv-x", "horiz-origin-x", "image-rendering", "letter-spacing", "lighting-color", "marker-end", "marker-mid", "marker-start", "overline-position", "overline-thickness", "paint-order", "panose-1", "pointer-events", "rendering-intent", "shape-rendering", "stop-color", "stop-opacity", "strikethrough-position", "strikethrough-thickness", "stroke-dasharray", "stroke-dashoffset", "stroke-linecap", "stroke-linejoin", "stroke-miterlimit", "stroke-opacity", "stroke-width", "text-anchor", "text-decoration", "text-rendering", "underline-position", "underline-thickness", "unicode-bidi", "unicode-range", "units-per-em", "v-alphabetic", "v-hanging", "v-ideographic", "v-mathematical", "vector-effect", "vert-adv-y", "vert-origin-x", "vert-origin-y", "word-spacing", "writing-mode", "xmlns:xlink", "x-height"].forEach(function (attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, null, false, false); - }); - ["xlink:actuate", "xlink:arcrole", "xlink:role", "xlink:show", "xlink:title", "xlink:type"].forEach(function (attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, "http://www.w3.org/1999/xlink", false, false); - }); - ["xml:base", "xml:lang", "xml:space"].forEach(function (attributeName) { - var name = attributeName.replace(CAMELIZE, capitalize); - properties[name] = new PropertyInfoRecord(name, STRING, false, attributeName, "http://www.w3.org/XML/1998/namespace", false, false); - }); - ["tabIndex", "crossOrigin"].forEach(function (attributeName) { - properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, attributeName.toLowerCase(), null, false, false); - }); - var xlinkHref = "xlinkHref"; - properties[xlinkHref] = new PropertyInfoRecord("xlinkHref", STRING, false, "xlink:href", "http://www.w3.org/1999/xlink", true, false); - ["src", "href", "action", "formAction"].forEach(function (attributeName) { - properties[attributeName] = new PropertyInfoRecord(attributeName, STRING, false, attributeName.toLowerCase(), null, true, true); - }); - var isJavaScriptProtocol = /^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*\:/i; - var didWarn = false; - function sanitizeURL(url) { - { - if (!didWarn && isJavaScriptProtocol.test(url)) { - didWarn = true; - error("A future version of React will block javascript: URLs as a security precaution. " + "Use event handlers instead if you can. If you need to generate unsafe HTML try " + "using dangerouslySetInnerHTML instead. React was passed %s.", JSON.stringify(url)); - } - } - } - function getValueForProperty(node, name, expected, propertyInfo) { - { - if (propertyInfo.mustUseProperty) { - var propertyName = propertyInfo.propertyName; - return node[propertyName]; - } else { - { - checkAttributeStringCoercion(expected, name); - } - if (propertyInfo.sanitizeURL) { - sanitizeURL("" + expected); - } - var attributeName = propertyInfo.attributeName; - var stringValue = null; - if (propertyInfo.type === OVERLOADED_BOOLEAN) { - if (node.hasAttribute(attributeName)) { - var value = node.getAttribute(attributeName); - if (value === "") { - return true; - } - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - return value; - } - if (value === "" + expected) { - return expected; - } - return value; - } - } else if (node.hasAttribute(attributeName)) { - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - return node.getAttribute(attributeName); - } - if (propertyInfo.type === BOOLEAN) { - return expected; - } - stringValue = node.getAttribute(attributeName); - } - if (shouldRemoveAttribute(name, expected, propertyInfo, false)) { - return stringValue === null ? expected : stringValue; - } else if (stringValue === "" + expected) { - return expected; - } else { - return stringValue; - } - } - } - } - function getValueForAttribute(node, name, expected, isCustomComponentTag) { - { - if (!isAttributeNameSafe(name)) { - return; - } - if (!node.hasAttribute(name)) { - return expected === undefined ? undefined : null; - } - var value = node.getAttribute(name); - { - checkAttributeStringCoercion(expected, name); - } - if (value === "" + expected) { - return expected; - } - return value; - } - } - function setValueForProperty(node, name, value, isCustomComponentTag) { - var propertyInfo = getPropertyInfo(name); - if (shouldIgnoreAttribute(name, propertyInfo, isCustomComponentTag)) { - return; - } - if (shouldRemoveAttribute(name, value, propertyInfo, isCustomComponentTag)) { - value = null; - } - if (isCustomComponentTag || propertyInfo === null) { - if (isAttributeNameSafe(name)) { - var _attributeName = name; - if (value === null) { - node.removeAttribute(_attributeName); - } else { - { - checkAttributeStringCoercion(value, name); - } - node.setAttribute(_attributeName, "" + value); - } - } - return; - } - var mustUseProperty = propertyInfo.mustUseProperty; - if (mustUseProperty) { - var propertyName = propertyInfo.propertyName; - if (value === null) { - var type = propertyInfo.type; - node[propertyName] = type === BOOLEAN ? false : ""; - } else { - node[propertyName] = value; - } - return; - } - var attributeName = propertyInfo.attributeName, attributeNamespace = propertyInfo.attributeNamespace; - if (value === null) { - node.removeAttribute(attributeName); - } else { - var _type = propertyInfo.type; - var attributeValue; - if (_type === BOOLEAN || _type === OVERLOADED_BOOLEAN && value === true) { - attributeValue = ""; - } else { - { - { - checkAttributeStringCoercion(value, attributeName); - } - attributeValue = "" + value; - } - if (propertyInfo.sanitizeURL) { - sanitizeURL(attributeValue.toString()); - } - } - if (attributeNamespace) { - node.setAttributeNS(attributeNamespace, attributeName, attributeValue); - } else { - node.setAttribute(attributeName, attributeValue); - } - } - } - var REACT_ELEMENT_TYPE = Symbol.for("react.element"); - var REACT_PORTAL_TYPE = Symbol.for("react.portal"); - var REACT_FRAGMENT_TYPE = Symbol.for("react.fragment"); - var REACT_STRICT_MODE_TYPE = Symbol.for("react.strict_mode"); - var REACT_PROFILER_TYPE = Symbol.for("react.profiler"); - var REACT_PROVIDER_TYPE = Symbol.for("react.provider"); - var REACT_CONTEXT_TYPE = Symbol.for("react.context"); - var REACT_FORWARD_REF_TYPE = Symbol.for("react.forward_ref"); - var REACT_SUSPENSE_TYPE = Symbol.for("react.suspense"); - var REACT_SUSPENSE_LIST_TYPE = Symbol.for("react.suspense_list"); - var REACT_MEMO_TYPE = Symbol.for("react.memo"); - var REACT_LAZY_TYPE = Symbol.for("react.lazy"); - var REACT_SCOPE_TYPE = Symbol.for("react.scope"); - var REACT_DEBUG_TRACING_MODE_TYPE = Symbol.for("react.debug_trace_mode"); - var REACT_OFFSCREEN_TYPE = Symbol.for("react.offscreen"); - var REACT_LEGACY_HIDDEN_TYPE = Symbol.for("react.legacy_hidden"); - var REACT_CACHE_TYPE = Symbol.for("react.cache"); - var REACT_TRACING_MARKER_TYPE = Symbol.for("react.tracing_marker"); - var MAYBE_ITERATOR_SYMBOL = Symbol.iterator; - var FAUX_ITERATOR_SYMBOL = "@@iterator"; - function getIteratorFn(maybeIterable) { - if (maybeIterable === null || typeof maybeIterable !== "object") { - return null; - } - var maybeIterator = MAYBE_ITERATOR_SYMBOL && maybeIterable[MAYBE_ITERATOR_SYMBOL] || maybeIterable[FAUX_ITERATOR_SYMBOL]; - if (typeof maybeIterator === "function") { - return maybeIterator; - } - return null; - } - var assign = Object.assign; - var disabledDepth = 0; - var prevLog; - var prevInfo; - var prevWarn; - var prevError; - var prevGroup; - var prevGroupCollapsed; - var prevGroupEnd; - function disabledLog() {} - disabledLog.__reactDisabledLog = true; - function disableLogs() { - { - if (disabledDepth === 0) { - prevLog = console.log; - prevInfo = console.info; - prevWarn = console.warn; - prevError = console.error; - prevGroup = console.group; - prevGroupCollapsed = console.groupCollapsed; - prevGroupEnd = console.groupEnd; - var props = { - configurable: true, - enumerable: true, - value: disabledLog, - writable: true - }; - Object.defineProperties(console, { - info: props, - log: props, - warn: props, - error: props, - group: props, - groupCollapsed: props, - groupEnd: props - }); - } - disabledDepth++; - } - } - function reenableLogs() { - { - disabledDepth--; - if (disabledDepth === 0) { - var props = { - configurable: true, - enumerable: true, - writable: true - }; - Object.defineProperties(console, { - log: assign({}, props, { - value: prevLog - }), - info: assign({}, props, { - value: prevInfo - }), - warn: assign({}, props, { - value: prevWarn - }), - error: assign({}, props, { - value: prevError - }), - group: assign({}, props, { - value: prevGroup - }), - groupCollapsed: assign({}, props, { - value: prevGroupCollapsed - }), - groupEnd: assign({}, props, { - value: prevGroupEnd - }) - }); - } - if (disabledDepth < 0) { - error("disabledDepth fell below zero. " + "This is a bug in React. Please file an issue."); - } - } - } - var ReactCurrentDispatcher = ReactSharedInternals.ReactCurrentDispatcher; - var prefix; - function describeBuiltInComponentFrame(name, source, ownerFn) { - { - if (prefix === undefined) { - try { - throw Error(); - } catch (x) { - var match = x.stack.trim().match(/\n( *(at )?)/); - prefix = match && match[1] || ""; - } - } - return "\n" + prefix + name; - } - } - var reentry = false; - var componentFrameCache; - { - var PossiblyWeakMap = typeof WeakMap === "function" ? WeakMap : Map; - componentFrameCache = new PossiblyWeakMap(); - } - function describeNativeComponentFrame(fn, construct) { - if (!fn || reentry) { - return ""; - } - { - var frame = componentFrameCache.get(fn); - if (frame !== undefined) { - return frame; - } - } - var control; - reentry = true; - var previousPrepareStackTrace = Error.prepareStackTrace; - Error.prepareStackTrace = undefined; - var previousDispatcher; - { - previousDispatcher = ReactCurrentDispatcher.current; - ReactCurrentDispatcher.current = null; - disableLogs(); - } - try { - if (construct) { - var Fake = function () { - throw Error(); - }; - Object.defineProperty(Fake.prototype, "props", { - set: function () { - throw Error(); - } - }); - if (typeof Reflect === "object" && Reflect.construct) { - try { - Reflect.construct(Fake, []); - } catch (x) { - control = x; - } - Reflect.construct(fn, [], Fake); - } else { - try { - Fake.call(); - } catch (x) { - control = x; - } - fn.call(Fake.prototype); - } - } else { - try { - throw Error(); - } catch (x) { - control = x; - } - fn(); - } - } catch (sample) { - if (sample && control && typeof sample.stack === "string") { - var sampleLines = sample.stack.split("\n"); - var controlLines = control.stack.split("\n"); - var s = sampleLines.length - 1; - var c = controlLines.length - 1; - while (s >= 1 && c >= 0 && sampleLines[s] !== controlLines[c]) { - c--; - } - for (; s >= 1 && c >= 0; (s--, c--)) { - if (sampleLines[s] !== controlLines[c]) { - if (s !== 1 || c !== 1) { - do { - s--; - c--; - if (c < 0 || sampleLines[s] !== controlLines[c]) { - var _frame = "\n" + sampleLines[s].replace(" at new ", " at "); - if (fn.displayName && _frame.includes("")) { - _frame = _frame.replace("", fn.displayName); - } - { - if (typeof fn === "function") { - componentFrameCache.set(fn, _frame); - } - } - return _frame; - } - } while (s >= 1 && c >= 0); - } - break; - } - } - } - } finally { - reentry = false; - { - ReactCurrentDispatcher.current = previousDispatcher; - reenableLogs(); - } - Error.prepareStackTrace = previousPrepareStackTrace; - } - var name = fn ? fn.displayName || fn.name : ""; - var syntheticFrame = name ? describeBuiltInComponentFrame(name) : ""; - { - if (typeof fn === "function") { - componentFrameCache.set(fn, syntheticFrame); - } - } - return syntheticFrame; - } - function describeClassComponentFrame(ctor, source, ownerFn) { - { - return describeNativeComponentFrame(ctor, true); - } - } - function describeFunctionComponentFrame(fn, source, ownerFn) { - { - return describeNativeComponentFrame(fn, false); - } - } - function shouldConstruct(Component) { - var prototype = Component.prototype; - return !!(prototype && prototype.isReactComponent); - } - function describeUnknownElementTypeFrameInDEV(type, source, ownerFn) { - if (type == null) { - return ""; - } - if (typeof type === "function") { - { - return describeNativeComponentFrame(type, shouldConstruct(type)); - } - } - if (typeof type === "string") { - return describeBuiltInComponentFrame(type); - } - switch (type) { - case REACT_SUSPENSE_TYPE: - return describeBuiltInComponentFrame("Suspense"); - case REACT_SUSPENSE_LIST_TYPE: - return describeBuiltInComponentFrame("SuspenseList"); - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_FORWARD_REF_TYPE: - return describeFunctionComponentFrame(type.render); - case REACT_MEMO_TYPE: - return describeUnknownElementTypeFrameInDEV(type.type, source, ownerFn); - case REACT_LAZY_TYPE: - { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return describeUnknownElementTypeFrameInDEV(init(payload), source, ownerFn); - } catch (x) {} - } - } - } - return ""; - } - function describeFiber(fiber) { - fiber._debugOwner ? fiber._debugOwner.type : null; - fiber._debugSource; - switch (fiber.tag) { - case HostComponent: - return describeBuiltInComponentFrame(fiber.type); - case LazyComponent: - return describeBuiltInComponentFrame("Lazy"); - case SuspenseComponent: - return describeBuiltInComponentFrame("Suspense"); - case SuspenseListComponent: - return describeBuiltInComponentFrame("SuspenseList"); - case FunctionComponent: - case IndeterminateComponent: - case SimpleMemoComponent: - return describeFunctionComponentFrame(fiber.type); - case ForwardRef: - return describeFunctionComponentFrame(fiber.type.render); - case ClassComponent: - return describeClassComponentFrame(fiber.type); - default: - return ""; - } - } - function getStackByFiberInDevAndProd(workInProgress) { - try { - var info = ""; - var node = workInProgress; - do { - info += describeFiber(node); - node = node.return; - } while (node); - return info; - } catch (x) { - return "\nError generating stack: " + x.message + "\n" + x.stack; - } - } - function getWrappedName(outerType, innerType, wrapperName) { - var displayName = outerType.displayName; - if (displayName) { - return displayName; - } - var functionName = innerType.displayName || innerType.name || ""; - return functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName; - } - function getContextName(type) { - return type.displayName || "Context"; - } - function getComponentNameFromType(type) { - if (type == null) { - return null; - } - { - if (typeof type.tag === "number") { - error("Received an unexpected object in getComponentNameFromType(). " + "This is likely a bug in React. Please file an issue."); - } - } - if (typeof type === "function") { - return type.displayName || type.name || null; - } - if (typeof type === "string") { - return type; - } - switch (type) { - case REACT_FRAGMENT_TYPE: - return "Fragment"; - case REACT_PORTAL_TYPE: - return "Portal"; - case REACT_PROFILER_TYPE: - return "Profiler"; - case REACT_STRICT_MODE_TYPE: - return "StrictMode"; - case REACT_SUSPENSE_TYPE: - return "Suspense"; - case REACT_SUSPENSE_LIST_TYPE: - return "SuspenseList"; - } - if (typeof type === "object") { - switch (type.$$typeof) { - case REACT_CONTEXT_TYPE: - var context = type; - return getContextName(context) + ".Consumer"; - case REACT_PROVIDER_TYPE: - var provider = type; - return getContextName(provider._context) + ".Provider"; - case REACT_FORWARD_REF_TYPE: - return getWrappedName(type, type.render, "ForwardRef"); - case REACT_MEMO_TYPE: - var outerName = type.displayName || null; - if (outerName !== null) { - return outerName; - } - return getComponentNameFromType(type.type) || "Memo"; - case REACT_LAZY_TYPE: - { - var lazyComponent = type; - var payload = lazyComponent._payload; - var init = lazyComponent._init; - try { - return getComponentNameFromType(init(payload)); - } catch (x) { - return null; - } - } - } - } - return null; - } - function getWrappedName$1(outerType, innerType, wrapperName) { - var functionName = innerType.displayName || innerType.name || ""; - return outerType.displayName || (functionName !== "" ? wrapperName + "(" + functionName + ")" : wrapperName); - } - function getContextName$1(type) { - return type.displayName || "Context"; - } - function getComponentNameFromFiber(fiber) { - var tag = fiber.tag, type = fiber.type; - switch (tag) { - case CacheComponent: - return "Cache"; - case ContextConsumer: - var context = type; - return getContextName$1(context) + ".Consumer"; - case ContextProvider: - var provider = type; - return getContextName$1(provider._context) + ".Provider"; - case DehydratedFragment: - return "DehydratedFragment"; - case ForwardRef: - return getWrappedName$1(type, type.render, "ForwardRef"); - case Fragment: - return "Fragment"; - case HostComponent: - return type; - case HostPortal: - return "Portal"; - case HostRoot: - return "Root"; - case HostText: - return "Text"; - case LazyComponent: - return getComponentNameFromType(type); - case Mode: - if (type === REACT_STRICT_MODE_TYPE) { - return "StrictMode"; - } - return "Mode"; - case OffscreenComponent: - return "Offscreen"; - case Profiler: - return "Profiler"; - case ScopeComponent: - return "Scope"; - case SuspenseComponent: - return "Suspense"; - case SuspenseListComponent: - return "SuspenseList"; - case TracingMarkerComponent: - return "TracingMarker"; - case ClassComponent: - case FunctionComponent: - case IncompleteClassComponent: - case IndeterminateComponent: - case MemoComponent: - case SimpleMemoComponent: - if (typeof type === "function") { - return type.displayName || type.name || null; - } - if (typeof type === "string") { - return type; - } - break; - } - return null; - } - var ReactDebugCurrentFrame = ReactSharedInternals.ReactDebugCurrentFrame; - var current = null; - var isRendering = false; - function getCurrentFiberOwnerNameInDevOrNull() { - { - if (current === null) { - return null; - } - var owner = current._debugOwner; - if (owner !== null && typeof owner !== "undefined") { - return getComponentNameFromFiber(owner); - } - } - return null; - } - function getCurrentFiberStackInDev() { - { - if (current === null) { - return ""; - } - return getStackByFiberInDevAndProd(current); - } - } - function resetCurrentFiber() { - { - ReactDebugCurrentFrame.getCurrentStack = null; - current = null; - isRendering = false; - } - } - function setCurrentFiber(fiber) { - { - ReactDebugCurrentFrame.getCurrentStack = fiber === null ? null : getCurrentFiberStackInDev; - current = fiber; - isRendering = false; - } - } - function getCurrentFiber() { - { - return current; - } - } - function setIsRendering(rendering) { - { - isRendering = rendering; - } - } - function toString(value) { - return "" + value; - } - function getToStringValue(value) { - switch (typeof value) { - case "boolean": - case "number": - case "string": - case "undefined": - return value; - case "object": - { - checkFormFieldValueStringCoercion(value); - } - return value; - default: - return ""; - } - } - var hasReadOnlyValue = { - button: true, - checkbox: true, - image: true, - hidden: true, - radio: true, - reset: true, - submit: true - }; - function checkControlledValueProps(tagName, props) { - { - if (!(hasReadOnlyValue[props.type] || props.onChange || props.onInput || props.readOnly || props.disabled || props.value == null)) { - error("You provided a `value` prop to a form field without an " + "`onChange` handler. This will render a read-only field. If " + "the field should be mutable use `defaultValue`. Otherwise, " + "set either `onChange` or `readOnly`."); - } - if (!(props.onChange || props.readOnly || props.disabled || props.checked == null)) { - error("You provided a `checked` prop to a form field without an " + "`onChange` handler. This will render a read-only field. If " + "the field should be mutable use `defaultChecked`. Otherwise, " + "set either `onChange` or `readOnly`."); - } - } - } - function isCheckable(elem) { - var type = elem.type; - var nodeName = elem.nodeName; - return nodeName && nodeName.toLowerCase() === "input" && (type === "checkbox" || type === "radio"); - } - function getTracker(node) { - return node._valueTracker; - } - function detachTracker(node) { - node._valueTracker = null; - } - function getValueFromNode(node) { - var value = ""; - if (!node) { - return value; - } - if (isCheckable(node)) { - value = node.checked ? "true" : "false"; - } else { - value = node.value; - } - return value; - } - function trackValueOnNode(node) { - var valueField = isCheckable(node) ? "checked" : "value"; - var descriptor = Object.getOwnPropertyDescriptor(node.constructor.prototype, valueField); - { - checkFormFieldValueStringCoercion(node[valueField]); - } - var currentValue = "" + node[valueField]; - if (node.hasOwnProperty(valueField) || typeof descriptor === "undefined" || typeof descriptor.get !== "function" || typeof descriptor.set !== "function") { - return; - } - var get = descriptor.get, set = descriptor.set; - Object.defineProperty(node, valueField, { - configurable: true, - get: function () { - return get.call(this); - }, - set: function (value) { - { - checkFormFieldValueStringCoercion(value); - } - currentValue = "" + value; - set.call(this, value); - } - }); - Object.defineProperty(node, valueField, { - enumerable: descriptor.enumerable - }); - var tracker = { - getValue: function () { - return currentValue; - }, - setValue: function (value) { - { - checkFormFieldValueStringCoercion(value); - } - currentValue = "" + value; - }, - stopTracking: function () { - detachTracker(node); - delete node[valueField]; - } - }; - return tracker; - } - function track(node) { - if (getTracker(node)) { - return; - } - node._valueTracker = trackValueOnNode(node); - } - function updateValueIfChanged(node) { - if (!node) { - return false; - } - var tracker = getTracker(node); - if (!tracker) { - return true; - } - var lastValue = tracker.getValue(); - var nextValue = getValueFromNode(node); - if (nextValue !== lastValue) { - tracker.setValue(nextValue); - return true; - } - return false; - } - function getActiveElement(doc) { - doc = doc || (typeof document !== "undefined" ? document : undefined); - if (typeof doc === "undefined") { - return null; - } - try { - return doc.activeElement || doc.body; - } catch (e) { - return doc.body; - } - } - var didWarnValueDefaultValue = false; - var didWarnCheckedDefaultChecked = false; - var didWarnControlledToUncontrolled = false; - var didWarnUncontrolledToControlled = false; - function isControlled(props) { - var usesChecked = props.type === "checkbox" || props.type === "radio"; - return usesChecked ? props.checked != null : props.value != null; - } - function getHostProps(element, props) { - var node = element; - var checked = props.checked; - var hostProps = assign({}, props, { - defaultChecked: undefined, - defaultValue: undefined, - value: undefined, - checked: checked != null ? checked : node._wrapperState.initialChecked - }); - return hostProps; - } - function initWrapperState(element, props) { - { - checkControlledValueProps("input", props); - if (props.checked !== undefined && props.defaultChecked !== undefined && !didWarnCheckedDefaultChecked) { - error("%s contains an input of type %s with both checked and defaultChecked props. " + "Input elements must be either controlled or uncontrolled " + "(specify either the checked prop, or the defaultChecked prop, but not " + "both). Decide between using a controlled or uncontrolled input " + "element and remove one of these props. More info: " + "https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); - didWarnCheckedDefaultChecked = true; - } - if (props.value !== undefined && props.defaultValue !== undefined && !didWarnValueDefaultValue) { - error("%s contains an input of type %s with both value and defaultValue props. " + "Input elements must be either controlled or uncontrolled " + "(specify either the value prop, or the defaultValue prop, but not " + "both). Decide between using a controlled or uncontrolled input " + "element and remove one of these props. More info: " + "https://reactjs.org/link/controlled-components", getCurrentFiberOwnerNameInDevOrNull() || "A component", props.type); - didWarnValueDefaultValue = true; - } - } - var node = element; - var defaultValue = props.defaultValue == null ? "" : props.defaultValue; - node._wrapperState = { - initialChecked: props.checked != null ? props.checked : props.defaultChecked, - initialValue: getToStringValue(props.value != null ? props.value : defaultValue), - controlled: isControlled(props) - }; - } - function updateChecked(element, props) { - var node = element; - var checked = props.checked; - if (checked != null) { - setValueForProperty(node, "checked", checked, false); - } - } - function updateWrapper(element, props) { - var node = element; - { - var controlled = isControlled(props); - if (!node._wrapperState.controlled && controlled && !didWarnUncontrolledToControlled) { - error("A component is changing an uncontrolled input to be controlled. " + "This is likely caused by the value changing from undefined to " + "a defined value, which should not happen. " + "Decide between using a controlled or uncontrolled input " + "element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); - didWarnUncontrolledToControlled = true; - } - if (node._wrapperState.controlled && !controlled && !didWarnControlledToUncontrolled) { - error("A component is changing a controlled input to be uncontrolled. " + "This is likely caused by the value changing from a defined to " + "undefined, which should not happen. " + "Decide between using a controlled or uncontrolled input " + "element for the lifetime of the component. More info: https://reactjs.org/link/controlled-components"); - didWarnControlledToUncontrolled = true; - } - } - updateChecked(element, props); - var value = getToStringValue(props.value); - var type = props.type; - if (value != null) { - if (type === "number") { - if (value === 0 && node.value === "" || node.value != value) { - node.value = toString(value); - } - } else if (node.value !== toString(value)) { - node.value = toString(value); - } - } else if (type === "submit" || type === "reset") { - node.removeAttribute("value"); - return; - } - { - if (props.hasOwnProperty("value")) { - setDefaultValue(node, props.type, value); - } else if (props.hasOwnProperty("defaultValue")) { - setDefaultValue(node, props.type, getToStringValue(props.defaultValue)); - } - } - { - if (props.checked == null && props.defaultChecked != null) { - node.defaultChecked = !!props.defaultChecked; - } - } - } - function postMountWrapper(element, props, isHydrating) { - var node = element; - if (props.hasOwnProperty("value") || props.hasOwnProperty("defaultValue")) { - var type = props.type; - var isButton = type === "submit" || type === "reset"; - if (isButton && (props.value === undefined || props.value === null)) { - return; - } - var initialValue = toString(node._wrapperState.initialValue); - if (!isHydrating) { - { - if (initialValue !== node.value) { - node.value = initialValue; - } - } - } - { - node.defaultValue = initialValue; - } - } - var name = node.name; - if (name !== "") { - node.name = ""; - } - { - node.defaultChecked = !node.defaultChecked; - node.defaultChecked = !!node._wrapperState.initialChecked; - } - if (name !== "") { - node.name = name; - } - } - function restoreControlledState(element, props) { - var node = element; - updateWrapper(node, props); - updateNamedCousins(node, props); - } - function updateNamedCousins(rootNode, props) { - var name = props.name; - if (props.type === "radio" && name != null) { - var queryRoot = rootNode; - while (queryRoot.parentNode) { - queryRoot = queryRoot.parentNode; - } - { - checkAttributeStringCoercion(name, "name"); - } - var group = queryRoot.querySelectorAll("input[name=" + JSON.stringify("" + name) + "][type=\"radio\"]"); - for (var i = 0; i < group.length; i++) { - var otherNode = group[i]; - if (otherNode === rootNode || otherNode.form !== rootNode.form) { - continue; - } - var otherProps = getFiberCurrentPropsFromNode(otherNode); - if (!otherProps) { - throw new Error("ReactDOMInput: Mixing React and non-React radio inputs with the " + "same `name` is not supported."); - } - updateValueIfChanged(otherNode); - updateWrapper(otherNode, otherProps); - } - } - } - function setDefaultValue(node, type, value) { - if (type !== "number" || getActiveElement(node.ownerDocument) !== node) { - if (value == null) { - node.defaultValue = toString(node._wrapperState.initialValue); - } else if (node.defaultValue !== toString(value)) { - node.defaultValue = toString(value); - } - } - } - var didWarnSelectedSetOnOption = false; - var didWarnInvalidChild = false; - var didWarnInvalidInnerHTML = false; - function validateProps(element, props) { - { - if (props.value == null) { - if (typeof props.children === "object" && props.children !== null) { - React.Children.forEach(props.children, function (child) { - if (child == null) { - return; - } - if (typeof child === "string" || typeof child === "number") { - return; - } - if (!didWarnInvalidChild) { - didWarnInvalidChild = true; - error("Cannot infer the option value of complex children. " + "Pass a `value` prop or use a plain string as children to