From 3787272f0ee9d612937da590587daa705102282e Mon Sep 17 00:00:00 2001 From: juan Date: Thu, 26 Aug 2021 12:16:19 +0200 Subject: [PATCH 1/5] Include edited event for autolabeler --- index.js | 1 + 1 file changed, 1 insertion(+) diff --git a/index.js b/index.js index 75813873e..3ffe0aa9a 100644 --- a/index.js +++ b/index.js @@ -27,6 +27,7 @@ module.exports = (app, { getRouter }) => { 'pull_request.opened', 'pull_request.reopened', 'pull_request.synchronize', + 'pull_request.edited', ], async (context) => { const { disableAutolabeler } = getInput() From 803cbec0b32b5ba1e5065d997116b570da642a44 Mon Sep 17 00:00:00 2001 From: juan Date: Thu, 26 Aug 2021 14:39:20 +0200 Subject: [PATCH 2/5] Add dist folder --- dist/index.js | 158796 +++++++++++++++++++++++++---------------------- 1 file changed, 82963 insertions(+), 75833 deletions(-) diff --git a/dist/index.js b/dist/index.js index ccb1a0a93..2fd8008ef 100644 --- a/dist/index.js +++ b/dist/index.js @@ -5,7 +5,7 @@ /***/ ((module) => { "use strict"; -module.exports = JSON.parse('{"name":"@hapi/joi","description":"Object schema validation","version":"15.1.1","homepage":"https://github.com/hapijs/joi","repository":"git://github.com/hapijs/joi","main":"lib/index.js","keywords":["schema","validation"],"dependencies":{"@hapi/address":"2.x.x","@hapi/bourne":"1.x.x","@hapi/hoek":"8.x.x","@hapi/topo":"3.x.x"},"devDependencies":{"@hapi/code":"6.x.x","@hapi/lab":"20.x.x"},"scripts":{"test":"lab -t 100 -a @hapi/code -L","test-cov-html":"lab -r html -o coverage.html -a @hapi/code"},"license":"BSD-3-Clause"}'); +module.exports = JSON.parse('{"_from":"@hapi/joi@15.1.1","_id":"@hapi/joi@15.1.1","_inBundle":false,"_integrity":"sha512-entf8ZMOK8sc+8YfeOlM8pCfg3b5+WZIKBfUaaJT8UsjAAPjartzxIYm3TIbjvA4u+u++KbcXD38k682nVHDAQ==","_location":"/@hapi/joi","_phantomChildren":{},"_requested":{"type":"version","registry":true,"raw":"@hapi/joi@15.1.1","name":"@hapi/joi","escapedName":"@hapi%2fjoi","scope":"@hapi","rawSpec":"15.1.1","saveSpec":null,"fetchSpec":"15.1.1"},"_requiredBy":["/"],"_resolved":"https://registry.npmjs.org/@hapi/joi/-/joi-15.1.1.tgz","_shasum":"c675b8a71296f02833f8d6d243b34c57b8ce19d7","_spec":"@hapi/joi@15.1.1","_where":"/Users/juancabello/Workspace/release-drafter","bugs":{"url":"https://github.com/hapijs/joi/issues"},"bundleDependencies":false,"dependencies":{"@hapi/address":"2.x.x","@hapi/bourne":"1.x.x","@hapi/hoek":"8.x.x","@hapi/topo":"3.x.x"},"deprecated":"Switch to \'npm install joi\'","description":"Object schema validation","devDependencies":{"@hapi/code":"6.x.x","@hapi/lab":"20.x.x"},"homepage":"https://github.com/hapijs/joi","keywords":["schema","validation"],"license":"BSD-3-Clause","main":"lib/index.js","name":"@hapi/joi","repository":{"type":"git","url":"git://github.com/hapijs/joi.git"},"scripts":{"test":"lab -t 100 -a @hapi/code -L","test-cov-html":"lab -r html -o coverage.html -a @hapi/code"},"version":"15.1.1"}'); /***/ }), @@ -41,6 +41,7 @@ module.exports = (app, { getRouter }) => { 'pull_request.opened', 'pull_request.reopened', 'pull_request.synchronize', + 'pull_request.edited', ], async (context) => { const { disableAutolabeler } = getInput() @@ -4007,6 +4008,10 @@ module.exports = internals.clone = function (obj, options = {}, _seen = null) { const keys = Utils.keys(obj, options); for (const key of keys) { + if (key === '__proto__') { + continue; + } + if (baseProto === Types.array && key === 'length') { @@ -12051,52 +12056,24 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau var universalUserAgent = __nccwpck_require__(45030); var request = __nccwpck_require__(36234); +var authOauthApp = __nccwpck_require__(58459); var deprecation = __nccwpck_require__(58932); var universalGithubAppJwt = __nccwpck_require__(84419); var LRU = _interopDefault(__nccwpck_require__(7129)); -var requestError = __nccwpck_require__(10537); - -async function getAppAuthentication({ - appId, - privateKey, - timeDifference -}) { - const appAuthentication = await universalGithubAppJwt.githubAppJwt({ - id: +appId, - privateKey, - now: timeDifference && Math.floor(Date.now() / 1000) + timeDifference - }); - return { - type: "app", - token: appAuthentication.token, - appId: appAuthentication.appId, - expiresAt: new Date(appAuthentication.expiration * 1000).toISOString() - }; -} - -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} +var authOauthUser = __nccwpck_require__(11591); function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); + + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + } + keys.push.apply(keys, symbols); } @@ -12123,6 +12100,21 @@ function _objectSpread2(target) { return target; } +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; @@ -12159,6 +12151,32 @@ function _objectWithoutProperties(source, excluded) { return target; } +async function getAppAuthentication({ + appId, + privateKey, + timeDifference +}) { + try { + const appAuthentication = await universalGithubAppJwt.githubAppJwt({ + id: +appId, + privateKey, + now: timeDifference && Math.floor(Date.now() / 1000) + timeDifference + }); + return { + type: "app", + token: appAuthentication.token, + appId: appAuthentication.appId, + expiresAt: new Date(appAuthentication.expiration * 1000).toISOString() + }; + } catch (error) { + if (privateKey === "-----BEGIN RSA PRIVATE KEY-----") { + throw new Error("The 'privateKey` option contains only the first line '-----BEGIN RSA PRIVATE KEY-----'. If you are setting it using a `.env` file, make sure it is set on a single line with newlines replaced by '\n'"); + } else { + throw error; + } + } +} + // https://github.com/isaacs/node-lru-cache#readme function getCache() { return new LRU({ @@ -12192,6 +12210,7 @@ async function get(cache, options) { expiresAt, permissions, repositoryIds: options.repositoryIds, + repositoryNames: options.repositoryNames, singleFileName, repositorySelection: repositorySelection }; @@ -12206,11 +12225,13 @@ async function set(cache, options, data) { function optionsToCacheKey({ installationId, permissions = {}, - repositoryIds = [] + repositoryIds = [], + repositoryNames = [] }) { const permissionsString = Object.keys(permissions).sort().map(name => permissions[name] === "read" ? name : `${name}!`).join(","); const repositoryIdsString = repositoryIds.sort().join(","); - return [installationId, repositoryIdsString, permissionsString].filter(Boolean).join("|"); + const repositoryNamesString = repositoryNames.join(","); + return [installationId, repositoryIdsString, repositoryNamesString, permissionsString].filter(Boolean).join("|"); } function toTokenAuthentication({ @@ -12221,6 +12242,7 @@ function toTokenAuthentication({ repositorySelection, permissions, repositoryIds, + repositoryNames, singleFileName }) { return Object.assign({ @@ -12234,11 +12256,14 @@ function toTokenAuthentication({ repositorySelection }, repositoryIds ? { repositoryIds + } : null, repositoryNames ? { + repositoryNames } : null, singleFileName ? { singleFileName } : null); } +const _excluded = ["type", "factory", "oauthApp"]; async function getInstallationAuthentication(state, options, customRequest) { const installationId = Number(options.installationId || state.installationId); @@ -12247,14 +12272,16 @@ async function getInstallationAuthentication(state, options, customRequest) { } if (options.factory) { - const { + const _state$options = _objectSpread2(_objectSpread2({}, state), options), + { type, - factory - } = options, - factoryAuthOptions = _objectWithoutProperties(options, ["type", "factory"]); // @ts-ignore if `options.factory` is set, the return type for `auth()` should be `Promise>` + factory, + oauthApp + } = _state$options, + factoryAuthOptions = _objectWithoutProperties(_state$options, _excluded); // @ts-expect-error if `options.factory` is set, the return type for `auth()` should be `Promise>` - return factory(Object.assign({}, state, factoryAuthOptions)); + return factory(factoryAuthOptions); } const optionsWithInstallationTokenFromState = Object.assign({ @@ -12271,6 +12298,7 @@ async function getInstallationAuthentication(state, options, customRequest) { expiresAt, permissions, repositoryIds, + repositoryNames, singleFileName, repositorySelection } = result; @@ -12282,6 +12310,7 @@ async function getInstallationAuthentication(state, options, customRequest) { permissions, repositorySelection, repositoryIds, + repositoryNames, singleFileName }); } @@ -12294,15 +12323,14 @@ async function getInstallationAuthentication(state, options, customRequest) { token, expires_at: expiresAt, repositories, - permissions, - // @ts-ignore - repository_selection: repositorySelection, - // @ts-ignore + permissions: permissionsOptional, + repository_selection: repositorySelectionOptional, single_file: singleFileName } } = await request("POST /app/installations/{installation_id}/access_tokens", { installation_id: installationId, repository_ids: options.repositoryIds, + repositories: options.repositoryNames, permissions: options.permissions, mediaType: { previews: ["machine-man"] @@ -12311,7 +12339,14 @@ async function getInstallationAuthentication(state, options, customRequest) { authorization: `bearer ${appAuthentication.token}` } }); + /* istanbul ignore next - permissions are optional per OpenAPI spec, but we think that is incorrect */ + + const permissions = permissionsOptional || {}; + /* istanbul ignore next - repositorySelection are optional per OpenAPI spec, but we think that is incorrect */ + + const repositorySelection = repositorySelectionOptional || "all"; const repositoryIds = repositories ? repositories.map(r => r.id) : void 0; + const repositoryNames = repositories ? repositories.map(repo => repo.name) : void 0; const createdAt = new Date().toISOString(); await set(state.cache, optionsWithInstallationTokenFromState, { token, @@ -12320,6 +12355,7 @@ async function getInstallationAuthentication(state, options, customRequest) { repositorySelection, permissions, repositoryIds, + repositoryNames, singleFileName }); return toTokenAuthentication({ @@ -12330,61 +12366,42 @@ async function getInstallationAuthentication(state, options, customRequest) { repositorySelection, permissions, repositoryIds, + repositoryNames, singleFileName }); } -async function getOAuthAuthentication(state, options, customRequest) { - const request = customRequest || state.request; // The "/login/oauth/access_token" is not part of the REST API hosted on api.github.com, - // instead it’s using the github.com domain. +async function auth(state, authOptions) { + switch (authOptions.type) { + case "app": + return getAppAuthentication(state); + // @ts-expect-error "oauth" is not supperted in types - const route = /^https:\/\/(api\.)?github\.com$/.test(state.request.endpoint.DEFAULTS.baseUrl) ? "POST https://github.com/login/oauth/access_token" : `POST ${state.request.endpoint.DEFAULTS.baseUrl.replace("/api/v3", "/login/oauth/access_token")}`; - const parameters = { - headers: { - accept: `application/json` - }, - client_id: state.clientId, - client_secret: state.clientSecret, - code: options.code, - state: options.state, - redirect_uri: options.redirectUrl - }; - const response = await request(route, parameters); + case "oauth": + state.log.warn( // @ts-expect-error `log.warn()` expects string + new deprecation.Deprecation(`[@octokit/auth-app] {type: "oauth"} is deprecated. Use {type: "oauth-app"} instead`)); - if (response.data.error !== undefined) { - throw new requestError.RequestError(`${response.data.error_description} (${response.data.error})`, response.status, { - headers: response.headers, - request: request.endpoint(route, parameters) - }); - } + case "oauth-app": + return state.oauthApp({ + type: "oauth-app" + }); - const { - data: { - access_token: token, - scope - } - } = response; - return { - type: "token", - tokenType: "oauth", - token, - scopes: scope.split(/,\s*/).filter(Boolean) - }; -} + case "installation": + return getInstallationAuthentication(state, _objectSpread2(_objectSpread2({}, authOptions), {}, { + type: "installation" + })); -async function auth(state, options) { - if (options.type === "app") { - return getAppAuthentication(state); - } + case "oauth-user": + // @ts-expect-error TODO: infer correct auth options type based on type. authOptions should be typed as "WebFlowAuthOptions | OAuthAppDeviceFlowAuthOptions | GitHubAppDeviceFlowAuthOptions" + return state.oauthApp(authOptions); - if (options.type === "installation") { - return getInstallationAuthentication(state, options); + default: + // @ts-expect-error type is "never" at this point + throw new Error(`Invalid auth type: ${authOptions.type}`); } - - return getOAuthAuthentication(state, options); } -const PATHS = ["/app", "/app/hook/config", "/app/installations", "/app/installations/{installation_id}", "/app/installations/{installation_id}/access_tokens", "/app/installations/{installation_id}/suspended", "/marketplace_listing/accounts/{account_id}", "/marketplace_listing/plan", "/marketplace_listing/plans", "/marketplace_listing/plans/{plan_id}/accounts", "/marketplace_listing/stubbed/accounts/{account_id}", "/marketplace_listing/stubbed/plan", "/marketplace_listing/stubbed/plans", "/marketplace_listing/stubbed/plans/{plan_id}/accounts", "/orgs/{org}/installation", "/repos/{owner}/{repo}/installation", "/users/{username}/installation"]; // CREDIT: Simon Grondin (https://github.com/SGrondin) +const PATHS = ["/app", "/app/hook/config", "/app/hook/deliveries", "/app/hook/deliveries/{delivery_id}", "/app/hook/deliveries/{delivery_id}/attempts", "/app/installations", "/app/installations/{installation_id}", "/app/installations/{installation_id}/access_tokens", "/app/installations/{installation_id}/suspended", "/marketplace_listing/accounts/{account_id}", "/marketplace_listing/plan", "/marketplace_listing/plans", "/marketplace_listing/plans/{plan_id}/accounts", "/marketplace_listing/stubbed/accounts/{account_id}", "/marketplace_listing/stubbed/plan", "/marketplace_listing/stubbed/plans", "/marketplace_listing/stubbed/plans/{plan_id}/accounts", "/orgs/{org}/installation", "/repos/{owner}/{repo}/installation", "/users/{username}/installation"]; // CREDIT: Simon Grondin (https://github.com/SGrondin) // https://github.com/octokit/plugin-throttling.js/blob/45c5d7f13b8af448a9dbca468d9c9150a73b3948/lib/route-matcher.js function routeMatcher(paths) { @@ -12424,9 +12441,14 @@ function isNotTimeSkewError(error) { } async function hook(state, request, route, parameters) { - let endpoint = request.endpoint.merge(route, parameters); + const endpoint = request.endpoint.merge(route, parameters); + const url = endpoint.url; // Do not intercept request to retrieve a new token + + if (/\/login\/oauth\/access_token$/.test(url)) { + return request(endpoint); + } - if (requiresAppAuth(endpoint.url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) { + if (requiresAppAuth(url.replace(request.endpoint.DEFAULTS.baseUrl, ""))) { const { token } = await getAppAuthentication(state); @@ -12444,11 +12466,11 @@ async function hook(state, request, route, parameters) { // Throw the error to be handled upstream. - if (typeof error.headers.date === "undefined") { + if (typeof error.response.headers.date === "undefined") { throw error; } - const diff = Math.floor((Date.parse(error.headers.date) - Date.parse(new Date().toString())) / 1000); + const diff = Math.floor((Date.parse(error.response.headers.date) - Date.parse(new Date().toString())) / 1000); state.log.warn(error.message); state.log.warn(`[@octokit/auth-app] GitHub API time and system time are different by ${diff} seconds. Retrying request with the difference accounted for.`); const { @@ -12463,10 +12485,19 @@ async function hook(state, request, route, parameters) { return response; } + if (authOauthUser.requiresBasicAuth(url)) { + const authentication = await state.oauthApp({ + type: "oauth-app" + }); + endpoint.headers.authorization = authentication.headers.authorization; + return request(endpoint); + } + const { token, createdAt - } = await getInstallationAuthentication(state, {}, request); + } = await getInstallationAuthentication(state, // @ts-expect-error TBD + {}, request); endpoint.headers.authorization = `token ${token}`; return sendRequestWithRetries(state, request, endpoint, createdAt); } @@ -12504,197 +12535,128 @@ async function sendRequestWithRetries(state, request, options, createdAt, retrie } } -const VERSION = "2.10.5"; +const VERSION = "3.6.0"; -const createAppAuth = function createAppAuth(options) { - const log = Object.assign({ - warn: console.warn.bind(console) - }, options.log); +function createAppAuth(options) { + if (!options.appId) { + throw new Error("[@octokit/auth-app] appId option is required"); + } + + if (!options.privateKey) { + throw new Error("[@octokit/auth-app] privateKey option is required"); + } - if ("id" in options) { - log.warn(new deprecation.Deprecation('[@octokit/auth-app] "createAppAuth({ id })" is deprecated, use "createAppAuth({ appId })" instead')); + if ("installationId" in options && !options.installationId) { + throw new Error("[@octokit/auth-app] installationId is set to a falsy value"); } + const log = Object.assign({ + warn: console.warn.bind(console) + }, options.log); + const request$1 = options.request || request.request.defaults({ + headers: { + "user-agent": `octokit-auth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` + } + }); const state = Object.assign({ - request: request.request.defaults({ - headers: { - "user-agent": `octokit-auth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` - } - }), + request: request$1, cache: getCache() - }, options, { - appId: Number("appId" in options ? options.appId : options.id) - }, options.installationId ? { + }, options, options.installationId ? { installationId: Number(options.installationId) } : {}, { - log - }); + log, + oauthApp: authOauthApp.createOAuthAppAuth({ + clientType: "github-app", + clientId: options.clientId || "", + clientSecret: options.clientSecret || "", + request: request$1 + }) + }); // @ts-expect-error not worth the extra code to appease TS + return Object.assign(auth.bind(null, state), { hook: hook.bind(null, state) }); -}; - -exports.createAppAuth = createAppAuth; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 40334: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -async function auth(token) { - const tokenType = token.split(/\./).length === 3 ? "app" : /^v\d+\./.test(token) ? "installation" : "oauth"; - return { - type: "token", - token: token, - tokenType - }; } -/** - * Prefix token for usage in the Authorization header - * - * @param token OAuth token or JSON Web Token - */ -function withAuthorizationPrefix(token) { - if (token.split(/\./).length === 3) { - return `bearer ${token}`; - } - - return `token ${token}`; -} - -async function hook(token, request, route, parameters) { - const endpoint = request.endpoint.merge(route, parameters); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); -} - -const createTokenAuth = function createTokenAuth(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"); +Object.defineProperty(exports, "createOAuthUserAuth", ({ + enumerable: true, + get: function () { + return authOauthUser.createOAuthUserAuth; } - - token = token.replace(/^(token|bearer) +/i, ""); - return Object.assign(auth.bind(null, token), { - hook: hook.bind(null, token) - }); -}; - -exports.createTokenAuth = createTokenAuth; +})); +exports.createAppAuth = createAppAuth; //# sourceMappingURL=index.js.map /***/ }), -/***/ 79567: -/***/ ((__unused_webpack_module, exports) => { +/***/ 58459: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -async function auth(reason) { - return { - type: "unauthenticated", - reason - }; -} +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -function isRateLimitError(error) { - if (error.status !== 403) { - return false; - } - /* istanbul ignore if */ +var universalUserAgent = __nccwpck_require__(45030); +var request = __nccwpck_require__(36234); +var btoa = _interopDefault(__nccwpck_require__(72358)); +var authOauthUser = __nccwpck_require__(11591); +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); - if (!error.headers) { - return false; - } + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); - return error.headers["x-ratelimit-remaining"] === "0"; -} + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + } -const REGEX_ABUSE_LIMIT_MESSAGE = /\babuse\b/i; -function isAbuseLimitError(error) { - if (error.status !== 403) { - return false; + keys.push.apply(keys, symbols); } - return REGEX_ABUSE_LIMIT_MESSAGE.test(error.message); + return keys; } -async function hook(reason, request, route, parameters) { - const endpoint = request.endpoint.merge(route, parameters); - return request(endpoint).catch(error => { - if (error.status === 404) { - error.message = `Not found. May be due to lack of authentication. Reason: ${reason}`; - throw error; - } - - if (isRateLimitError(error)) { - error.message = `API rate limit exceeded. This maybe caused by the lack of authentication. Reason: ${reason}`; - throw error; - } - - if (isAbuseLimitError(error)) { - error.message = `You have triggered an abuse detection mechanism. This maybe caused by the lack of authentication. Reason: ${reason}`; - throw error; - } - - if (error.status === 401) { - error.message = `Unauthorized. "${endpoint.method} ${endpoint.url}" failed most likely due to lack of authentication. Reason: ${reason}`; - throw error; - } +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; - if (error.status >= 400 && error.status < 500) { - error.message = error.message.replace(/\.?$/, `. May be caused by lack of authentication (${reason}).`); + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); } + } - throw error; - }); + return target; } -const createUnauthenticatedAuth = function createUnauthenticatedAuth(options) { - if (!options || !options.reason) { - throw new Error("[@octokit/auth-unauthenticated] No reason passed to createUnauthenticatedAuth"); +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; } - return Object.assign(auth.bind(null, options.reason), { - hook: hook.bind(null, options.reason) - }); -}; - -exports.createUnauthenticatedAuth = createUnauthenticatedAuth; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 76762: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -var universalUserAgent = __nccwpck_require__(45030); -var beforeAfterHook = __nccwpck_require__(83682); -var request = __nccwpck_require__(36234); -var graphql = __nccwpck_require__(88467); -var authToken = __nccwpck_require__(40334); + return obj; +} function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; @@ -12732,139 +12694,97 @@ function _objectWithoutProperties(source, excluded) { return target; } -const VERSION = "3.2.4"; - -class Octokit { - constructor(options = {}) { - const hook = new beforeAfterHook.Collection(); - const requestDefaults = { - baseUrl: request.request.endpoint.DEFAULTS.baseUrl, - headers: {}, - request: Object.assign({}, options.request, { - hook: hook.bind(null, "request") - }), - mediaType: { - previews: [], - format: "" +const _excluded = ["type"]; +async function auth(state, authOptions) { + if (authOptions.type === "oauth-app") { + return { + type: "oauth-app", + clientId: state.clientId, + clientSecret: state.clientSecret, + clientType: state.clientType, + headers: { + authorization: `basic ${btoa(`${state.clientId}:${state.clientSecret}`)}` } - }; // prepend default user agent with `options.userAgent` if set - - requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.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; - } + if ("factory" in authOptions) { + const _authOptions$state = _objectSpread2(_objectSpread2({}, authOptions), state), + options = _objectWithoutProperties(_authOptions$state, _excluded); // @ts-expect-error TODO: `option` cannot be never, is this a bug? - this.request = request.request.defaults(requestDefaults); - this.graphql = graphql.withCustomRequest(this.request).defaults(requestDefaults); - this.log = Object.assign({ - debug: () => {}, - info: () => {}, - warn: console.warn.bind(console), - error: console.error.bind(console) - }, options.log); - this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance - // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered. - // (2) If only `options.auth` is set, use the default token authentication strategy. - // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance. - // TODO: type `options.auth` based on `options.authStrategy`. - if (!options.authStrategy) { - if (!options.auth) { - // (1) - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - // (2) - const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯ + return authOptions.factory(options); + } - hook.wrap("request", auth.hook); - this.auth = auth; - } - } else { - const { - authStrategy - } = options, - otherOptions = _objectWithoutProperties(options, ["authStrategy"]); + const common = _objectSpread2({ + clientId: state.clientId, + clientSecret: state.clientSecret, + request: state.request + }, authOptions); // TS: Look what you made me do - 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)); // @ts-ignore ¯\_(ツ)_/¯ - hook.wrap("request", auth.hook); - this.auth = auth; - } // apply plugins - // https://stackoverflow.com/a/16345172 + const userAuth = state.clientType === "oauth-app" ? await authOauthUser.createOAuthUserAuth(_objectSpread2(_objectSpread2({}, common), {}, { + clientType: state.clientType + })) : await authOauthUser.createOAuthUserAuth(_objectSpread2(_objectSpread2({}, common), {}, { + clientType: state.clientType + })); + return userAuth(); +} +async function hook(state, request, route, parameters) { + let endpoint = request.endpoint.merge(route, parameters); // Do not intercept OAuth Web/Device flow request - const classConstructor = this.constructor; - classConstructor.plugins.forEach(plugin => { - Object.assign(this, plugin(this, options)); - }); + if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) { + return request(endpoint); } - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; - - if (typeof defaults === "function") { - super(defaults(options)); - return; - } + if (state.clientType === "github-app" && !authOauthUser.requiresBasicAuth(endpoint.url)) { + throw new Error(`[@octokit/auth-oauth-app] GitHub Apps cannot use their client ID/secret for basic authentication for endpoints other than "/applications/{client_id}/**". "${endpoint.method} ${endpoint.url}" is not supported.`); + } - super(Object.assign({}, defaults, options, options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null)); - } + const credentials = btoa(`${state.clientId}:${state.clientSecret}`); + endpoint.headers.authorization = `basic ${credentials}`; - }; - return OctokitWithDefaults; + try { + return await request(endpoint); + } catch (error) { + /* istanbul ignore if */ + if (error.status !== 401) throw error; + error.message = `[@octokit/auth-oauth-app] "${endpoint.method} ${endpoint.url}" does not support clientId/clientSecret basic authentication.`; + throw error; } - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ - +} - static plugin(...newPlugins) { - var _a; +const VERSION = "4.3.0"; - const currentPlugins = this.plugins; - const NewOctokit = (_a = class extends this {}, _a.plugins = currentPlugins.concat(newPlugins.filter(plugin => !currentPlugins.includes(plugin))), _a); - return NewOctokit; - } +function createOAuthAppAuth(options) { + const state = Object.assign({ + request: request.request.defaults({ + headers: { + "user-agent": `octokit-auth-oauth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` + } + }), + clientType: "oauth-app" + }, options); // @ts-expect-error not worth the extra code to appease TS + return Object.assign(auth.bind(null, state), { + hook: hook.bind(null, state) + }); } -Octokit.VERSION = VERSION; -Octokit.plugins = []; -exports.Octokit = Octokit; +Object.defineProperty(exports, "createOAuthUserAuth", ({ + enumerable: true, + get: function () { + return authOauthUser.createOAuthUserAuth; + } +})); +exports.createOAuthAppAuth = createOAuthAppAuth; //# sourceMappingURL=index.js.map /***/ }), -/***/ 59440: +/***/ 44344: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; @@ -12872,982 +12792,2432 @@ exports.Octokit = Octokit; Object.defineProperty(exports, "__esModule", ({ value: true })); -var isPlainObject = __nccwpck_require__(70558); var universalUserAgent = __nccwpck_require__(45030); +var request = __nccwpck_require__(36234); +var oauthMethods = __nccwpck_require__(88445); -function lowercaseKeys(object) { - if (!object) { - return {}; - } +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); -} + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); -function mergeDeep(defaults, options) { - const result = Object.assign({}, defaults); - Object.keys(options).forEach(key => { - if (isPlainObject.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] + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } - }); - return result; + + keys.push.apply(keys, symbols); + } + + return keys; } -function removeUndefinedProperties(obj) { - for (const key in obj) { - if (obj[key] === undefined) { - delete obj[key]; +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); } } - return obj; + return target; } -function merge(defaults, route, options) { - if (typeof route === "string") { - let [method, url] = route.split(" "); - options = Object.assign(url ? { - method, - url - } : { - url: method - }, options); +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); } else { - options = Object.assign({}, route); - } // lowercase header names before merging with defaults to avoid duplicates - + obj[key] = value; + } - options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging + return obj; +} - removeUndefinedProperties(options); - removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; - if (defaults && defaults.mediaType.previews.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter(preview => !mergedOptions.mediaType.previews.includes(preview)).concat(mergedOptions.mediaType.previews); + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; } - mergedOptions.mediaType.previews = mergedOptions.mediaType.previews.map(preview => preview.replace(/-preview/, "")); - return mergedOptions; + return target; } -function addQueryParameters(url, parameters) { - const separator = /\?/.test(url) ? "&" : "?"; - const names = Object.keys(parameters); +function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; - if (names.length === 0) { - return url; - } + var target = _objectWithoutPropertiesLoose(source, excluded); - return url + separator + names.map(name => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + var key, i; + + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; } + } - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); + return target; } -const urlVariableRegex = /\{[^}]+\}/g; +async function getOAuthAccessToken(state, options) { + const cachedAuthentication = getCachedAuthentication(state, options.auth); + if (cachedAuthentication) return cachedAuthentication; // Step 1: Request device and user codes + // https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-1-app-requests-the-device-and-user-verification-codes-from-github -function removeNonChars(variableName) { - return variableName.replace(/^\W+|\W+$/g, "").split(/,/); + const { + data: verification + } = await oauthMethods.createDeviceCode({ + clientType: state.clientType, + clientId: state.clientId, + request: options.request || state.request, + // @ts-expect-error the extra code to make TS happy is not worth it + scopes: options.auth.scopes || state.scopes + }); // Step 2: User must enter the user code on https://github.com/login/device + // See https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-2-prompt-the-user-to-enter-the-user-code-in-a-browser + + await state.onVerification(verification); // Step 3: Exchange device code for access token + // See https://docs.github.com/en/developers/apps/authorizing-oauth-apps#step-3-app-polls-github-to-check-if-the-user-authorized-the-device + + const authentication = await waitForAccessToken(options.request || state.request, state.clientId, state.clientType, verification); + state.authentication = authentication; + return authentication; } -function extractUrlVariableNames(url) { - const matches = url.match(urlVariableRegex); +function getCachedAuthentication(state, auth) { + if (auth.refresh === true) return false; + if (!state.authentication) return false; - if (!matches) { - return []; + if (state.clientType === "github-app") { + return state.authentication; } - return matches.map(removeNonChars).reduce((a, b) => a.concat(b), []); + const authentication = state.authentication; + const newScope = ("scopes" in auth && auth.scopes || state.scopes).join(" "); + const currentScope = authentication.scopes.join(" "); + return newScope === currentScope ? authentication : false; } -function omit(object, keysToOmit) { - return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { - obj[key] = object[key]; - return obj; - }, {}); +async function wait(seconds) { + await new Promise(resolve => setTimeout(resolve, seconds * 1000)); } -// Based on https://github.com/bramstein/url-template, licensed under BSD -// TODO: create separate package. -// -// Copyright (c) 2012-2014, Bram Stein -// All rights reserved. -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions -// are met: -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the distribution. -// 3. The name of the author may not be used to endorse or promote products -// derived from this software without specific prior written permission. -// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED -// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF -// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO -// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, -// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, -// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY -// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING -// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, -// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +async function waitForAccessToken(request, clientId, clientType, verification) { + try { + const options = { + clientId, + request, + code: verification.device_code + }; // WHY TYPESCRIPT WHY ARE YOU DOING THIS TO ME -/* istanbul ignore file */ -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, "]"); + const { + authentication + } = clientType === "oauth-app" ? await oauthMethods.exchangeDeviceCode(_objectSpread2(_objectSpread2({}, options), {}, { + clientType: "oauth-app" + })) : await oauthMethods.exchangeDeviceCode(_objectSpread2(_objectSpread2({}, options), {}, { + clientType: "github-app" + })); + return _objectSpread2({ + type: "token", + tokenType: "oauth" + }, authentication); + } catch (error) { + // istanbul ignore if + if (!error.response) throw error; + const errorType = error.response.data.error; + + if (errorType === "authorization_pending") { + await wait(verification.interval); + return waitForAccessToken(request, clientId, clientType, verification); } - return part; - }).join(""); + if (errorType === "slow_down") { + await wait(verification.interval + 5); + return waitForAccessToken(request, clientId, clientType, verification); + } + + throw error; + } } -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function (c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); +async function auth(state, authOptions) { + return getOAuthAccessToken(state, { + auth: authOptions }); } -function encodeValue(operator, value, key) { - value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); +async function hook(state, request, route, parameters) { + let endpoint = request.endpoint.merge(route, parameters); // Do not intercept request to retrieve codes or token - if (key) { - return encodeUnreserved(key) + "=" + value; - } else { - return value; + if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) { + return request(endpoint); } -} -function isDefined(value) { - return value !== undefined && value !== null; -} - -function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; + const { + token + } = await getOAuthAccessToken(state, { + request, + auth: { + type: "oauth" + } + }); + endpoint.headers.authorization = `token ${token}`; + return request(endpoint); } -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)); - } +const VERSION = "3.1.2"; - result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function (value) { - result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); - }); - } else { - Object.keys(value).forEach(function (k) { - if (isDefined(value[k])) { - result.push(encodeValue(operator, value[k], k)); - } - }); - } - } else { - const tmp = []; +function createOAuthDeviceAuth(options) { + const requestWithDefaults = options.request || request.request.defaults({ + headers: { + "user-agent": `octokit-auth-oauth-device.js/${VERSION} ${universalUserAgent.getUserAgent()}` + } + }); - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function (value) { - tmp.push(encodeValue(operator, value)); - }); - } else { - Object.keys(value).forEach(function (k) { - if (isDefined(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); - } - }); - } + const { + request: request$1 = requestWithDefaults + } = options, + otherOptions = _objectWithoutProperties(options, ["request"]); + + const state = options.clientType === "github-app" ? _objectSpread2(_objectSpread2({}, otherOptions), {}, { + clientType: "github-app", + request: request$1 + }) : _objectSpread2(_objectSpread2({}, otherOptions), {}, { + clientType: "oauth-app", + request: request$1, + scopes: options.scopes || [] + }); - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); - } - } - } - } else { - if (operator === ";") { - if (isDefined(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); - } + if (!options.clientId) { + throw new Error('[@octokit/auth-oauth-device] "clientId" option must be set (https://github.com/octokit/auth-oauth-device.js#usage)'); } - return result; -} + if (!options.onVerification) { + throw new Error('[@octokit/auth-oauth-device] "onVerification" option must be a function (https://github.com/octokit/auth-oauth-device.js#usage)'); + } // @ts-ignore too much for tsc / ts-jest ¯\_(ツ)_/¯ -function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; + + return Object.assign(auth.bind(null, state), { + hook: hook.bind(null, state) + }); } -function expand(template, context) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - return template.replace(/\{([^\{\}]+)\}|([^\{\}]+)/g, function (_, expression, literal) { - if (expression) { - let operator = ""; - const values = []; +exports.createOAuthDeviceAuth = createOAuthDeviceAuth; +//# sourceMappingURL=index.js.map - 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 = ","; +/***/ 11591: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; - } +"use strict"; - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); - } - } else { - return encodeReserved(literal); - } - }); -} -function parse(options) { - // https://fetch.spec.whatwg.org/#methods - let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible +Object.defineProperty(exports, "__esModule", ({ value: true })); - 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"]); // extract variable names from URL to calculate remaining variables later +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } - const urlVariableNames = extractUrlVariableNames(url); - url = parseUrl(url).expand(parameters); +var universalUserAgent = __nccwpck_require__(45030); +var request = __nccwpck_require__(36234); +var authOauthDevice = __nccwpck_require__(44344); +var oauthMethods = __nccwpck_require__(88445); +var btoa = _interopDefault(__nccwpck_require__(72358)); - if (!/^http/.test(url)) { - url = options.baseUrl + url; - } +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); - 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 (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); - if (!isBinaryRequest) { - if (options.mediaType.format) { - // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw - headers.accept = headers.accept.split(/,/).map(preview => preview.replace(/application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, `application/vnd$1$2.${options.mediaType.format}`)).join(","); + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); } - 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(","); - } - } // for GET/HEAD requests, set URL query parameters from remaining parameters - // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters + keys.push.apply(keys, symbols); + } + return keys; +} - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } else { - headers["content-length"] = 0; - } + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); } - } // default content-type for JSON if body is set - - - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; - } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body. - // fetch does not allow to set `content-length` header, but we can set body to an empty string + } + return target; +} - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; - } // Only return body/request keys if present - +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } - return Object.assign({ - method, - url, - headers - }, typeof body !== "undefined" ? { - body - } : null, options.request ? { - request: options.request - } : null); + return obj; } -function endpointWithDefaults(defaults, route, options) { - return parse(merge(defaults, route, options)); -} +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; -function withDefaults(oldDefaults, newDefaults) { - const DEFAULTS = merge(oldDefaults, newDefaults); - const endpoint = endpointWithDefaults.bind(null, DEFAULTS); - return Object.assign(endpoint, { - DEFAULTS, - defaults: withDefaults.bind(null, DEFAULTS), - merge: merge.bind(null, DEFAULTS), - parse - }); + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + + return target; } -const VERSION = "6.0.10"; +function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; -const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url. -// So we use RequestParameters and add method as additional required property. + var target = _objectWithoutPropertiesLoose(source, excluded); -const DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "", - previews: [] - } -}; + var key, i; -const endpoint = withDefaults(null, DEFAULTS); + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); -exports.endpoint = endpoint; -//# sourceMappingURL=index.js.map + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; + } + } + return target; +} -/***/ }), +const VERSION = "1.3.0"; -/***/ 70558: -/***/ ((__unused_webpack_module, exports) => { +async function getAuthentication(state) { + // handle code exchange form OAuth Web Flow + if ("code" in state.strategyOptions) { + const { + authentication + } = await oauthMethods.exchangeWebFlowCode(_objectSpread2(_objectSpread2({ + clientId: state.clientId, + clientSecret: state.clientSecret, + clientType: state.clientType + }, state.strategyOptions), {}, { + request: state.request + })); + return _objectSpread2({ + type: "token", + tokenType: "oauth" + }, authentication); + } // handle OAuth device flow -"use strict"; + if ("onVerification" in state.strategyOptions) { + const deviceAuth = authOauthDevice.createOAuthDeviceAuth(_objectSpread2(_objectSpread2({ + clientType: state.clientType, + clientId: state.clientId + }, state.strategyOptions), {}, { + request: state.request + })); + const authentication = await deviceAuth({ + type: "oauth" + }); + return _objectSpread2({ + clientSecret: state.clientSecret + }, authentication); + } // use existing authentication -Object.defineProperty(exports, "__esModule", ({ value: true })); -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ + if ("token" in state.strategyOptions) { + return _objectSpread2({ + type: "token", + tokenType: "oauth", + clientId: state.clientId, + clientSecret: state.clientSecret, + clientType: state.clientType + }, state.strategyOptions); + } -function isObject(o) { - return Object.prototype.toString.call(o) === '[object Object]'; + throw new Error("[@octokit/auth-oauth-user] Invalid strategy options"); } -function isPlainObject(o) { - var ctor,prot; - - 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; +async function auth(state, options = {}) { + if (!state.authentication) { + // This is what TS makes us do ¯\_(ツ)_/¯ + state.authentication = state.clientType === "oauth-app" ? await getAuthentication(state) : await getAuthentication(state); + } - // If constructor does not have an Object-specific method - if (prot.hasOwnProperty('isPrototypeOf') === false) { - return false; + if (state.authentication.invalid) { + throw new Error("[@octokit/auth-oauth-user] Token is invalid"); } - // Most likely a plain Object - return true; -} + const currentAuthentication = state.authentication; // (auto) refresh for user-to-server tokens -exports.isPlainObject = isPlainObject; + if ("expiresAt" in currentAuthentication) { + if (options.type === "refresh" || new Date(currentAuthentication.expiresAt) < new Date()) { + const { + authentication + } = await oauthMethods.refreshToken({ + clientType: "github-app", + clientId: state.clientId, + clientSecret: state.clientSecret, + refreshToken: currentAuthentication.refreshToken, + request: state.request + }); + state.authentication = _objectSpread2({ + tokenType: "oauth", + type: "token" + }, authentication); + } + } // throw error for invalid refresh call -/***/ }), + if (options.type === "refresh") { + if (state.clientType === "oauth-app") { + throw new Error("[@octokit/auth-oauth-user] OAuth Apps do not support expiring tokens"); + } -/***/ 88467: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (!currentAuthentication.hasOwnProperty("expiresAt")) { + throw new Error("[@octokit/auth-oauth-user] Refresh token missing"); + } + } // check or reset token -"use strict"; + if (options.type === "check" || options.type === "reset") { + const method = options.type === "check" ? oauthMethods.checkToken : oauthMethods.resetToken; -Object.defineProperty(exports, "__esModule", ({ value: true })); + try { + const { + authentication + } = await method({ + // @ts-expect-error making TS happy would require unnecessary code so no + clientType: state.clientType, + clientId: state.clientId, + clientSecret: state.clientSecret, + token: state.authentication.token, + request: state.request + }); + state.authentication = _objectSpread2({ + tokenType: "oauth", + type: "token" + }, authentication); + return state.authentication; + } catch (error) { + // istanbul ignore else + if (error.status === 404) { + error.message = "[@octokit/auth-oauth-user] Token is invalid"; // @ts-expect-error TBD -var request = __nccwpck_require__(36234); -var universalUserAgent = __nccwpck_require__(45030); + state.authentication.invalid = true; + } -const VERSION = "4.5.8"; + throw error; + } + } // invalidate -class GraphqlError extends Error { - constructor(request, response) { - const message = response.data.errors[0].message; - super(message); - Object.assign(this, response.data); - Object.assign(this, { - headers: response.headers - }); - this.name = "GraphqlError"; - this.request = request; // Maintains proper stack trace (only available on V8) - /* istanbul ignore next */ + if (options.type === "delete" || options.type === "deleteAuthorization") { + const method = options.type === "delete" ? oauthMethods.deleteToken : oauthMethods.deleteAuthorization; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); + try { + await method({ + // @ts-expect-error making TS happy would require unnecessary code so no + clientType: state.clientType, + clientId: state.clientId, + clientSecret: state.clientSecret, + token: state.authentication.token, + request: state.request + }); + } catch (error) { + // istanbul ignore if + if (error.status !== 404) throw error; } + + state.authentication.invalid = true; + return state.authentication; } + return state.authentication; } -const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"]; -const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; -function graphql(request, query, options) { - if (typeof query === "string" && options && "query" in options) { - return Promise.reject(new Error(`[@octokit/graphql] "query" 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; - } +/** + * The following endpoints require an OAuth App to authenticate using its client_id and client_secret. + * + * - [`POST /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#check-a-token) - Check a token + * - [`PATCH /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#reset-a-token) - Reset a token + * - [`POST /applications/{client_id}/token/scoped`](https://docs.github.com/en/rest/reference/apps#create-a-scoped-access-token) - Create a scoped access token + * - [`DELETE /applications/{client_id}/token`](https://docs.github.com/en/rest/reference/apps#delete-an-app-token) - Delete an app token + * - [`DELETE /applications/{client_id}/grant`](https://docs.github.com/en/rest/reference/apps#delete-an-app-authorization) - Delete an app authorization + * + * deprecated: + * + * - [`GET /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#check-an-authorization) - Check an authorization + * - [`POST /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#reset-an-authorization) - Reset an authorization + * - [`DELETE /applications/{client_id}/tokens/{access_token}`](https://docs.github.com/en/rest/reference/apps#revoke-an-authorization-for-an-application) - Revoke an authorization for an application + * - [`DELETE /applications/{client_id}/grants/{access_token}`](https://docs.github.com/en/rest/reference/apps#revoke-a-grant-for-an-application) - Revoke a grant for an application + */ +const ROUTES_REQUIRING_BASIC_AUTH = /\/applications\/[^/]+\/(token|grant)s?/; +function requiresBasicAuth(url) { + return url && ROUTES_REQUIRING_BASIC_AUTH.test(url); +} - if (!result.variables) { - result.variables = {}; - } +async function hook(state, request, route, parameters = {}) { + const endpoint = request.endpoint.merge(route, parameters); // Do not intercept OAuth Web/Device flow request - result.variables[key] = parsedOptions[key]; - return result; - }, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix - // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451 + if (/\/login\/(oauth\/access_token|device\/code)$/.test(endpoint.url)) { + return request(endpoint); + } - const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl; + if (requiresBasicAuth(endpoint.url)) { + const credentials = btoa(`${state.clientId}:${state.clientSecret}`); + endpoint.headers.authorization = `basic ${credentials}`; + return request(endpoint); + } // TS makes us do this ¯\_(ツ)_/¯ - if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { - requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); - } - return request(requestOptions).then(response => { - if (response.data.errors) { - const headers = {}; + const { + token + } = state.clientType === "oauth-app" ? await auth(_objectSpread2(_objectSpread2({}, state), {}, { + request + })) : await auth(_objectSpread2(_objectSpread2({}, state), {}, { + request + })); + endpoint.headers.authorization = "token " + token; + return request(endpoint); +} - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; +const _excluded = ["clientId", "clientSecret", "clientType", "request"]; +function createOAuthUserAuth(_ref) { + let { + clientId, + clientSecret, + clientType = "oauth-app", + request: request$1 = request.request.defaults({ + headers: { + "user-agent": `octokit-auth-oauth-app.js/${VERSION} ${universalUserAgent.getUserAgent()}` } + }) + } = _ref, + strategyOptions = _objectWithoutProperties(_ref, _excluded); - throw new GraphqlError(requestOptions, { - headers, - data: response.data - }); - } + const state = Object.assign({ + clientType, + clientId, + clientSecret, + strategyOptions, + request: request$1 + }); // @ts-expect-error not worth the extra code needed to appease TS - return response.data.data; + return Object.assign(auth.bind(null, state), { + // @ts-expect-error not worth the extra code needed to appease TS + hook: hook.bind(null, state) }); } +createOAuthUserAuth.VERSION = VERSION; -function withDefaults(request$1, newDefaults) { - const newRequest = request$1.defaults(newDefaults); +exports.createOAuthUserAuth = createOAuthUserAuth; +exports.requiresBasicAuth = requiresBasicAuth; +//# sourceMappingURL=index.js.map - const newApi = (query, options) => { - return graphql(newRequest, query, options); + +/***/ }), + +/***/ 40334: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +async function auth(token) { + const tokenType = token.split(/\./).length === 3 ? "app" : /^v\d+\./.test(token) ? "installation" : "oauth"; + return { + type: "token", + token: token, + tokenType }; +} - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: request.request.endpoint - }); +/** + * Prefix token for usage in the Authorization header + * + * @param token OAuth token or JSON Web Token + */ +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; + } + + return `token ${token}`; } -const graphql$1 = withDefaults(request.request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}` - }, - method: "POST", - url: "/graphql" -}); -function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" - }); +async function hook(token, request, route, parameters) { + const endpoint = request.endpoint.merge(route, parameters); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); } -exports.graphql = graphql$1; -exports.withCustomRequest = withCustomRequest; +const createTokenAuth = function createTokenAuth(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) + }); +}; + +exports.createTokenAuth = createTokenAuth; //# sourceMappingURL=index.js.map /***/ }), -/***/ 25823: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 79567: +/***/ ((__unused_webpack_module, exports) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -var requestError = __nccwpck_require__(10537); - -const VERSION = "1.2.8"; +async function auth(reason) { + return { + type: "unauthenticated", + reason + }; +} -function isIssueLabelsUpdateOrReplace({ - method, - url -}) { - if (!["POST", "PUT"].includes(method)) { +function isRateLimitError(error) { + if (error.status !== 403) { return false; } + /* istanbul ignore if */ + - if (!/\/repos\/[^/]+\/[^/]+\/issues\/[^/]+\/labels/.test(url)) { + if (!error.response) { return false; } - return true; + return error.response.headers["x-ratelimit-remaining"] === "0"; } -function enterpriseCompatibility(octokit) { - octokit.hook.wrap("request", async (request, options) => { - // see https://github.com/octokit/rest.js/blob/15.x/lib/routes.json#L3046-L3068 - if (isIssueLabelsUpdateOrReplace(options)) { - options.data = options.labels; - delete options.labels; // for @octokit/rest v16.x, remove validation of labels option - - /* istanbul ignore if */ +const REGEX_ABUSE_LIMIT_MESSAGE = /\babuse\b/i; +function isAbuseLimitError(error) { + if (error.status !== 403) { + return false; + } - if (options.request.validate) { - delete options.request.validate.labels; - } + return REGEX_ABUSE_LIMIT_MESSAGE.test(error.message); +} - return request(options); - } // TODO: implement fix for #62 here - // https://github.com/octokit/plugin-enterprise-compatibility.js/issues/60 +async function hook(reason, request, route, parameters) { + const endpoint = request.endpoint.merge(route, parameters); + return request(endpoint).catch(error => { + if (error.status === 404) { + error.message = `Not found. May be due to lack of authentication. Reason: ${reason}`; + throw error; + } + if (isRateLimitError(error)) { + error.message = `API rate limit exceeded. This maybe caused by the lack of authentication. Reason: ${reason}`; + throw error; + } - if (/\/orgs\/[^/]+\/teams/.test(options.url)) { - try { - return await request(options); - } catch (error) { - if (error.status !== 404) { - throw error; - } + if (isAbuseLimitError(error)) { + error.message = `You have triggered an abuse detection mechanism. This maybe caused by the lack of authentication. Reason: ${reason}`; + throw error; + } - if (!error.headers || !error.headers["x-github-enterprise-version"]) { - throw error; - } + if (error.status === 401) { + error.message = `Unauthorized. "${endpoint.method} ${endpoint.url}" failed most likely due to lack of authentication. Reason: ${reason}`; + throw error; + } - const deprecatedUrl = options.url.replace(/\/orgs\/[^/]+\/teams\/[^/]+/, "/teams/{team_id}"); - throw new requestError.RequestError(`"${options.method} ${options.url}" is not supported in your GitHub Enterprise Server version. Please replace with octokit.request("${options.method} ${deprecatedUrl}", { team_id })`, 404, { - request: options - }); - } + if (error.status >= 400 && error.status < 500) { + error.message = error.message.replace(/\.?$/, `. May be caused by lack of authentication (${reason}).`); } - return request(options); + throw error; }); } -enterpriseCompatibility.VERSION = VERSION; -exports.enterpriseCompatibility = enterpriseCompatibility; +const createUnauthenticatedAuth = function createUnauthenticatedAuth(options) { + if (!options || !options.reason) { + throw new Error("[@octokit/auth-unauthenticated] No reason passed to createUnauthenticatedAuth"); + } + + return Object.assign(auth.bind(null, options.reason), { + hook: hook.bind(null, options.reason) + }); +}; + +exports.createUnauthenticatedAuth = createUnauthenticatedAuth; //# sourceMappingURL=index.js.map /***/ }), -/***/ 64193: -/***/ ((__unused_webpack_module, exports) => { +/***/ 76762: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const VERSION = "2.6.2"; - -/** - * Some “list” response that can be paginated have a different response structure - * - * They have a `total_count` key in the response (search also has `incomplete_results`, - * /installation/repositories also has `repository_selection`), as well as a key with - * the list of the items which name varies from endpoint to endpoint. - * - * Octokit normalizes these responses so that paginated results are always returned following - * the same structure. One challenge is that if the list response has only one page, no Link - * header is provided, so this header alone is not sufficient to check wether a response is - * paginated or not. - * - * We check if a "total_count" key is present in the response data, but also make sure that - * a "url" property is not, as the "Get the combined status for a specific ref" endpoint would - * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref - */ -function normalizePaginatedListResponse(response) { - const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); - if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way - // to retrieve the same information. - - const incompleteResults = response.data.incomplete_results; - const repositorySelection = response.data.repository_selection; - const totalCount = response.data.total_count; - delete response.data.incomplete_results; - delete response.data.repository_selection; - delete response.data.total_count; - const namespaceKey = Object.keys(response.data)[0]; - const data = response.data[namespaceKey]; - response.data = data; +var universalUserAgent = __nccwpck_require__(45030); +var beforeAfterHook = __nccwpck_require__(83682); +var request = __nccwpck_require__(36234); +var graphql = __nccwpck_require__(88467); +var authToken = __nccwpck_require__(40334); - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; - } +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; } - response.data.total_count = totalCount; - return response; + return target; } -function iterator(octokit, route, parameters) { - const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); - const requestMethod = typeof route === "function" ? route : octokit.request; - const method = options.method; - const headers = options.headers; - let url = options.url; - return { - [Symbol.asyncIterator]: () => ({ - async next() { - if (!url) return { - done: true - }; - const response = await requestMethod({ - method, - url, - headers - }); - const normalizedResponse = normalizePaginatedListResponse(response); // `response.headers.link` format: - // '; rel="next", ; rel="last"' - // sets `url` to undefined if "next" URL is not present or `link` header is not set +function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; - url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; - return { - value: normalizedResponse - }; - } + var target = _objectWithoutPropertiesLoose(source, excluded); - }) - }; -} + var key, i; -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = undefined; + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; + } } - return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn); + return target; } -function gather(octokit, results, iterator, mapFn) { - return iterator.next().then(result => { - if (result.done) { - return results; - } +const VERSION = "3.5.1"; - let earlyExit = false; +const _excluded = ["authStrategy"]; +class Octokit { + constructor(options = {}) { + const hook = new beforeAfterHook.Collection(); + const requestDefaults = { + baseUrl: request.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: "" + } + }; // prepend default user agent with `options.userAgent` if set - function done() { - earlyExit = true; - } + requestDefaults.headers["user-agent"] = [options.userAgent, `octokit-core.js/${VERSION} ${universalUserAgent.getUserAgent()}`].filter(Boolean).join(" "); - results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data); + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; + } - if (earlyExit) { - return results; + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; } - return gather(octokit, results, iterator, mapFn); - }); -} + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } -const composePaginateRest = Object.assign(paginate, { - iterator -}); + this.request = request.request.defaults(requestDefaults); + this.graphql = graphql.withCustomRequest(this.request).defaults(requestDefaults); + this.log = Object.assign({ + debug: () => {}, + info: () => {}, + warn: console.warn.bind(console), + error: console.error.bind(console) + }, options.log); + this.hook = hook; // (1) If neither `options.authStrategy` nor `options.auth` are set, the `octokit` instance + // is unauthenticated. The `this.auth()` method is a no-op and no request hook is registered. + // (2) If only `options.auth` is set, use the default token authentication strategy. + // (3) If `options.authStrategy` is set then use it and pass in `options.auth`. Always pass own request as many strategies accept a custom request instance. + // TODO: type `options.auth` based on `options.authStrategy`. -/** - * @param octokit Octokit instance - * @param options Options passed to Octokit constructor - */ + if (!options.authStrategy) { + if (!options.auth) { + // (1) + this.auth = async () => ({ + type: "unauthenticated" + }); + } else { + // (2) + const auth = authToken.createTokenAuth(options.auth); // @ts-ignore ¯\_(ツ)_/¯ + + hook.wrap("request", auth.hook); + this.auth = auth; + } + } else { + const { + authStrategy + } = options, + otherOptions = _objectWithoutProperties(options, _excluded); + + 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)); // @ts-ignore ¯\_(ツ)_/¯ + + hook.wrap("request", auth.hook); + this.auth = auth; + } // apply plugins + // https://stackoverflow.com/a/16345172 + + + const classConstructor = this.constructor; + classConstructor.plugins.forEach(plugin => { + Object.assign(this, plugin(this, options)); + }); + } + + 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; + } -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; } -paginateRest.VERSION = VERSION; +Octokit.VERSION = VERSION; +Octokit.plugins = []; -exports.composePaginateRest = composePaginateRest; -exports.paginateRest = paginateRest; +exports.Octokit = Octokit; //# sourceMappingURL=index.js.map /***/ }), -/***/ 83044: -/***/ ((__unused_webpack_module, exports) => { +/***/ 59440: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; Object.defineProperty(exports, "__esModule", ({ value: true })); -const Endpoints = { - actions: { - addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], - cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"], - createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], - createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"], - createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"], - createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], - createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"], - createWorkflowDispatch: ["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"], - deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], - deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"], - deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"], - deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], - deleteWorkflowRunLogs: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], - disableSelectedRepositoryGithubActionsOrganization: ["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"], - disableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"], - downloadArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"], - downloadJobLogsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"], - downloadWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], - enableSelectedRepositoryGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"], - enableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"], - getAllowedActionsOrganization: ["GET /orgs/{org}/actions/permissions/selected-actions"], - getAllowedActionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"], - getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - getGithubActionsPermissionsOrganization: ["GET /orgs/{org}/actions/permissions"], - getGithubActionsPermissionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions"], - getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], - getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], - getRepoPermissions: ["GET /repos/{owner}/{repo}/actions/permissions", {}, { - renamed: ["actions", "getGithubActionsPermissionsRepository"] - }], - getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], - getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], - getSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"], - getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], - getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], - getWorkflowRunUsage: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"], - getWorkflowUsage: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"], - listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], - listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"], - listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], - listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], - listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], - listRunnerApplicationsForRepo: ["GET /repos/{owner}/{repo}/actions/runners/downloads"], - listSelectedReposForOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"], - listSelectedRepositoriesEnabledGithubActionsOrganization: ["GET /orgs/{org}/actions/permissions/repositories"], - listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], - listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], - listWorkflowRunArtifacts: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"], - listWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"], - listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], - reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], - removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], - setAllowedActionsOrganization: ["PUT /orgs/{org}/actions/permissions/selected-actions"], - setAllowedActionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"], - setGithubActionsPermissionsOrganization: ["PUT /orgs/{org}/actions/permissions"], - setGithubActionsPermissionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions"], - setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"], - setSelectedRepositoriesEnabledGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories"] - }, - activity: { - checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], - deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], - deleteThreadSubscription: ["DELETE /notifications/threads/{thread_id}/subscription"], - getFeeds: ["GET /feeds"], - getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], - getThread: ["GET /notifications/threads/{thread_id}"], - getThreadSubscriptionForAuthenticatedUser: ["GET /notifications/threads/{thread_id}/subscription"], - listEventsForAuthenticatedUser: ["GET /users/{username}/events"], - listNotificationsForAuthenticatedUser: ["GET /notifications"], - listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"], - listPublicEvents: ["GET /events"], - listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], - listPublicEventsForUser: ["GET /users/{username}/events/public"], - listPublicOrgEvents: ["GET /orgs/{org}/events"], - listReceivedEventsForUser: ["GET /users/{username}/received_events"], - listReceivedPublicEventsForUser: ["GET /users/{username}/received_events/public"], - listRepoEvents: ["GET /repos/{owner}/{repo}/events"], - listRepoNotificationsForAuthenticatedUser: ["GET /repos/{owner}/{repo}/notifications"], - listReposStarredByAuthenticatedUser: ["GET /user/starred"], - listReposStarredByUser: ["GET /users/{username}/starred"], - listReposWatchedByUser: ["GET /users/{username}/subscriptions"], - listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], - listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], - listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], - markNotificationsAsRead: ["PUT /notifications"], - markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], - markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], - setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], - setThreadSubscription: ["PUT /notifications/threads/{thread_id}/subscription"], - starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], - unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] - }, - apps: { - addRepoToInstallation: ["PUT /user/installations/{installation_id}/repositories/{repository_id}"], - checkToken: ["POST /applications/{client_id}/token"], - createContentAttachment: ["POST /content_references/{content_reference_id}/attachments", { - mediaType: { - previews: ["corsair"] - } - }], - createFromManifest: ["POST /app-manifests/{code}/conversions"], - createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens"], - deleteAuthorization: ["DELETE /applications/{client_id}/grant"], - deleteInstallation: ["DELETE /app/installations/{installation_id}"], - deleteToken: ["DELETE /applications/{client_id}/token"], - getAuthenticated: ["GET /app"], - getBySlug: ["GET /apps/{app_slug}"], - getInstallation: ["GET /app/installations/{installation_id}"], - getOrgInstallation: ["GET /orgs/{org}/installation"], - getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], - getSubscriptionPlanForAccount: ["GET /marketplace_listing/accounts/{account_id}"], - getSubscriptionPlanForAccountStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}"], - getUserInstallation: ["GET /users/{username}/installation"], - getWebhookConfigForApp: ["GET /app/hook/config"], - listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], - listAccountsForPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"], - listInstallationReposForAuthenticatedUser: ["GET /user/installations/{installation_id}/repositories"], - listInstallations: ["GET /app/installations"], - listInstallationsForAuthenticatedUser: ["GET /user/installations"], - listPlans: ["GET /marketplace_listing/plans"], - listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], - listReposAccessibleToInstallation: ["GET /installation/repositories"], - listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], - listSubscriptionsForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed"], - removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}"], - resetToken: ["PATCH /applications/{client_id}/token"], - revokeInstallationAccessToken: ["DELETE /installation/token"], - suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], - unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"], - updateWebhookConfigForApp: ["PATCH /app/hook/config"] - }, - billing: { - getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], - getGithubActionsBillingUser: ["GET /users/{username}/settings/billing/actions"], - getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], - getGithubPackagesBillingUser: ["GET /users/{username}/settings/billing/packages"], - getSharedStorageBillingOrg: ["GET /orgs/{org}/settings/billing/shared-storage"], - getSharedStorageBillingUser: ["GET /users/{username}/settings/billing/shared-storage"] - }, - checks: { - create: ["POST /repos/{owner}/{repo}/check-runs"], - createSuite: ["POST /repos/{owner}/{repo}/check-suites"], - get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], - getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], - listAnnotations: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"], - listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], - listForSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"], - listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], - rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"], - setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences"], - update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] - }, - codeScanning: { - getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", {}, { - renamedParameters: { - alert_id: "alert_number" - } - }], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], - listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], - updateAlert: ["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"], - uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] - }, - codesOfConduct: { - getAllCodesOfConduct: ["GET /codes_of_conduct", { - mediaType: { - previews: ["scarlet-witch"] +var isPlainObject = __nccwpck_require__(63287); +var universalUserAgent = __nccwpck_require__(45030); + +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.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 removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === undefined) { + delete obj[key]; + } + } + + return obj; +} + +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); + } // lowercase header names before merging with defaults to avoid duplicates + + + options.headers = lowercaseKeys(options.headers); // remove properties with undefined values before merging + + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); // mediaType.previews arrays are merged, instead of overwritten + + 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; +} + +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("&"); +} + +const 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), []); +} + +function omit(object, keysToOmit) { + return Object.keys(object).filter(option => !keysToOmit.includes(option)).reduce((obj, key) => { + obj[key] = object[key]; + return obj; + }, {}); +} + +// Based on https://github.com/bramstein/url-template, licensed under BSD +// TODO: create separate package. +// +// Copyright (c) 2012-2014, Bram Stein +// All rights reserved. +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions +// are met: +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the distribution. +// 3. The name of the author may not be used to endorse or promote products +// derived from this software without specific prior written permission. +// THIS SOFTWARE IS PROVIDED BY THE AUTHOR "AS IS" AND ANY EXPRESS OR IMPLIED +// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO +// EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, +// INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, +// BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY +// OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +/* istanbul ignore file */ +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; + } +} + +function isDefined(value) { + return value !== undefined && 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)); } - }], - getConductCode: ["GET /codes_of_conduct/{key}", { - mediaType: { - previews: ["scarlet-witch"] + + result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function (value) { + result.push(encodeValue(operator, value, isKeyOperator(operator) ? key : "")); + }); + } else { + Object.keys(value).forEach(function (k) { + if (isDefined(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function (value) { + tmp.push(encodeValue(operator, value)); + }); + } 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(",")); + } } - }], - getForRepo: ["GET /repos/{owner}/{repo}/community/code_of_conduct", { - mediaType: { - previews: ["scarlet-witch"] + } + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); } - }] - }, - emojis: { - get: ["GET /emojis"] - }, - enterpriseAdmin: { - disableSelectedOrganizationGithubActionsEnterprise: ["DELETE /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"], - enableSelectedOrganizationGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"], - getAllowedActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/selected-actions"], - getGithubActionsPermissionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions"], - listSelectedOrganizationsEnabledGithubActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/organizations"], - setAllowedActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/selected-actions"], - setGithubActionsPermissionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions"], - setSelectedOrganizationsEnabledGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations"] - }, + } 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) + }; +} + +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(","); + } + } else { + return encodeReserved(literal); + } + }); +} + +function parse(options) { + // https://fetch.spec.whatwg.org/#methods + let method = options.method.toUpperCase(); // replace :varname with {varname} to make it RFC 6570 compatible + + 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"]); // extract variable names from URL to calculate remaining variables later + + 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) { + // e.g. application/vnd.github.v3+json => application/vnd.github.v3.raw + 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(","); + } + } // for GET/HEAD requests, set URL query parameters from remaining parameters + // for PATCH/POST/PUT/DELETE requests, set request body from remaining parameters + + + if (["GET", "HEAD"].includes(method)) { + url = addQueryParameters(url, remainingParameters); + } else { + if ("data" in remainingParameters) { + body = remainingParameters.data; + } else { + if (Object.keys(remainingParameters).length) { + body = remainingParameters; + } else { + headers["content-length"] = 0; + } + } + } // default content-type for JSON if body is set + + + if (!headers["content-type"] && typeof body !== "undefined") { + headers["content-type"] = "application/json; charset=utf-8"; + } // GitHub expects 'content-length: 0' header for PUT/PATCH requests without body. + // fetch does not allow to set `content-length` header, but we can set body to an empty string + + + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; + } // Only return body/request keys if present + + + return Object.assign({ + method, + url, + headers + }, typeof body !== "undefined" ? { + body + } : null, options.request ? { + request: options.request + } : null); +} + +function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); +} + +function withDefaults(oldDefaults, newDefaults) { + const DEFAULTS = merge(oldDefaults, newDefaults); + const endpoint = endpointWithDefaults.bind(null, DEFAULTS); + return Object.assign(endpoint, { + DEFAULTS, + defaults: withDefaults.bind(null, DEFAULTS), + merge: merge.bind(null, DEFAULTS), + parse + }); +} + +const VERSION = "6.0.12"; + +const userAgent = `octokit-endpoint.js/${VERSION} ${universalUserAgent.getUserAgent()}`; // DEFAULTS has all properties set that EndpointOptions has, except url. +// So we use RequestParameters and add method as additional required property. + +const DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "", + previews: [] + } +}; + +const endpoint = withDefaults(null, DEFAULTS); + +exports.endpoint = endpoint; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 88467: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var request = __nccwpck_require__(36234); +var universalUserAgent = __nccwpck_require__(45030); + +const VERSION = "4.6.4"; + +class GraphqlError extends Error { + constructor(request, response) { + const message = response.data.errors[0].message; + super(message); + Object.assign(this, response.data); + Object.assign(this, { + headers: response.headers + }); + this.name = "GraphqlError"; + this.request = request; // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } + +} + +const NON_VARIABLE_OPTIONS = ["method", "baseUrl", "url", "headers", "request", "query", "mediaType"]; +const FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; +const GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; +function graphql(request, 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`)); + } + } + + 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]; + return result; + }, {}); // workaround for GitHub Enterprise baseUrl set with /api/v3 suffix + // https://github.com/octokit/auth-app.js/issues/111#issuecomment-657610451 + + const baseUrl = parsedOptions.baseUrl || request.endpoint.DEFAULTS.baseUrl; + + if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { + requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); + } + + return request(requestOptions).then(response => { + if (response.data.errors) { + const headers = {}; + + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } + + throw new GraphqlError(requestOptions, { + headers, + data: response.data + }); + } + + return response.data.data; + }); +} + +function withDefaults(request$1, newDefaults) { + const newRequest = request$1.defaults(newDefaults); + + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: request.request.endpoint + }); +} + +const graphql$1 = withDefaults(request.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${universalUserAgent.getUserAgent()}` + }, + method: "POST", + url: "/graphql" +}); +function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); +} + +exports.graphql = graphql$1; +exports.withCustomRequest = withCustomRequest; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 51017: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function oauthAuthorizationUrl(options) { + const clientType = options.clientType || "oauth-app"; + const baseUrl = options.baseUrl || "https://github.com"; + const result = { + clientType, + allowSignup: options.allowSignup === false ? false : true, + clientId: options.clientId, + login: options.login || null, + redirectUrl: options.redirectUrl || null, + state: options.state || Math.random().toString(36).substr(2), + url: "" + }; + + if (clientType === "oauth-app") { + const scopes = "scopes" in options ? options.scopes : []; + result.scopes = typeof scopes === "string" ? scopes.split(/[,\s]+/).filter(Boolean) : scopes; + } + + result.url = urlBuilderAuthorize(`${baseUrl}/login/oauth/authorize`, result); + return result; +} + +function urlBuilderAuthorize(base, options) { + const map = { + allowSignup: "allow_signup", + clientId: "client_id", + login: "login", + redirectUrl: "redirect_uri", + scopes: "scope", + state: "state" + }; + let url = base; + Object.keys(map) // Filter out keys that are null and remove the url key + .filter(k => options[k] !== null) // Filter out empty scopes array + .filter(k => { + if (k !== "scopes") return true; + if (options.clientType === "github-app") return false; + return !Array.isArray(options[k]) || options[k].length > 0; + }) // Map Array with the proper URL parameter names and change the value to a string using template strings + // @ts-ignore + .map(key => [map[key], `${options[key]}`]) // Finally, build the URL + .forEach(([key, value], index) => { + url += index === 0 ? `?` : "&"; + url += `${key}=${encodeURIComponent(value)}`; + }); + return url; +} + +exports.oauthAuthorizationUrl = oauthAuthorizationUrl; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 88445: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } + +var oauthAuthorizationUrl = __nccwpck_require__(51017); +var request = __nccwpck_require__(36234); +var requestError = __nccwpck_require__(10537); +var btoa = _interopDefault(__nccwpck_require__(72358)); + +const VERSION = "1.2.4"; + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + } + + keys.push.apply(keys, symbols); + } + + return keys; +} + +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; +} + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +function _objectWithoutPropertiesLoose(source, excluded) { + if (source == null) return {}; + var target = {}; + var sourceKeys = Object.keys(source); + var key, i; + + for (i = 0; i < sourceKeys.length; i++) { + key = sourceKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + target[key] = source[key]; + } + + return target; +} + +function _objectWithoutProperties(source, excluded) { + if (source == null) return {}; + + var target = _objectWithoutPropertiesLoose(source, excluded); + + var key, i; + + if (Object.getOwnPropertySymbols) { + var sourceSymbolKeys = Object.getOwnPropertySymbols(source); + + for (i = 0; i < sourceSymbolKeys.length; i++) { + key = sourceSymbolKeys[i]; + if (excluded.indexOf(key) >= 0) continue; + if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; + target[key] = source[key]; + } + } + + return target; +} + +function requestToOAuthBaseUrl(request) { + const endpointDefaults = request.endpoint.DEFAULTS; + return /^https:\/\/(api\.)?github\.com$/.test(endpointDefaults.baseUrl) ? "https://github.com" : endpointDefaults.baseUrl.replace("/api/v3", ""); +} +async function oauthRequest(request, route, parameters) { + const withOAuthParameters = _objectSpread2({ + baseUrl: requestToOAuthBaseUrl(request), + headers: { + accept: "application/json" + } + }, parameters); + + const response = await request(route, withOAuthParameters); + + if ("error" in response.data) { + const error = new requestError.RequestError(`${response.data.error_description} (${response.data.error}, ${response.data.error_uri})`, 400, { + request: request.endpoint.merge(route, withOAuthParameters), + headers: response.headers + }); // @ts-ignore add custom response property until https://github.com/octokit/request-error.js/issues/169 is resolved + + error.response = response; + throw error; + } + + return response; +} + +const _excluded = ["request"]; +function getWebFlowAuthorizationUrl(_ref) { + let { + request: request$1 = request.request + } = _ref, + options = _objectWithoutProperties(_ref, _excluded); + + const baseUrl = requestToOAuthBaseUrl(request$1); // @ts-expect-error TypeScript wants `clientType` to be set explicitly ¯\_(ツ)_/¯ + + return oauthAuthorizationUrl.oauthAuthorizationUrl(_objectSpread2(_objectSpread2({}, options), {}, { + baseUrl + })); +} + +async function exchangeWebFlowCode(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const response = await oauthRequest(request$1, "POST /login/oauth/access_token", { + client_id: options.clientId, + client_secret: options.clientSecret, + code: options.code, + redirect_uri: options.redirectUrl, + state: options.state + }); + const authentication = { + clientType: options.clientType, + clientId: options.clientId, + clientSecret: options.clientSecret, + token: response.data.access_token, + scopes: response.data.scope.split(/\s+/).filter(Boolean) + }; + + if (options.clientType === "github-app") { + if ("refresh_token" in response.data) { + const apiTimeInMs = new Date(response.headers.date).getTime(); + authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp(apiTimeInMs, response.data.expires_in), authentication.refreshTokenExpiresAt = toTimestamp(apiTimeInMs, response.data.refresh_token_expires_in); + } + + delete authentication.scopes; + } + + return _objectSpread2(_objectSpread2({}, response), {}, { + authentication + }); +} + +function toTimestamp(apiTimeInMs, expirationInSeconds) { + return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString(); +} + +async function createDeviceCode(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const parameters = { + client_id: options.clientId + }; + + if ("scopes" in options && Array.isArray(options.scopes)) { + parameters.scope = options.scopes.join(" "); + } + + return oauthRequest(request$1, "POST /login/device/code", parameters); +} + +async function exchangeDeviceCode(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const response = await oauthRequest(request$1, "POST /login/oauth/access_token", { + client_id: options.clientId, + device_code: options.code, + grant_type: "urn:ietf:params:oauth:grant-type:device_code" + }); + const authentication = { + clientType: options.clientType, + clientId: options.clientId, + token: response.data.access_token, + scopes: response.data.scope.split(/\s+/).filter(Boolean) + }; + + if ("clientSecret" in options) { + authentication.clientSecret = options.clientSecret; + } + + if (options.clientType === "github-app") { + if ("refresh_token" in response.data) { + const apiTimeInMs = new Date(response.headers.date).getTime(); + authentication.refreshToken = response.data.refresh_token, authentication.expiresAt = toTimestamp$1(apiTimeInMs, response.data.expires_in), authentication.refreshTokenExpiresAt = toTimestamp$1(apiTimeInMs, response.data.refresh_token_expires_in); + } + + delete authentication.scopes; + } + + return _objectSpread2(_objectSpread2({}, response), {}, { + authentication + }); +} + +function toTimestamp$1(apiTimeInMs, expirationInSeconds) { + return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString(); +} + +async function checkToken(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const response = await request$1("POST /applications/{client_id}/token", { + headers: { + authorization: `basic ${btoa(`${options.clientId}:${options.clientSecret}`)}` + }, + client_id: options.clientId, + access_token: options.token + }); + const authentication = { + clientType: options.clientType, + clientId: options.clientId, + clientSecret: options.clientSecret, + token: options.token, + scopes: response.data.scopes + }; + + if (options.clientType === "github-app") { + delete authentication.scopes; + } + + return _objectSpread2(_objectSpread2({}, response), {}, { + authentication + }); +} + +async function refreshToken(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const response = await oauthRequest(request$1, "POST /login/oauth/access_token", { + client_id: options.clientId, + client_secret: options.clientSecret, + grant_type: "refresh_token", + refresh_token: options.refreshToken + }); + const apiTimeInMs = new Date(response.headers.date).getTime(); + const authentication = { + clientType: "github-app", + clientId: options.clientId, + clientSecret: options.clientSecret, + token: response.data.access_token, + refreshToken: response.data.refresh_token, + expiresAt: toTimestamp$2(apiTimeInMs, response.data.expires_in), + refreshTokenExpiresAt: toTimestamp$2(apiTimeInMs, response.data.refresh_token_expires_in) + }; + return _objectSpread2(_objectSpread2({}, response), {}, { + authentication + }); +} + +function toTimestamp$2(apiTimeInMs, expirationInSeconds) { + return new Date(apiTimeInMs + expirationInSeconds * 1000).toISOString(); +} + +const _excluded$1 = ["request", "clientType", "clientId", "clientSecret", "token"]; +async function scopeToken(options) { + const { + request: request$1, + clientType, + clientId, + clientSecret, + token + } = options, + requestOptions = _objectWithoutProperties(options, _excluded$1); + + const response = await (request$1 || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request)("POST /applications/{client_id}/token/scoped", _objectSpread2({ + headers: { + authorization: `basic ${btoa(`${clientId}:${clientSecret}`)}` + }, + client_id: clientId, + access_token: token + }, requestOptions)); + const authentication = { + clientType, + clientId, + clientSecret, + token: response.data.token + }; + return _objectSpread2(_objectSpread2({}, response), {}, { + authentication + }); +} + +async function resetToken(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const auth = btoa(`${options.clientId}:${options.clientSecret}`); + const response = await request$1("PATCH /applications/{client_id}/token", { + headers: { + authorization: `basic ${auth}` + }, + client_id: options.clientId, + access_token: options.token + }); + const authentication = { + clientType: options.clientType, + clientId: options.clientId, + clientSecret: options.clientSecret, + token: response.data.token, + scopes: response.data.scopes + }; + + if (options.clientType === "github-app") { + delete authentication.scopes; + } + + return _objectSpread2(_objectSpread2({}, response), {}, { + authentication + }); +} + +async function deleteToken(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const auth = btoa(`${options.clientId}:${options.clientSecret}`); + return request$1("DELETE /applications/{client_id}/token", { + headers: { + authorization: `basic ${auth}` + }, + client_id: options.clientId, + access_token: options.token + }); +} + +async function deleteAuthorization(options) { + const request$1 = options.request || + /* istanbul ignore next: we always pass a custom request in tests */ + request.request; + const auth = btoa(`${options.clientId}:${options.clientSecret}`); + return request$1("DELETE /applications/{client_id}/grant", { + headers: { + authorization: `basic ${auth}` + }, + client_id: options.clientId, + access_token: options.token + }); +} + +exports.VERSION = VERSION; +exports.checkToken = checkToken; +exports.createDeviceCode = createDeviceCode; +exports.deleteAuthorization = deleteAuthorization; +exports.deleteToken = deleteToken; +exports.exchangeDeviceCode = exchangeDeviceCode; +exports.exchangeWebFlowCode = exchangeWebFlowCode; +exports.getWebFlowAuthorizationUrl = getWebFlowAuthorizationUrl; +exports.refreshToken = refreshToken; +exports.resetToken = resetToken; +exports.scopeToken = scopeToken; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 25823: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +var requestError = __nccwpck_require__(10537); + +const VERSION = "1.3.0"; + +function enterpriseCompatibility(octokit) { + octokit.hook.wrap("request", async (request, options) => { + // TODO: implement fix for #62 here + // https://github.com/octokit/plugin-enterprise-compatibility.js/issues/60 + if (/\/orgs\/[^/]+\/teams/.test(options.url)) { + try { + return await request(options); + } catch (error) { + if (error.status !== 404) { + throw error; + } + + if (!error.response || !error.response.headers["x-github-enterprise-version"]) { + throw error; + } + + const deprecatedUrl = options.url.replace(/\/orgs\/[^/]+\/teams\/[^/]+/, "/teams/{team_id}"); + throw new requestError.RequestError(`"${options.method} ${options.url}" is not supported in your GitHub Enterprise Server version. Please replace with octokit.request("${options.method} ${deprecatedUrl}", { team_id })`, 404, { + request: options + }); + } + } + + return request(options); + }); +} +enterpriseCompatibility.VERSION = VERSION; + +exports.enterpriseCompatibility = enterpriseCompatibility; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 64193: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +const VERSION = "2.15.1"; + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + } + + keys.push.apply(keys, symbols); + } + + return keys; +} + +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; +} + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +/** + * Some “list” response that can be paginated have a different response structure + * + * They have a `total_count` key in the response (search also has `incomplete_results`, + * /installation/repositories also has `repository_selection`), as well as a key with + * the list of the items which name varies from endpoint to endpoint. + * + * Octokit normalizes these responses so that paginated results are always returned following + * the same structure. One challenge is that if the list response has only one page, no Link + * header is provided, so this header alone is not sufficient to check wether a response is + * paginated or not. + * + * We check if a "total_count" key is present in the response data, but also make sure that + * a "url" property is not, as the "Get the combined status for a specific ref" endpoint would + * otherwise match: https://developer.github.com/v3/repos/statuses/#get-the-combined-status-for-a-specific-ref + */ +function normalizePaginatedListResponse(response) { + // endpoints can respond with 204 if repository is empty + if (!response.data) { + return _objectSpread2(_objectSpread2({}, response), {}, { + data: [] + }); + } + + const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); + if (!responseNeedsNormalization) return response; // keep the additional properties intact as there is currently no other way + // to retrieve the same information. + + const incompleteResults = response.data.incomplete_results; + const repositorySelection = response.data.repository_selection; + const totalCount = response.data.total_count; + delete response.data.incomplete_results; + delete response.data.repository_selection; + delete response.data.total_count; + const namespaceKey = Object.keys(response.data)[0]; + const data = response.data[namespaceKey]; + response.data = data; + + if (typeof incompleteResults !== "undefined") { + response.data.incomplete_results = incompleteResults; + } + + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; + } + + response.data.total_count = totalCount; + return response; +} + +function iterator(octokit, route, parameters) { + const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); + const requestMethod = typeof route === "function" ? route : octokit.request; + const method = options.method; + const headers = options.headers; + let url = options.url; + return { + [Symbol.asyncIterator]: () => ({ + async next() { + if (!url) return { + done: true + }; + + try { + const response = await requestMethod({ + method, + url, + headers + }); + const normalizedResponse = normalizePaginatedListResponse(response); // `response.headers.link` format: + // '; rel="next", ; rel="last"' + // sets `url` to undefined if "next" URL is not present or `link` header is not set + + url = ((normalizedResponse.headers.link || "").match(/<([^>]+)>;\s*rel="next"/) || [])[1]; + return { + value: normalizedResponse + }; + } catch (error) { + if (error.status !== 409) throw error; + url = ""; + return { + value: { + status: 200, + headers: {}, + data: [] + } + }; + } + } + + }) + }; +} + +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = undefined; + } + + return gather(octokit, [], iterator(octokit, route, parameters)[Symbol.asyncIterator](), mapFn); +} + +function gather(octokit, results, iterator, mapFn) { + return iterator.next().then(result => { + if (result.done) { + return results; + } + + let earlyExit = false; + + function done() { + earlyExit = true; + } + + results = results.concat(mapFn ? mapFn(result.value, done) : result.value.data); + + if (earlyExit) { + return results; + } + + return gather(octokit, results, iterator, mapFn); + }); +} + +const composePaginateRest = Object.assign(paginate, { + iterator +}); + +const paginatingEndpoints = ["GET /app/hook/deliveries", "GET /app/installations", "GET /applications/grants", "GET /authorizations", "GET /enterprises/{enterprise}/actions/permissions/organizations", "GET /enterprises/{enterprise}/actions/runner-groups", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/organizations", "GET /enterprises/{enterprise}/actions/runner-groups/{runner_group_id}/runners", "GET /enterprises/{enterprise}/actions/runners", "GET /enterprises/{enterprise}/actions/runners/downloads", "GET /events", "GET /gists", "GET /gists/public", "GET /gists/starred", "GET /gists/{gist_id}/comments", "GET /gists/{gist_id}/commits", "GET /gists/{gist_id}/forks", "GET /installation/repositories", "GET /issues", "GET /marketplace_listing/plans", "GET /marketplace_listing/plans/{plan_id}/accounts", "GET /marketplace_listing/stubbed/plans", "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", "GET /networks/{owner}/{repo}/events", "GET /notifications", "GET /organizations", "GET /orgs/{org}/actions/permissions/repositories", "GET /orgs/{org}/actions/runner-groups", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/repositories", "GET /orgs/{org}/actions/runner-groups/{runner_group_id}/runners", "GET /orgs/{org}/actions/runners", "GET /orgs/{org}/actions/runners/downloads", "GET /orgs/{org}/actions/secrets", "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", "GET /orgs/{org}/blocks", "GET /orgs/{org}/credential-authorizations", "GET /orgs/{org}/events", "GET /orgs/{org}/failed_invitations", "GET /orgs/{org}/hooks", "GET /orgs/{org}/hooks/{hook_id}/deliveries", "GET /orgs/{org}/installations", "GET /orgs/{org}/invitations", "GET /orgs/{org}/invitations/{invitation_id}/teams", "GET /orgs/{org}/issues", "GET /orgs/{org}/members", "GET /orgs/{org}/migrations", "GET /orgs/{org}/migrations/{migration_id}/repositories", "GET /orgs/{org}/outside_collaborators", "GET /orgs/{org}/projects", "GET /orgs/{org}/public_members", "GET /orgs/{org}/repos", "GET /orgs/{org}/team-sync/groups", "GET /orgs/{org}/teams", "GET /orgs/{org}/teams/{team_slug}/discussions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", "GET /orgs/{org}/teams/{team_slug}/invitations", "GET /orgs/{org}/teams/{team_slug}/members", "GET /orgs/{org}/teams/{team_slug}/projects", "GET /orgs/{org}/teams/{team_slug}/repos", "GET /orgs/{org}/teams/{team_slug}/team-sync/group-mappings", "GET /orgs/{org}/teams/{team_slug}/teams", "GET /projects/columns/{column_id}/cards", "GET /projects/{project_id}/collaborators", "GET /projects/{project_id}/columns", "GET /repos/{owner}/{repo}/actions/artifacts", "GET /repos/{owner}/{repo}/actions/runners", "GET /repos/{owner}/{repo}/actions/runners/downloads", "GET /repos/{owner}/{repo}/actions/runs", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", "GET /repos/{owner}/{repo}/actions/secrets", "GET /repos/{owner}/{repo}/actions/workflows", "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", "GET /repos/{owner}/{repo}/assignees", "GET /repos/{owner}/{repo}/autolinks", "GET /repos/{owner}/{repo}/branches", "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", "GET /repos/{owner}/{repo}/code-scanning/alerts", "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", "GET /repos/{owner}/{repo}/code-scanning/analyses", "GET /repos/{owner}/{repo}/collaborators", "GET /repos/{owner}/{repo}/comments", "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/commits", "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head", "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", "GET /repos/{owner}/{repo}/commits/{ref}/statuses", "GET /repos/{owner}/{repo}/contributors", "GET /repos/{owner}/{repo}/deployments", "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", "GET /repos/{owner}/{repo}/events", "GET /repos/{owner}/{repo}/forks", "GET /repos/{owner}/{repo}/git/matching-refs/{ref}", "GET /repos/{owner}/{repo}/hooks", "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", "GET /repos/{owner}/{repo}/invitations", "GET /repos/{owner}/{repo}/issues", "GET /repos/{owner}/{repo}/issues/comments", "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/issues/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", "GET /repos/{owner}/{repo}/issues/{issue_number}/events", "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", "GET /repos/{owner}/{repo}/keys", "GET /repos/{owner}/{repo}/labels", "GET /repos/{owner}/{repo}/milestones", "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", "GET /repos/{owner}/{repo}/notifications", "GET /repos/{owner}/{repo}/pages/builds", "GET /repos/{owner}/{repo}/projects", "GET /repos/{owner}/{repo}/pulls", "GET /repos/{owner}/{repo}/pulls/comments", "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", "GET /repos/{owner}/{repo}/releases", "GET /repos/{owner}/{repo}/releases/{release_id}/assets", "GET /repos/{owner}/{repo}/secret-scanning/alerts", "GET /repos/{owner}/{repo}/stargazers", "GET /repos/{owner}/{repo}/subscribers", "GET /repos/{owner}/{repo}/tags", "GET /repos/{owner}/{repo}/teams", "GET /repositories", "GET /repositories/{repository_id}/environments/{environment_name}/secrets", "GET /scim/v2/enterprises/{enterprise}/Groups", "GET /scim/v2/enterprises/{enterprise}/Users", "GET /scim/v2/organizations/{org}/Users", "GET /search/code", "GET /search/commits", "GET /search/issues", "GET /search/labels", "GET /search/repositories", "GET /search/topics", "GET /search/users", "GET /teams/{team_id}/discussions", "GET /teams/{team_id}/discussions/{discussion_number}/comments", "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", "GET /teams/{team_id}/discussions/{discussion_number}/reactions", "GET /teams/{team_id}/invitations", "GET /teams/{team_id}/members", "GET /teams/{team_id}/projects", "GET /teams/{team_id}/repos", "GET /teams/{team_id}/team-sync/group-mappings", "GET /teams/{team_id}/teams", "GET /user/blocks", "GET /user/emails", "GET /user/followers", "GET /user/following", "GET /user/gpg_keys", "GET /user/installations", "GET /user/installations/{installation_id}/repositories", "GET /user/issues", "GET /user/keys", "GET /user/marketplace_purchases", "GET /user/marketplace_purchases/stubbed", "GET /user/memberships/orgs", "GET /user/migrations", "GET /user/migrations/{migration_id}/repositories", "GET /user/orgs", "GET /user/public_emails", "GET /user/repos", "GET /user/repository_invitations", "GET /user/starred", "GET /user/subscriptions", "GET /user/teams", "GET /users", "GET /users/{username}/events", "GET /users/{username}/events/orgs/{org}", "GET /users/{username}/events/public", "GET /users/{username}/followers", "GET /users/{username}/following", "GET /users/{username}/gists", "GET /users/{username}/gpg_keys", "GET /users/{username}/keys", "GET /users/{username}/orgs", "GET /users/{username}/projects", "GET /users/{username}/received_events", "GET /users/{username}/received_events/public", "GET /users/{username}/repos", "GET /users/{username}/starred", "GET /users/{username}/subscriptions"]; + +function isPaginatingEndpoint(arg) { + if (typeof arg === "string") { + return paginatingEndpoints.includes(arg); + } else { + return false; + } +} + +/** + * @param octokit Octokit instance + * @param options Options passed to Octokit constructor + */ + +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; +} +paginateRest.VERSION = VERSION; + +exports.composePaginateRest = composePaginateRest; +exports.isPaginatingEndpoint = isPaginatingEndpoint; +exports.paginateRest = paginateRest; +exports.paginatingEndpoints = paginatingEndpoints; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 83044: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +function ownKeys(object, enumerableOnly) { + var keys = Object.keys(object); + + if (Object.getOwnPropertySymbols) { + var symbols = Object.getOwnPropertySymbols(object); + if (enumerableOnly) symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + keys.push.apply(keys, symbols); + } + + return keys; +} + +function _objectSpread2(target) { + for (var i = 1; i < arguments.length; i++) { + var source = arguments[i] != null ? arguments[i] : {}; + + if (i % 2) { + ownKeys(Object(source), true).forEach(function (key) { + _defineProperty(target, key, source[key]); + }); + } else if (Object.getOwnPropertyDescriptors) { + Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); + } else { + ownKeys(Object(source)).forEach(function (key) { + Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); + }); + } + } + + return target; +} + +const Endpoints = { + actions: { + addSelectedRepoToOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], + cancelWorkflowRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel"], + createOrUpdateEnvironmentSecret: ["PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: ["PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + createRegistrationTokenForOrg: ["POST /orgs/{org}/actions/runners/registration-token"], + createRegistrationTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/registration-token"], + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: ["POST /repos/{owner}/{repo}/actions/runners/remove-token"], + createWorkflowDispatch: ["POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches"], + deleteArtifact: ["DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + deleteEnvironmentSecret: ["DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], + deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], + deleteRepoSecret: ["DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + deleteSelfHostedRunnerFromOrg: ["DELETE /orgs/{org}/actions/runners/{runner_id}"], + deleteSelfHostedRunnerFromRepo: ["DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}"], + deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], + deleteWorkflowRunLogs: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], + disableSelectedRepositoryGithubActionsOrganization: ["DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}"], + disableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable"], + downloadArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}"], + downloadJobLogsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs"], + downloadWorkflowRunLogs: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs"], + enableSelectedRepositoryGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories/{repository_id}"], + enableWorkflow: ["PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable"], + getAllowedActionsOrganization: ["GET /orgs/{org}/actions/permissions/selected-actions"], + getAllowedActionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions/selected-actions"], + getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + getEnvironmentPublicKey: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key"], + getEnvironmentSecret: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}"], + getGithubActionsPermissionsOrganization: ["GET /orgs/{org}/actions/permissions"], + getGithubActionsPermissionsRepository: ["GET /repos/{owner}/{repo}/actions/permissions"], + getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], + getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], + getPendingDeploymentsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"], + getRepoPermissions: ["GET /repos/{owner}/{repo}/actions/permissions", {}, { + renamed: ["actions", "getGithubActionsPermissionsRepository"] + }], + getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], + getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + getReviewsForRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals"], + getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], + getSelfHostedRunnerForRepo: ["GET /repos/{owner}/{repo}/actions/runners/{runner_id}"], + getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], + getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], + getWorkflowRunUsage: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing"], + getWorkflowUsage: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing"], + listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], + listEnvironmentSecrets: ["GET /repositories/{repository_id}/environments/{environment_name}/secrets"], + listJobsForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs"], + listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], + listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], + listRunnerApplicationsForRepo: ["GET /repos/{owner}/{repo}/actions/runners/downloads"], + listSelectedReposForOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}/repositories"], + listSelectedRepositoriesEnabledGithubActionsOrganization: ["GET /orgs/{org}/actions/permissions/repositories"], + listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], + listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], + listWorkflowRunArtifacts: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts"], + listWorkflowRuns: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs"], + listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], + reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], + removeSelectedRepoFromOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}"], + reviewPendingDeploymentsForRun: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments"], + setAllowedActionsOrganization: ["PUT /orgs/{org}/actions/permissions/selected-actions"], + setAllowedActionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions/selected-actions"], + setGithubActionsPermissionsOrganization: ["PUT /orgs/{org}/actions/permissions"], + setGithubActionsPermissionsRepository: ["PUT /repos/{owner}/{repo}/actions/permissions"], + setSelectedReposForOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}/repositories"], + setSelectedRepositoriesEnabledGithubActionsOrganization: ["PUT /orgs/{org}/actions/permissions/repositories"] + }, + activity: { + checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], + deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], + deleteThreadSubscription: ["DELETE /notifications/threads/{thread_id}/subscription"], + getFeeds: ["GET /feeds"], + getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], + getThread: ["GET /notifications/threads/{thread_id}"], + getThreadSubscriptionForAuthenticatedUser: ["GET /notifications/threads/{thread_id}/subscription"], + listEventsForAuthenticatedUser: ["GET /users/{username}/events"], + listNotificationsForAuthenticatedUser: ["GET /notifications"], + listOrgEventsForAuthenticatedUser: ["GET /users/{username}/events/orgs/{org}"], + listPublicEvents: ["GET /events"], + listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], + listPublicEventsForUser: ["GET /users/{username}/events/public"], + listPublicOrgEvents: ["GET /orgs/{org}/events"], + listReceivedEventsForUser: ["GET /users/{username}/received_events"], + listReceivedPublicEventsForUser: ["GET /users/{username}/received_events/public"], + listRepoEvents: ["GET /repos/{owner}/{repo}/events"], + listRepoNotificationsForAuthenticatedUser: ["GET /repos/{owner}/{repo}/notifications"], + listReposStarredByAuthenticatedUser: ["GET /user/starred"], + listReposStarredByUser: ["GET /users/{username}/starred"], + listReposWatchedByUser: ["GET /users/{username}/subscriptions"], + listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], + listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], + listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], + markNotificationsAsRead: ["PUT /notifications"], + markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], + setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], + setThreadSubscription: ["PUT /notifications/threads/{thread_id}/subscription"], + starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], + unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] + }, + apps: { + addRepoToInstallation: ["PUT /user/installations/{installation_id}/repositories/{repository_id}"], + checkToken: ["POST /applications/{client_id}/token"], + createContentAttachment: ["POST /content_references/{content_reference_id}/attachments", { + mediaType: { + previews: ["corsair"] + } + }], + createFromManifest: ["POST /app-manifests/{code}/conversions"], + createInstallationAccessToken: ["POST /app/installations/{installation_id}/access_tokens"], + deleteAuthorization: ["DELETE /applications/{client_id}/grant"], + deleteInstallation: ["DELETE /app/installations/{installation_id}"], + deleteToken: ["DELETE /applications/{client_id}/token"], + getAuthenticated: ["GET /app"], + getBySlug: ["GET /apps/{app_slug}"], + getInstallation: ["GET /app/installations/{installation_id}"], + getOrgInstallation: ["GET /orgs/{org}/installation"], + getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], + getSubscriptionPlanForAccount: ["GET /marketplace_listing/accounts/{account_id}"], + getSubscriptionPlanForAccountStubbed: ["GET /marketplace_listing/stubbed/accounts/{account_id}"], + getUserInstallation: ["GET /users/{username}/installation"], + getWebhookConfigForApp: ["GET /app/hook/config"], + listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], + listAccountsForPlanStubbed: ["GET /marketplace_listing/stubbed/plans/{plan_id}/accounts"], + listInstallationReposForAuthenticatedUser: ["GET /user/installations/{installation_id}/repositories"], + listInstallations: ["GET /app/installations"], + listInstallationsForAuthenticatedUser: ["GET /user/installations"], + listPlans: ["GET /marketplace_listing/plans"], + listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], + listReposAccessibleToInstallation: ["GET /installation/repositories"], + listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], + listSubscriptionsForAuthenticatedUserStubbed: ["GET /user/marketplace_purchases/stubbed"], + removeRepoFromInstallation: ["DELETE /user/installations/{installation_id}/repositories/{repository_id}"], + resetToken: ["PATCH /applications/{client_id}/token"], + revokeInstallationAccessToken: ["DELETE /installation/token"], + scopeToken: ["POST /applications/{client_id}/token/scoped"], + suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], + unsuspendInstallation: ["DELETE /app/installations/{installation_id}/suspended"], + updateWebhookConfigForApp: ["PATCH /app/hook/config"] + }, + billing: { + getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], + getGithubActionsBillingUser: ["GET /users/{username}/settings/billing/actions"], + getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], + getGithubPackagesBillingUser: ["GET /users/{username}/settings/billing/packages"], + getSharedStorageBillingOrg: ["GET /orgs/{org}/settings/billing/shared-storage"], + getSharedStorageBillingUser: ["GET /users/{username}/settings/billing/shared-storage"] + }, + checks: { + create: ["POST /repos/{owner}/{repo}/check-runs"], + createSuite: ["POST /repos/{owner}/{repo}/check-suites"], + get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], + getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], + listAnnotations: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations"], + listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], + listForSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs"], + listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], + rerequestSuite: ["POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest"], + setSuitesPreferences: ["PATCH /repos/{owner}/{repo}/check-suites/preferences"], + update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] + }, + codeScanning: { + deleteAnalysis: ["DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}"], + getAlert: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", {}, { + renamedParameters: { + alert_id: "alert_number" + } + }], + getAnalysis: ["GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}"], + getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], + listAlertsInstances: ["GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances"], + listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], + updateAlert: ["PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}"], + uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] + }, + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct", { + mediaType: { + previews: ["scarlet-witch"] + } + }], + getConductCode: ["GET /codes_of_conduct/{key}", { + mediaType: { + previews: ["scarlet-witch"] + } + }], + getForRepo: ["GET /repos/{owner}/{repo}/community/code_of_conduct", { + mediaType: { + previews: ["scarlet-witch"] + } + }] + }, + emojis: { + get: ["GET /emojis"] + }, + enterpriseAdmin: { + disableSelectedOrganizationGithubActionsEnterprise: ["DELETE /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"], + enableSelectedOrganizationGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations/{org_id}"], + getAllowedActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/selected-actions"], + getGithubActionsPermissionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions"], + listSelectedOrganizationsEnabledGithubActionsEnterprise: ["GET /enterprises/{enterprise}/actions/permissions/organizations"], + setAllowedActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/selected-actions"], + setGithubActionsPermissionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions"], + setSelectedOrganizationsEnabledGithubActionsEnterprise: ["PUT /enterprises/{enterprise}/actions/permissions/organizations"] + }, gists: { checkIsStarred: ["GET /gists/{gist_id}/star"], create: ["POST /gists"], @@ -13890,15 +15260,24 @@ const Endpoints = { getTemplate: ["GET /gitignore/templates/{name}"] }, interactions: { + getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], - getRestrictionsForYourPublicRepos: ["GET /user/interaction-limits"], + getRestrictionsForYourPublicRepos: ["GET /user/interaction-limits", {}, { + renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] + }], + removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], removeRestrictionsForRepo: ["DELETE /repos/{owner}/{repo}/interaction-limits"], - removeRestrictionsForYourPublicRepos: ["DELETE /user/interaction-limits"], + removeRestrictionsForYourPublicRepos: ["DELETE /user/interaction-limits", {}, { + renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] + }], + setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], - setRestrictionsForYourPublicRepos: ["PUT /user/interaction-limits"] + setRestrictionsForYourPublicRepos: ["PUT /user/interaction-limits", {}, { + renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] + }] }, issues: { addAssignees: ["POST /repos/{owner}/{repo}/issues/{issue_number}/assignees"], @@ -14038,6 +15417,7 @@ const Endpoints = { }, orgs: { blockUser: ["PUT /orgs/{org}/blocks/{username}"], + cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], @@ -14053,6 +15433,7 @@ const Endpoints = { list: ["GET /organizations"], listAppInstallations: ["GET /orgs/{org}/installations"], listBlockedUsers: ["GET /orgs/{org}/blocks"], + listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], listForAuthenticatedUser: ["GET /user/orgs"], listForUser: ["GET /users/{username}/orgs"], listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], @@ -14075,6 +15456,31 @@ const Endpoints = { updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] }, + packages: { + deletePackageForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}"], + deletePackageForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}"], + deletePackageVersionForAuthenticatedUser: ["DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}"], + deletePackageVersionForOrg: ["DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"], + getAllPackageVersionsForAPackageOwnedByAnOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions", {}, { + renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] + }], + getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions", {}, { + renamed: ["packages", "getAllPackageVersionsForPackageOwnedByAuthenticatedUser"] + }], + getAllPackageVersionsForPackageOwnedByAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions"], + getAllPackageVersionsForPackageOwnedByOrg: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions"], + getAllPackageVersionsForPackageOwnedByUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions"], + getPackageForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}"], + getPackageForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}"], + getPackageForUser: ["GET /users/{username}/packages/{package_type}/{package_name}"], + getPackageVersionForAuthenticatedUser: ["GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}"], + getPackageVersionForOrganization: ["GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}"], + getPackageVersionForUser: ["GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}"], + restorePackageForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/restore{?token}"], + restorePackageForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}"], + restorePackageVersionForAuthenticatedUser: ["POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"], + restorePackageVersionForOrg: ["POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore"] + }, projects: { addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}", { mediaType: { @@ -14304,7 +15710,7 @@ const Endpoints = { previews: ["squirrel-girl"] } }, { - deprecated: "octokit.reactions.deleteLegacy() is deprecated, see https://docs.github.com/v3/reactions/#delete-a-reaction-legacy" + deprecated: "octokit.rest.reactions.deleteLegacy() is deprecated, see https://docs.github.com/rest/reference/reactions/#delete-a-reaction-legacy" }], listForCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", { mediaType: { @@ -14373,6 +15779,7 @@ const Endpoints = { createForAuthenticatedUser: ["POST /user/repos"], createFork: ["POST /repos/{owner}/{repo}/forks"], createInOrg: ["POST /orgs/{org}/repos"], + createOrUpdateEnvironment: ["PUT /repos/{owner}/{repo}/environments/{environment_name}"], createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], createPagesSite: ["POST /repos/{owner}/{repo}/pages", { mediaType: { @@ -14390,6 +15797,7 @@ const Endpoints = { delete: ["DELETE /repos/{owner}/{repo}"], deleteAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], deleteAdminBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], + deleteAnEnvironment: ["DELETE /repos/{owner}/{repo}/environments/{environment_name}"], deleteBranchProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection"], deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], deleteCommitSignatureProtection: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures", { @@ -14438,6 +15846,7 @@ const Endpoints = { get: ["GET /repos/{owner}/{repo}"], getAccessRestrictions: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions"], getAdminBranchProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins"], + getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], getAllStatusCheckContexts: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts"], getAllTopics: ["GET /repos/{owner}/{repo}/topics", { mediaType: { @@ -14465,6 +15874,7 @@ const Endpoints = { getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], getDeploymentStatus: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}"], + getEnvironment: ["GET /repos/{owner}/{repo}/environments/{environment_name}"], getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], getPages: ["GET /repos/{owner}/{repo}/pages"], @@ -14473,6 +15883,7 @@ const Endpoints = { getPullRequestReviewProtection: ["GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews"], getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], getReadme: ["GET /repos/{owner}/{repo}/readme"], + getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], @@ -14534,6 +15945,7 @@ const Endpoints = { removeUserAccessRestrictions: ["DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", {}, { mapToData: "users" }], + renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics", { mediaType: { previews: ["mercy"] @@ -14675,7 +16087,7 @@ const Endpoints = { } }; -const VERSION = "4.4.1"; +const VERSION = "4.15.1"; function endpointsToMethods(octokit, endpointsMap) { const newMethods = {}; @@ -14758,19 +16170,11 @@ function decorate(octokit, scope, methodName, defaults, decorations) { return Object.assign(withDecorations, requestWithDefaults); } -/** - * This plugin is a 1:1 copy of internal @octokit/rest plugins. The primary - * goal is to rebuild @octokit/rest on top of @octokit/core. Once that is - * done, we will remove the registerEndpoints methods and return the methods - * directly as with the other plugins. At that point we will also remove the - * legacy workarounds and deprecations. - * - * See the plan at - * https://github.com/octokit/plugin-rest-endpoint-methods.js/pull/1 - */ - function restEndpointMethods(octokit) { - return endpointsToMethods(octokit, Endpoints); + const api = endpointsToMethods(octokit, Endpoints); + return _objectSpread2(_objectSpread2({}, api), {}, { + rest: api + }); } restEndpointMethods.VERSION = VERSION; @@ -14829,30 +16233,31 @@ async function wrapRequest(state, request, options) { return limiter.schedule(request, options); } -const VERSION = "3.0.6"; -function retry(octokit, octokitOptions = {}) { +const VERSION = "3.0.9"; +function retry(octokit, octokitOptions) { const state = Object.assign({ enabled: true, retryAfterBaseValue: 1000, doNotRetry: [400, 401, 403, 404, 422], retries: 3 }, octokitOptions.retry); - octokit.retry = { - retryRequest: (error, retries, retryAfter) => { - error.request.request = Object.assign({}, error.request.request, { - retries: retries, - retryAfter: retryAfter - }); - return error; - } - }; - if (!state.enabled) { - return; + if (state.enabled) { + octokit.hook.error("request", errorRequest.bind(null, octokit, state)); + octokit.hook.wrap("request", wrapRequest.bind(null, state)); } - octokit.hook.error("request", errorRequest.bind(null, octokit, state)); - octokit.hook.wrap("request", wrapRequest.bind(null, state)); + return { + retry: { + retryRequest: (error, retries, retryAfter) => { + error.request.request = Object.assign({}, error.request.request, { + retries: retries, + retryAfter: retryAfter + }); + return error; + } + } + }; } retry.VERSION = VERSION; @@ -14875,29 +16280,18 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau var BottleneckLight = _interopDefault(__nccwpck_require__(11174)); -function _defineProperty(obj, key, value) { - if (key in obj) { - Object.defineProperty(obj, key, { - value: value, - enumerable: true, - configurable: true, - writable: true - }); - } else { - obj[key] = value; - } - - return obj; -} - function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); - if (enumerableOnly) symbols = symbols.filter(function (sym) { - return Object.getOwnPropertyDescriptor(object, sym).enumerable; - }); + + if (enumerableOnly) { + symbols = symbols.filter(function (sym) { + return Object.getOwnPropertyDescriptor(object, sym).enumerable; + }); + } + keys.push.apply(keys, symbols); } @@ -14924,7 +16318,22 @@ function _objectSpread2(target) { return target; } -const VERSION = "3.3.4"; +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +const VERSION = "3.5.1"; const noop = () => Promise.resolve(); // @ts-ignore @@ -14935,8 +16344,11 @@ function wrapRequest(state, request, options) { async function doRequest(state, request, options) { const isWrite = options.method !== "GET" && options.method !== "HEAD"; - const isSearch = options.method === "GET" && options.url.startsWith("/search/"); - const isGraphQL = options.url.startsWith("/graphql"); + const { + pathname + } = new URL(options.url, "http://github.test"); + const isSearch = options.method === "GET" && pathname.startsWith("/search/"); + const isGraphQL = pathname.startsWith("/graphql"); const retryCount = ~~options.request.retryCount; const jobOptions = retryCount > 0 ? { priority: 0, @@ -14957,7 +16369,7 @@ async function doRequest(state, request, options) { } // Guarantee at least 3000ms between requests that trigger notifications - if (isWrite && state.triggersNotification(options.url)) { + if (isWrite && state.triggersNotification(pathname)) { await state.notifications.key(state.id).schedule(jobOptions, noop); } // Guarantee at least 2000ms between search requests @@ -14974,7 +16386,7 @@ async function doRequest(state, request, options) { if (res.data.errors != null && // @ts-ignore res.data.errors.some(error => error.type === "RATE_LIMITED")) { const error = Object.assign(new Error("GraphQL Rate Limit Exceeded"), { - headers: res.headers, + response: res, data: res.data }); throw error; @@ -14984,15 +16396,15 @@ async function doRequest(state, request, options) { return req; } -var triggersNotificationPaths = ["/orgs/{org}/invitations", "/orgs/{org}/teams/{team_slug}/discussions", "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "/repos/{owner}/{repo}/collaborators/{username}", "/repos/{owner}/{repo}/commits/{commit_sha}/comments", "/repos/{owner}/{repo}/issues", "/repos/{owner}/{repo}/issues/{issue_number}/comments", "/repos/{owner}/{repo}/pulls", "/repos/{owner}/{repo}/pulls/{pull_number}/comments", "/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies", "/repos/{owner}/{repo}/pulls/{pull_number}/merge", "/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", "/repos/{owner}/{repo}/pulls/{pull_number}/reviews", "/repos/{owner}/{repo}/releases", "/teams/{team_id}/discussions", "/teams/{team_id}/discussions/{discussion_number}/comments"]; +var triggersNotificationPaths = ["/orgs/{org}/invitations", "/orgs/{org}/invitations/{invitation_id}", "/orgs/{org}/teams/{team_slug}/discussions", "/orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", "/repos/{owner}/{repo}/collaborators/{username}", "/repos/{owner}/{repo}/commits/{commit_sha}/comments", "/repos/{owner}/{repo}/issues", "/repos/{owner}/{repo}/issues/{issue_number}/comments", "/repos/{owner}/{repo}/pulls", "/repos/{owner}/{repo}/pulls/{pull_number}/comments", "/repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies", "/repos/{owner}/{repo}/pulls/{pull_number}/merge", "/repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers", "/repos/{owner}/{repo}/pulls/{pull_number}/reviews", "/repos/{owner}/{repo}/releases", "/teams/{team_id}/discussions", "/teams/{team_id}/discussions/{discussion_number}/comments"]; // @ts-ignore function routeMatcher(paths) { // EXAMPLE. For the following paths: /* [ - "/orgs/:org/invitations", - "/repos/:owner/:repo/collaborators/:username" + "/orgs/{org}/invitations", + "/repos/{owner}/{repo}/collaborators/{username}" ] */ // @ts-ignore const regexes = paths.map(path => path.split("/") // @ts-ignore @@ -15052,11 +16464,12 @@ function throttling(octokit, octokitOptions = {}) { id = "no-id", timeout = 1000 * 60 * 2, // Redis TTL: 2 minutes - connection + connection // @ts-ignore + } = octokitOptions.throttle || {}; if (!enabled) { - return; + return {}; } const common = { @@ -15103,7 +16516,10 @@ function throttling(octokit, octokitOptions = {}) { state.retryLimiter.on("failed", async function (error, info) { const options = info.args[info.args.length - 1]; - const shouldRetryGraphQL = options.url.startsWith("/graphql") && error.status !== 401; + const { + pathname + } = new URL(options.url, "http://github.test"); + const shouldRetryGraphQL = pathname.startsWith("/graphql") && error.status !== 401; if (!(shouldRetryGraphQL || error.status === 403)) { return; @@ -15120,7 +16536,7 @@ function throttling(octokit, octokitOptions = {}) { // https://docs.github.com/en/rest/overview/resources-in-the-rest-api#abuse-rate-limits // The Retry-After header can sometimes be blank when hitting an abuse limit, // but is always present after 2-3s, so make sure to set `retryAfter` to at least 5s by default. - const retryAfter = Math.max(~~error.headers["retry-after"], state.minimumAbuseRetryAfter); + const retryAfter = Math.max(~~error.response.headers["retry-after"], state.minimumAbuseRetryAfter); const wantRetry = await emitter.trigger("abuse-limit", retryAfter, options, octokit); return { wantRetry, @@ -15128,11 +16544,11 @@ function throttling(octokit, octokitOptions = {}) { }; } - if (error.headers != null && error.headers["x-ratelimit-remaining"] === "0") { + if (error.response.headers != null && error.response.headers["x-ratelimit-remaining"] === "0") { // The user has used all their allowed calls for the current time period (REST and GraphQL) // https://docs.github.com/en/rest/reference/rate-limit (REST) // https://docs.github.com/en/graphql/overview/resource-limitations#rate-limit (GraphQL) - const rateLimitReset = new Date(~~error.headers["x-ratelimit-reset"] * 1000).getTime(); + const rateLimitReset = new Date(~~error.response.headers["x-ratelimit-reset"] * 1000).getTime(); const retryAfter = Math.max(Math.ceil((rateLimitReset - Date.now()) / 1000), 0); const wantRetry = await emitter.trigger("rate-limit", retryAfter, options, octokit); return { @@ -15151,6 +16567,7 @@ function throttling(octokit, octokitOptions = {}) { } }); octokit.hook.wrap("request", wrapRequest.bind(null, state)); + return {}; } throttling.VERSION = VERSION; throttling.triggersNotification = triggersNotification; @@ -15174,7 +16591,8 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau var deprecation = __nccwpck_require__(58932); var once = _interopDefault(__nccwpck_require__(1223)); -const logOnce = once(deprecation => console.warn(deprecation)); +const logOnceCode = once(deprecation => console.warn(deprecation)); +const logOnceHeaders = once(deprecation => console.warn(deprecation)); /** * Error with extra properties to help with debugging */ @@ -15191,14 +16609,17 @@ class RequestError extends Error { this.name = "HttpError"; this.status = statusCode; - Object.defineProperty(this, "code", { - get() { - logOnce(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); - return 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 - }); - this.headers = options.headers || {}; // redact request credentials without mutating original request options const requestCopy = Object.assign({}, options.request); @@ -15213,7 +16634,22 @@ class RequestError extends Error { .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; + this.request = requestCopy; // deprecations + + Object.defineProperty(this, "code", { + get() { + logOnceCode(new deprecation.Deprecation("[@octokit/request-error] `error.code` is deprecated, use `error.status`.")); + return statusCode; + } + + }); + Object.defineProperty(this, "headers", { + get() { + logOnceHeaders(new deprecation.Deprecation("[@octokit/request-error] `error.headers` is deprecated, use `error.response.headers`.")); + return headers || {}; + } + + }); } } @@ -15236,17 +16672,19 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau var endpoint = __nccwpck_require__(59440); var universalUserAgent = __nccwpck_require__(45030); -var isPlainObject = __nccwpck_require__(49062); +var isPlainObject = __nccwpck_require__(63287); var nodeFetch = _interopDefault(__nccwpck_require__(80467)); var requestError = __nccwpck_require__(10537); -const VERSION = "5.4.12"; +const VERSION = "5.6.1"; function getBufferResponse(response) { return response.arrayBuffer(); } function fetchWrapper(requestOptions) { + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + if (isPlainObject.isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { requestOptions.body = JSON.stringify(requestOptions.body); } @@ -15260,7 +16698,9 @@ function fetchWrapper(requestOptions) { body: requestOptions.body, headers: requestOptions.headers, redirect: requestOptions.redirect - }, requestOptions.request)).then(response => { + }, // `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; @@ -15268,6 +16708,12 @@ function fetchWrapper(requestOptions) { 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) { return; } // GitHub API returns 200 for HEAD requests @@ -15279,49 +16725,43 @@ function fetchWrapper(requestOptions) { } throw new requestError.RequestError(response.statusText, status, { - headers, + response: { + url, + status, + headers, + data: undefined + }, request: requestOptions }); } if (status === 304) { throw new requestError.RequestError("Not modified", status, { - headers, + response: { + url, + status, + headers, + data: await getResponseData(response) + }, request: requestOptions }); } if (status >= 400) { - return response.text().then(message => { - const error = new requestError.RequestError(message, status, { + const data = await getResponseData(response); + const error = new requestError.RequestError(toErrorMessage(data), status, { + response: { + url, + status, headers, - request: requestOptions - }); - - try { - let responseBody = JSON.parse(error.message); - Object.assign(error, responseBody); - let errors = responseBody.errors; // Assumption `errors` would always be in Array format - - error.message = error.message + ": " + errors.map(JSON.stringify).join(", "); - } catch (e) {// ignore, see octokit/rest.js#684 - } - - throw error; + data + }, + request: requestOptions }); + throw error; } - 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(); - } - - return getBufferResponse(response); + return getResponseData(response); }).then(data => { return { status, @@ -15330,17 +16770,42 @@ function fetchWrapper(requestOptions) { data }; }).catch(error => { - if (error instanceof requestError.RequestError) { - throw error; - } - + if (error instanceof requestError.RequestError) throw error; throw new requestError.RequestError(error.message, 500, { - headers, 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(); + } + + return getBufferResponse(response); +} + +function toErrorMessage(data) { + if (typeof data === "string") return data; // istanbul ignore else - just in case + + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}`; + } + + return data.message; + } // istanbul ignore next - just in case + + + return `Unknown error: ${JSON.stringify(data)}`; +} + function withDefaults(oldEndpoint, newDefaults) { const endpoint = oldEndpoint.defaults(newDefaults); @@ -15378,52 +16843,6 @@ exports.request = request; //# sourceMappingURL=index.js.map -/***/ }), - -/***/ 49062: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -/*! - * is-plain-object - * - * Copyright (c) 2014-2017, Jon Schlinkert. - * Released under the MIT License. - */ - -function isObject(o) { - return Object.prototype.toString.call(o) === '[object Object]'; -} - -function isPlainObject(o) { - var ctor,prot; - - 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; - } - - // Most likely a plain Object - return true; -} - -exports.isPlainObject = isPlainObject; - - /***/ }), /***/ 18513: @@ -15967,6 +17386,8 @@ var isBase64 = _interopDefault(__nccwpck_require__(31310)); const VERSION = "0.0.0-development"; +const begin = "-----BEGIN RSA PRIVATE KEY-----"; +const end = "-----END RSA PRIVATE KEY-----"; function getPrivateKey(options = {}) { const env = options.env || process.env; const cwd = options.cwd || process.cwd(); @@ -15983,12 +17404,18 @@ function getPrivateKey(options = {}) { privateKey = Buffer.from(privateKey, "base64").toString(); } - const begin = "-----BEGIN RSA PRIVATE KEY-----"; - const end = "-----END RSA PRIVATE KEY-----"; - if (privateKey.includes(begin) && privateKey.includes(end)) { - // Full key with new lines - return privateKey.replace(/\\n/g, "\n"); + // newlines are escaped + if (privateKey.indexOf("\\n") !== -1) { + privateKey = privateKey.replace(/\\n/g, "\n"); + } // newlines are missing + + + if (privateKey.indexOf("\n") === -1) { + privateKey = addNewlines(privateKey); + } + + return privateKey; } throw new Error(`[@probot/get-private-key] The contents of "env.PRIVATE_KEY" could not be validated. Please check to ensure you have copied the contents of the .pem file correctly.`); @@ -16018,6 +17445,13 @@ function getPrivateKey(options = {}) { return null; } + +function addNewlines(privateKey) { + const middleLength = privateKey.length - begin.length - end.length - 2; + const middle = privateKey.substr(begin.length + 1, middleLength); + return `${begin}\n${middle.trim().replace(/\s+/g, "\n")}\n${end}`; +} + getPrivateKey.VERSION = VERSION; exports.getPrivateKey = getPrivateKey; @@ -16036,9 +17470,9 @@ Object.defineProperty(exports, "__esModule", ({ value: true })); function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; } -var yaml = _interopDefault(__nccwpck_require__(21917)); +var yaml = _interopDefault(__nccwpck_require__(80557)); -const VERSION = "1.0.1"; +const VERSION = "1.1.2"; function _defineProperty(obj, key, value) { if (key in obj) { @@ -16110,7 +17544,9 @@ async function getConfigFile(octokit, { } // https://docs.github.com/en/rest/reference/repos#get-repository-content - const requestOptions = await octokit.request.endpoint("GET /repos/{owner}/{repo}/contents/{path}", _objectSpread2({ + const endpoint = _objectSpread2({ + method: "GET", + url: "/repos/{owner}/{repo}/contents/{path}", owner, repo, path, @@ -16119,12 +17555,16 @@ async function getConfigFile(octokit, { } }, ref ? { ref - } : {})); + } : {}); + + const { + url + } = await octokit.request.endpoint(endpoint); const emptyConfigResult = { owner, repo, path, - url: requestOptions.url, + url, config: null }; @@ -16132,7 +17572,7 @@ async function getConfigFile(octokit, { const { data, headers - } = await octokit.request(requestOptions); // If path is a submodule, or a folder, then a JSON string is returned with + } = await octokit.request(endpoint); // If path is a submodule, or a folder, then a JSON string is returned with // the "Content-Type" header set to "application/json; charset=utf-8". // // - https://docs.github.com/en/rest/reference/repos#if-the-content-is-a-submodule @@ -16142,12 +17582,12 @@ async function getConfigFile(octokit, { // so we are fine if (headers["content-type"] === "application/json; charset=utf-8") { - throw new Error(`[@probot/octokit-plugin-config] ${requestOptions.url} exists, but is either a directory or a submodule. Ignoring.`); + throw new Error(`[@probot/octokit-plugin-config] ${url} exists, but is either a directory or a submodule. Ignoring.`); } if (fileExtension === "json") { if (typeof data === "string") { - throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${requestOptions.url} (invalid JSON)`); + throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${url} (invalid JSON)`); } return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { @@ -16155,10 +17595,10 @@ async function getConfigFile(octokit, { }); } - const config = yaml.safeLoad(data) || {}; + const config = yaml.load(data) || {}; if (typeof config === "string") { - throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${requestOptions.url} (YAML is not an object)`); + throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${url} (YAML is not an object)`); } return _objectSpread2(_objectSpread2({}, emptyConfigResult), {}, { @@ -16171,7 +17611,7 @@ async function getConfigFile(octokit, { if (error.name === "YAMLException") { const reason = /unknown tag/.test(error.message) ? "unsafe YAML" : "invalid YAML"; - throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${requestOptions.url} (${reason})`); + throw new Error(`[@probot/octokit-plugin-config] Configuration could not be parsed from ${url} (${reason})`); } throw error; @@ -16243,8958 +17683,7417 @@ async function getConfigFiles(octokit, { if (!requestedRepoFile.config) { if (repo === ".github") { return [requestedRepoFile]; - } - - const defaultRepoConfig = await getConfigFile(octokit, { - owner, - repo: ".github", - path - }); - return [requestedRepoFile, defaultRepoConfig]; - } // if the configuration has no `_extends` key, we are done here. - - - if (!requestedRepoFile.config._extends) { - return [requestedRepoFile]; - } // parse the value of `_extends` into request parameters to - // retrieve the new configuration file - - - let extendConfigOptions = extendsToGetContentParams({ - owner, - path, - url: requestedRepoFile.url, - extendsValue: requestedRepoFile.config._extends - }); // remove the `_extends` key from the configuration that is returned - - delete requestedRepoFile.config._extends; - const files = [requestedRepoFile]; // now load the configuration linked from the `_extends` key. If that - // configuration also includes an `_extends` key, then load that configuration - // as well, until the target configuration has no `_extends` key - - do { - const extendRepoConfig = await getConfigFile(octokit, extendConfigOptions); - files.push(extendRepoConfig); - - if (!extendRepoConfig.config || !extendRepoConfig.config._extends) { - return files; - } - - extendConfigOptions = extendsToGetContentParams({ - owner, - path, - url: extendRepoConfig.url, - extendsValue: extendRepoConfig.config._extends - }); - delete extendRepoConfig.config._extends; // Avoid loops - - const alreadyLoaded = files.find(file => file.owner === extendConfigOptions.owner && file.repo === extendConfigOptions.repo && file.path === extendConfigOptions.path); - - if (alreadyLoaded) { - throw new Error(`[@probot/octokit-plugin-config] Recursion detected. Ignoring "_extends: ${extendRepoConfig.config._extends}" from ${extendRepoConfig.url} because ${alreadyLoaded.url} was already loaded.`); - } - } while (true); -} - -/** - * Loads configuration from one or multiple files and resolves with - * the combined configuration as well as the list of files the configuration - * was loaded from - * - * @param octokit Octokit instance - * @param options - */ - -async function composeConfigGet(octokit, { - owner, - repo, - defaults, - path, - branch -}) { - const files = await getConfigFiles(octokit, { - owner, - repo, - path, - branch - }); - const configs = files.map(file => file.config).reverse().filter(Boolean); - return { - files, - config: typeof defaults === "function" ? defaults(configs) : Object.assign({}, defaults, ...configs) - }; -} - -/** - * @param octokit Octokit instance - */ - -function config(octokit) { - return { - config: { - async get(options) { - return composeConfigGet(octokit, options); - } - - } - }; -} -config.VERSION = VERSION; - -exports.composeConfigGet = composeConfigGet; -exports.config = config; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 39662: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = { getTransformStream }; - -const { Transform } = __nccwpck_require__(51642); - -const prettyFactory = __nccwpck_require__(31691); -const Sentry = __nccwpck_require__(22783); - -const LEVEL_MAP = { - 10: "trace", - 20: "debug", - 30: "info", - 40: "warn", - 50: "error", - 60: "fatal", -}; - -/** - * Implements Probot's default logging formatting and error captionaing using Sentry. - * - * @param {import("./").Options} options - * @returns Transform - * @see https://getpino.io/#/docs/transports - */ -function getTransformStream(options = {}) { - const formattingEnabled = options.logFormat !== "json"; - const levelAsString = options.logLevelInString === "true"; - const sentryEnabled = !!options.sentryDsn; - - if (sentryEnabled) { - Sentry.init({ - dsn: options.sentryDsn, - // See https://github.com/getsentry/sentry-javascript/issues/1964#issuecomment-688482615 - // 6 is enough to serialize the deepest property across all GitHub Event payloads - normalizeDepth: 6, - }); - } - - const pretty = prettyFactory({ - ignore: [ - // default pino keys - "time", - "pid", - "hostname", - // remove keys from pino-http - "req", - "res", - "responseTime", - ].join(","), - errorProps: ["event", "status", "headers", "request"].join(","), - }); - - return new Transform({ - objectMode: true, - transform(chunk, enc, cb) { - const line = chunk.toString().trim(); - - /* istanbul ignore if */ - if (line === undefined) return cb(); - - const data = sentryEnabled ? JSON.parse(line) : null; - - if (sentryEnabled && data.level >= 50) { - Sentry.withScope(function (scope) { - const sentryLevelName = - data.level === 50 ? Sentry.Severity.Error : Sentry.Severity.Fatal; - scope.setLevel(sentryLevelName); - - for (const extra of ["event", "headers", "request", "status"]) { - if (!data[extra]) continue; - - scope.setExtra(extra, data[extra]); - } - - // set user id and username to installation ID and account login - if (data.event && data.event.payload) { - const { - // When GitHub App is installed organization wide - installation: { id, account: { login: account } = {} } = {}, - - // When the repository belongs to an organization - organization: { login: organization } = {}, - // When the repository belongs to a user - repository: { owner: { login: owner } = {} } = {}, - } = data.event.payload; - - scope.setUser({ - id: id, - username: account || organization || owner, - }); - } - - Sentry.captureException(toSentryError(data)); - }); - } - - if (formattingEnabled) { - return cb(null, pretty(data || line)); - } - - if (levelAsString) { - return cb(null, stringifyLogLevel(data || JSON.parse(line))); - } - - cb(null, line + "\n"); - }, - }); -} - -function stringifyLogLevel(data) { - data.level = LEVEL_MAP[data.level]; - return JSON.stringify(data) + "\n"; -} - -function toSentryError(data) { - const error = new Error(data.msg); - error.name = data.type; - error.stack = data.stack; - return error; -} - - -/***/ }), - -/***/ 90785: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var SENTRY_API_VERSION = '7'; -/** Helper class to provide urls to different Sentry endpoints. */ -var API = /** @class */ (function () { - /** Create a new instance of API */ - function API(dsn) { - this.dsn = dsn; - this._dsnObject = new utils_1.Dsn(dsn); - } - /** Returns the Dsn object. */ - API.prototype.getDsn = function () { - return this._dsnObject; - }; - /** Returns the prefix to construct Sentry ingestion API endpoints. */ - API.prototype.getBaseApiEndpoint = function () { - var dsn = this._dsnObject; - var protocol = dsn.protocol ? dsn.protocol + ":" : ''; - var port = dsn.port ? ":" + dsn.port : ''; - return protocol + "//" + dsn.host + port + (dsn.path ? "/" + dsn.path : '') + "/api/"; - }; - /** Returns the store endpoint URL. */ - API.prototype.getStoreEndpoint = function () { - return this._getIngestEndpoint('store'); - }; - /** - * Returns the store endpoint URL with auth in the query string. - * - * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. - */ - API.prototype.getStoreEndpointWithUrlEncodedAuth = function () { - return this.getStoreEndpoint() + "?" + this._encodedAuth(); - }; - /** - * Returns the envelope endpoint URL with auth in the query string. - * - * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. - */ - API.prototype.getEnvelopeEndpointWithUrlEncodedAuth = function () { - return this._getEnvelopeEndpoint() + "?" + this._encodedAuth(); - }; - /** Returns only the path component for the store endpoint. */ - API.prototype.getStoreEndpointPath = function () { - var dsn = this._dsnObject; - return (dsn.path ? "/" + dsn.path : '') + "/api/" + dsn.projectId + "/store/"; - }; - /** - * Returns an object that can be used in request headers. - * This is needed for node and the old /store endpoint in sentry - */ - API.prototype.getRequestHeaders = function (clientName, clientVersion) { - var dsn = this._dsnObject; - var header = ["Sentry sentry_version=" + SENTRY_API_VERSION]; - header.push("sentry_client=" + clientName + "/" + clientVersion); - header.push("sentry_key=" + dsn.user); - if (dsn.pass) { - header.push("sentry_secret=" + dsn.pass); - } - return { - 'Content-Type': 'application/json', - 'X-Sentry-Auth': header.join(', '), - }; - }; - /** Returns the url to the report dialog endpoint. */ - API.prototype.getReportDialogEndpoint = function (dialogOptions) { - if (dialogOptions === void 0) { dialogOptions = {}; } - var dsn = this._dsnObject; - var endpoint = this.getBaseApiEndpoint() + "embed/error-page/"; - var encodedOptions = []; - encodedOptions.push("dsn=" + dsn.toString()); - for (var key in dialogOptions) { - if (key === 'dsn') { - continue; - } - if (key === 'user') { - if (!dialogOptions.user) { - continue; - } - if (dialogOptions.user.name) { - encodedOptions.push("name=" + encodeURIComponent(dialogOptions.user.name)); - } - if (dialogOptions.user.email) { - encodedOptions.push("email=" + encodeURIComponent(dialogOptions.user.email)); - } - } - else { - encodedOptions.push(encodeURIComponent(key) + "=" + encodeURIComponent(dialogOptions[key])); - } - } - if (encodedOptions.length) { - return endpoint + "?" + encodedOptions.join('&'); - } - return endpoint; - }; - /** Returns the envelope endpoint URL. */ - API.prototype._getEnvelopeEndpoint = function () { - return this._getIngestEndpoint('envelope'); - }; - /** Returns the ingest API endpoint for target. */ - API.prototype._getIngestEndpoint = function (target) { - var base = this.getBaseApiEndpoint(); - var dsn = this._dsnObject; - return "" + base + dsn.projectId + "/" + target + "/"; - }; - /** Returns a URL-encoded string with auth config suitable for a query string. */ - API.prototype._encodedAuth = function () { - var dsn = this._dsnObject; - var auth = { - // We send only the minimum set of required information. See - // https://github.com/getsentry/sentry-javascript/issues/2572. - sentry_key: dsn.user, - sentry_version: SENTRY_API_VERSION, - }; - return utils_1.urlEncode(auth); - }; - return API; -}()); -exports.API = API; -//# sourceMappingURL=api.js.map - -/***/ }), - -/***/ 25886: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var noop_1 = __nccwpck_require__(68641); -/** - * This is the base implemention of a Backend. - * @hidden - */ -var BaseBackend = /** @class */ (function () { - /** Creates a new backend instance. */ - function BaseBackend(options) { - this._options = options; - if (!this._options.dsn) { - utils_1.logger.warn('No DSN provided, backend will not do anything.'); - } - this._transport = this._setupTransport(); - } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - BaseBackend.prototype.eventFromException = function (_exception, _hint) { - throw new utils_1.SentryError('Backend has to implement `eventFromException` method'); - }; - /** - * @inheritDoc - */ - BaseBackend.prototype.eventFromMessage = function (_message, _level, _hint) { - throw new utils_1.SentryError('Backend has to implement `eventFromMessage` method'); - }; - /** - * @inheritDoc - */ - BaseBackend.prototype.sendEvent = function (event) { - this._transport.sendEvent(event).then(null, function (reason) { - utils_1.logger.error("Error while sending event: " + reason); - }); - }; - /** - * @inheritDoc - */ - BaseBackend.prototype.sendSession = function (session) { - if (!this._transport.sendSession) { - utils_1.logger.warn("Dropping session because custom transport doesn't implement sendSession"); - return; - } - this._transport.sendSession(session).then(null, function (reason) { - utils_1.logger.error("Error while sending session: " + reason); - }); - }; - /** - * @inheritDoc - */ - BaseBackend.prototype.getTransport = function () { - return this._transport; - }; - /** - * Sets up the transport so it can be used later to send requests. - */ - BaseBackend.prototype._setupTransport = function () { - return new noop_1.NoopTransport(); - }; - return BaseBackend; -}()); -exports.BaseBackend = BaseBackend; -//# sourceMappingURL=basebackend.js.map + } -/***/ }), + const defaultRepoConfig = await getConfigFile(octokit, { + owner, + repo: ".github", + path + }); + return [requestedRepoFile, defaultRepoConfig]; + } // if the configuration has no `_extends` key, we are done here. -/***/ 25684: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -/* eslint-disable max-lines */ -var hub_1 = __nccwpck_require__(6393); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var integration_1 = __nccwpck_require__(58500); + if (!requestedRepoFile.config._extends) { + return [requestedRepoFile]; + } // parse the value of `_extends` into request parameters to + // retrieve the new configuration file + + + let extendConfigOptions = extendsToGetContentParams({ + owner, + path, + url: requestedRepoFile.url, + extendsValue: requestedRepoFile.config._extends + }); // remove the `_extends` key from the configuration that is returned + + delete requestedRepoFile.config._extends; + const files = [requestedRepoFile]; // now load the configuration linked from the `_extends` key. If that + // configuration also includes an `_extends` key, then load that configuration + // as well, until the target configuration has no `_extends` key + + do { + const extendRepoConfig = await getConfigFile(octokit, extendConfigOptions); + files.push(extendRepoConfig); + + if (!extendRepoConfig.config || !extendRepoConfig.config._extends) { + return files; + } + + extendConfigOptions = extendsToGetContentParams({ + owner, + path, + url: extendRepoConfig.url, + extendsValue: extendRepoConfig.config._extends + }); + delete extendRepoConfig.config._extends; // Avoid loops + + const alreadyLoaded = files.find(file => file.owner === extendConfigOptions.owner && file.repo === extendConfigOptions.repo && file.path === extendConfigOptions.path); + + if (alreadyLoaded) { + throw new Error(`[@probot/octokit-plugin-config] Recursion detected. Ignoring "_extends: ${extendRepoConfig.config._extends}" from ${extendRepoConfig.url} because ${alreadyLoaded.url} was already loaded.`); + } + } while (true); +} + /** - * Base implementation for all JavaScript SDK clients. - * - * Call the constructor with the corresponding backend constructor and options - * specific to the client subclass. To access these options later, use - * {@link Client.getOptions}. Also, the Backend instance is available via - * {@link Client.getBackend}. - * - * If a Dsn is specified in the options, it will be parsed and stored. Use - * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is - * invalid, the constructor will throw a {@link SentryException}. Note that - * without a valid Dsn, the SDK will not send any events to Sentry. - * - * Before sending an event via the backend, it is passed through - * {@link BaseClient.prepareEvent} to add SDK information and scope data - * (breadcrumbs and context). To add more custom information, override this - * method and extend the resulting prepared event. - * - * To issue automatically created events (e.g. via instrumentation), use - * {@link Client.captureEvent}. It will prepare the event and pass it through - * the callback lifecycle. To issue auto-breadcrumbs, use - * {@link Client.addBreadcrumb}. - * - * @example - * class NodeClient extends BaseClient { - * public constructor(options: NodeOptions) { - * super(NodeBackend, options); - * } + * Loads configuration from one or multiple files and resolves with + * the combined configuration as well as the list of files the configuration + * was loaded from * - * // ... - * } + * @param octokit Octokit instance + * @param options */ -var BaseClient = /** @class */ (function () { - /** - * Initializes this client instance. - * - * @param backendClass A constructor function to create the backend. - * @param options Options for the client. - */ - function BaseClient(backendClass, options) { - /** Array of used integrations. */ - this._integrations = {}; - /** Number of call being processed */ - this._processing = 0; - this._backend = new backendClass(options); - this._options = options; - if (options.dsn) { - this._dsn = new utils_1.Dsn(options.dsn); - } - } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - BaseClient.prototype.captureException = function (exception, hint, scope) { - var _this = this; - var eventId = hint && hint.event_id; - this._process(this._getBackend() - .eventFromException(exception, hint) - .then(function (event) { return _this._captureEvent(event, hint, scope); }) - .then(function (result) { - eventId = result; - })); - return eventId; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.captureMessage = function (message, level, hint, scope) { - var _this = this; - var eventId = hint && hint.event_id; - var promisedEvent = utils_1.isPrimitive(message) - ? this._getBackend().eventFromMessage(String(message), level, hint) - : this._getBackend().eventFromException(message, hint); - this._process(promisedEvent - .then(function (event) { return _this._captureEvent(event, hint, scope); }) - .then(function (result) { - eventId = result; - })); - return eventId; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.captureEvent = function (event, hint, scope) { - var eventId = hint && hint.event_id; - this._process(this._captureEvent(event, hint, scope).then(function (result) { - eventId = result; - })); - return eventId; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.captureSession = function (session) { - if (!session.release) { - utils_1.logger.warn('Discarded session because of missing release'); - } - else { - this._sendSession(session); - } - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getDsn = function () { - return this._dsn; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getOptions = function () { - return this._options; - }; - /** - * @inheritDoc - */ - BaseClient.prototype.flush = function (timeout) { - var _this = this; - return this._isClientProcessing(timeout).then(function (ready) { - return _this._getBackend() - .getTransport() - .close(timeout) - .then(function (transportFlushed) { return ready && transportFlushed; }); - }); - }; - /** - * @inheritDoc - */ - BaseClient.prototype.close = function (timeout) { - var _this = this; - return this.flush(timeout).then(function (result) { - _this.getOptions().enabled = false; - return result; - }); - }; - /** - * Sets up the integrations - */ - BaseClient.prototype.setupIntegrations = function () { - if (this._isEnabled()) { - this._integrations = integration_1.setupIntegrations(this._options); - } - }; - /** - * @inheritDoc - */ - BaseClient.prototype.getIntegration = function (integration) { - try { - return this._integrations[integration.id] || null; - } - catch (_oO) { - utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Client"); - return null; - } - }; - /** Updates existing session based on the provided event */ - BaseClient.prototype._updateSessionFromEvent = function (session, event) { - var e_1, _a; - var crashed = false; - var errored = false; - var userAgent; - var exceptions = event.exception && event.exception.values; - if (exceptions) { - errored = true; - try { - for (var exceptions_1 = tslib_1.__values(exceptions), exceptions_1_1 = exceptions_1.next(); !exceptions_1_1.done; exceptions_1_1 = exceptions_1.next()) { - var ex = exceptions_1_1.value; - var mechanism = ex.mechanism; - if (mechanism && mechanism.handled === false) { - crashed = true; - break; - } - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (exceptions_1_1 && !exceptions_1_1.done && (_a = exceptions_1.return)) _a.call(exceptions_1); - } - finally { if (e_1) throw e_1.error; } - } - } - var user = event.user; - if (!session.userAgent) { - var headers = event.request ? event.request.headers : {}; - for (var key in headers) { - if (key.toLowerCase() === 'user-agent') { - userAgent = headers[key]; - break; - } - } - } - session.update(tslib_1.__assign(tslib_1.__assign({}, (crashed && { status: types_1.SessionStatus.Crashed })), { user: user, - userAgent: userAgent, errors: session.errors + Number(errored || crashed) })); - }; - /** Deliver captured session to Sentry */ - BaseClient.prototype._sendSession = function (session) { - this._getBackend().sendSession(session); - }; - /** Waits for the client to be done with processing. */ - BaseClient.prototype._isClientProcessing = function (timeout) { - var _this = this; - return new utils_1.SyncPromise(function (resolve) { - var ticked = 0; - var tick = 1; - var interval = setInterval(function () { - if (_this._processing == 0) { - clearInterval(interval); - resolve(true); - } - else { - ticked += tick; - if (timeout && ticked >= timeout) { - clearInterval(interval); - resolve(false); - } - } - }, tick); - }); - }; - /** Returns the current backend. */ - BaseClient.prototype._getBackend = function () { - return this._backend; - }; - /** Determines whether this SDK is enabled and a valid Dsn is present. */ - BaseClient.prototype._isEnabled = function () { - return this.getOptions().enabled !== false && this._dsn !== undefined; - }; - /** - * Adds common information to events. - * - * The information includes release and environment from `options`, - * breadcrumbs and context (extra, tags and user) from the scope. - * - * Information that is already present in the event is never overwritten. For - * nested objects, such as the context, keys are merged. - * - * @param event The original event. - * @param hint May contain additional information about the original exception. - * @param scope A scope containing event metadata. - * @returns A new event with more information. - */ - BaseClient.prototype._prepareEvent = function (event, scope, hint) { - var _this = this; - var _a = this.getOptions().normalizeDepth, normalizeDepth = _a === void 0 ? 3 : _a; - var prepared = tslib_1.__assign(tslib_1.__assign({}, event), { event_id: event.event_id || (hint && hint.event_id ? hint.event_id : utils_1.uuid4()), timestamp: event.timestamp || utils_1.dateTimestampInSeconds() }); - this._applyClientOptions(prepared); - this._applyIntegrationsMetadata(prepared); - // If we have scope given to us, use it as the base for further modifications. - // This allows us to prevent unnecessary copying of data if `captureContext` is not provided. - var finalScope = scope; - if (hint && hint.captureContext) { - finalScope = hub_1.Scope.clone(finalScope).update(hint.captureContext); - } - // We prepare the result here with a resolved Event. - var result = utils_1.SyncPromise.resolve(prepared); - // This should be the last thing called, since we want that - // {@link Hub.addEventProcessor} gets the finished prepared event. - if (finalScope) { - // In case we have a hub we reassign it. - result = finalScope.applyToEvent(prepared, hint); - } - return result.then(function (evt) { - if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { - return _this._normalizeEvent(evt, normalizeDepth); - } - return evt; - }); - }; - /** - * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization. - * Normalized keys: - * - `breadcrumbs.data` - * - `user` - * - `contexts` - * - `extra` - * @param event Event - * @returns Normalized event - */ - BaseClient.prototype._normalizeEvent = function (event, depth) { - if (!event) { - return null; - } - var normalized = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, event), (event.breadcrumbs && { - breadcrumbs: event.breadcrumbs.map(function (b) { return (tslib_1.__assign(tslib_1.__assign({}, b), (b.data && { - data: utils_1.normalize(b.data, depth), - }))); }), - })), (event.user && { - user: utils_1.normalize(event.user, depth), - })), (event.contexts && { - contexts: utils_1.normalize(event.contexts, depth), - })), (event.extra && { - extra: utils_1.normalize(event.extra, depth), - })); - // event.contexts.trace stores information about a Transaction. Similarly, - // event.spans[] stores information about child Spans. Given that a - // Transaction is conceptually a Span, normalization should apply to both - // Transactions and Spans consistently. - // For now the decision is to skip normalization of Transactions and Spans, - // so this block overwrites the normalized event to add back the original - // Transaction information prior to normalization. - if (event.contexts && event.contexts.trace) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - normalized.contexts.trace = event.contexts.trace; - } - return normalized; - }; - /** - * Enhances event using the client configuration. - * It takes care of all "static" values like environment, release and `dist`, - * as well as truncating overly long values. - * @param event event instance to be enhanced - */ - BaseClient.prototype._applyClientOptions = function (event) { - var options = this.getOptions(); - var environment = options.environment, release = options.release, dist = options.dist, _a = options.maxValueLength, maxValueLength = _a === void 0 ? 250 : _a; - if (!('environment' in event)) { - event.environment = 'environment' in options ? environment : 'production'; - } - if (event.release === undefined && release !== undefined) { - event.release = release; - } - if (event.dist === undefined && dist !== undefined) { - event.dist = dist; - } - if (event.message) { - event.message = utils_1.truncate(event.message, maxValueLength); - } - var exception = event.exception && event.exception.values && event.exception.values[0]; - if (exception && exception.value) { - exception.value = utils_1.truncate(exception.value, maxValueLength); - } - var request = event.request; - if (request && request.url) { - request.url = utils_1.truncate(request.url, maxValueLength); - } - }; - /** - * This function adds all used integrations to the SDK info in the event. - * @param sdkInfo The sdkInfo of the event that will be filled with all integrations. - */ - BaseClient.prototype._applyIntegrationsMetadata = function (event) { - var sdkInfo = event.sdk; - var integrationsArray = Object.keys(this._integrations); - if (sdkInfo && integrationsArray.length > 0) { - sdkInfo.integrations = integrationsArray; - } - }; - /** - * Tells the backend to send this event - * @param event The Sentry event to send - */ - BaseClient.prototype._sendEvent = function (event) { - this._getBackend().sendEvent(event); - }; - /** - * Processes the event and logs an error in case of rejection - * @param event - * @param hint - * @param scope - */ - BaseClient.prototype._captureEvent = function (event, hint, scope) { - return this._processEvent(event, hint, scope).then(function (finalEvent) { - return finalEvent.event_id; - }, function (reason) { - utils_1.logger.error(reason); - return undefined; - }); - }; - /** - * Processes an event (either error or message) and sends it to Sentry. - * - * This also adds breadcrumbs and context information to the event. However, - * platform specific meta data (such as the User's IP address) must be added - * by the SDK implementor. - * - * - * @param event The event to send to Sentry. - * @param hint May contain additional information about the original exception. - * @param scope A scope containing event metadata. - * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send. - */ - BaseClient.prototype._processEvent = function (event, hint, scope) { - var _this = this; - // eslint-disable-next-line @typescript-eslint/unbound-method - var _a = this.getOptions(), beforeSend = _a.beforeSend, sampleRate = _a.sampleRate; - if (!this._isEnabled()) { - return utils_1.SyncPromise.reject(new utils_1.SentryError('SDK not enabled, will not send event.')); - } - var isTransaction = event.type === 'transaction'; - // 1.0 === 100% events are sent - // 0.0 === 0% events are sent - // Sampling for transaction happens somewhere else - if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) { - return utils_1.SyncPromise.reject(new utils_1.SentryError('This event has been sampled, will not send event.')); - } - return this._prepareEvent(event, scope, hint) - .then(function (prepared) { - if (prepared === null) { - throw new utils_1.SentryError('An event processor returned null, will not send event.'); - } - var isInternalException = hint && hint.data && hint.data.__sentry__ === true; - if (isInternalException || isTransaction || !beforeSend) { - return prepared; - } - var beforeSendResult = beforeSend(prepared, hint); - if (typeof beforeSendResult === 'undefined') { - throw new utils_1.SentryError('`beforeSend` method has to return `null` or a valid event.'); - } - else if (utils_1.isThenable(beforeSendResult)) { - return beforeSendResult.then(function (event) { return event; }, function (e) { - throw new utils_1.SentryError("beforeSend rejected with " + e); - }); - } - return beforeSendResult; - }) - .then(function (processedEvent) { - if (processedEvent === null) { - throw new utils_1.SentryError('`beforeSend` returned `null`, will not send event.'); - } - var session = scope && scope.getSession && scope.getSession(); - if (!isTransaction && session) { - _this._updateSessionFromEvent(session, processedEvent); - } - _this._sendEvent(processedEvent); - return processedEvent; - }) - .then(null, function (reason) { - if (reason instanceof utils_1.SentryError) { - throw reason; - } - _this.captureException(reason, { - data: { - __sentry__: true, - }, - originalException: reason, - }); - throw new utils_1.SentryError("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: " + reason); - }); - }; - /** - * Occupies the client with processing and event - */ - BaseClient.prototype._process = function (promise) { - var _this = this; - this._processing += 1; - promise.then(function (value) { - _this._processing -= 1; - return value; - }, function (reason) { - _this._processing -= 1; - return reason; - }); - }; - return BaseClient; -}()); -exports.BaseClient = BaseClient; -//# sourceMappingURL=baseclient.js.map + +async function composeConfigGet(octokit, { + owner, + repo, + defaults, + path, + branch +}) { + const files = await getConfigFiles(octokit, { + owner, + repo, + path, + branch + }); + const configs = files.map(file => file.config).reverse().filter(Boolean); + return { + files, + config: typeof defaults === "function" ? defaults(configs) : Object.assign({}, defaults, ...configs) + }; +} + +/** + * @param octokit Octokit instance + */ + +function config(octokit) { + return { + config: { + async get(options) { + return composeConfigGet(octokit, options); + } + + } + }; +} +config.VERSION = VERSION; + +exports.composeConfigGet = composeConfigGet; +exports.config = config; +//# sourceMappingURL=index.js.map + /***/ }), -/***/ 79212: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 80557: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + + +var loader = __nccwpck_require__(26106); +var dumper = __nccwpck_require__(73811); + + +function renamed(from, to) { + return function () { + throw new Error('Function yaml.' + from + ' is removed in js-yaml 4. ' + + 'Use yaml.' + to + ' instead, which is now safe by default.'); + }; +} + + +module.exports.Type = __nccwpck_require__(57480); +module.exports.Schema = __nccwpck_require__(22258); +module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(54323); +module.exports.JSON_SCHEMA = __nccwpck_require__(70265); +module.exports.CORE_SCHEMA = __nccwpck_require__(90085); +module.exports.DEFAULT_SCHEMA = __nccwpck_require__(77599); +module.exports.load = loader.load; +module.exports.loadAll = loader.loadAll; +module.exports.dump = dumper.dump; +module.exports.YAMLException = __nccwpck_require__(30780); + +// Re-export all types in case user wants to create custom schema +module.exports.types = { + binary: __nccwpck_require__(56942), + float: __nccwpck_require__(56128), + map: __nccwpck_require__(74352), + null: __nccwpck_require__(61002), + pairs: __nccwpck_require__(18978), + set: __nccwpck_require__(87424), + timestamp: __nccwpck_require__(9561), + bool: __nccwpck_require__(85327), + int: __nccwpck_require__(2848), + merge: __nccwpck_require__(70884), + omap: __nccwpck_require__(65894), + seq: __nccwpck_require__(89695), + str: __nccwpck_require__(32568) +}; + +// Removed functions from JS-YAML 3.0.x +module.exports.safeLoad = renamed('safeLoad', 'load'); +module.exports.safeLoadAll = renamed('safeLoadAll', 'loadAll'); +module.exports.safeDump = renamed('safeDump', 'dump'); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var minimal_1 = __nccwpck_require__(88455); -exports.addBreadcrumb = minimal_1.addBreadcrumb; -exports.captureException = minimal_1.captureException; -exports.captureEvent = minimal_1.captureEvent; -exports.captureMessage = minimal_1.captureMessage; -exports.configureScope = minimal_1.configureScope; -exports.startTransaction = minimal_1.startTransaction; -exports.setContext = minimal_1.setContext; -exports.setExtra = minimal_1.setExtra; -exports.setExtras = minimal_1.setExtras; -exports.setTag = minimal_1.setTag; -exports.setTags = minimal_1.setTags; -exports.setUser = minimal_1.setUser; -exports.withScope = minimal_1.withScope; -var hub_1 = __nccwpck_require__(6393); -exports.addGlobalEventProcessor = hub_1.addGlobalEventProcessor; -exports.getCurrentHub = hub_1.getCurrentHub; -exports.getHubFromCarrier = hub_1.getHubFromCarrier; -exports.Hub = hub_1.Hub; -exports.makeMain = hub_1.makeMain; -exports.Scope = hub_1.Scope; -var api_1 = __nccwpck_require__(90785); -exports.API = api_1.API; -var baseclient_1 = __nccwpck_require__(25684); -exports.BaseClient = baseclient_1.BaseClient; -var basebackend_1 = __nccwpck_require__(25886); -exports.BaseBackend = basebackend_1.BaseBackend; -var request_1 = __nccwpck_require__(1553); -exports.eventToSentryRequest = request_1.eventToSentryRequest; -exports.sessionToSentryRequest = request_1.sessionToSentryRequest; -var sdk_1 = __nccwpck_require__(46406); -exports.initAndBind = sdk_1.initAndBind; -var noop_1 = __nccwpck_require__(68641); -exports.NoopTransport = noop_1.NoopTransport; -var Integrations = __nccwpck_require__(96727); -exports.Integrations = Integrations; -//# sourceMappingURL=index.js.map /***/ }), -/***/ 58500: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 44828: +/***/ ((module) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); -exports.installedIntegrations = []; -/** Gets integration to install */ -function getIntegrationsToSetup(options) { - var defaultIntegrations = (options.defaultIntegrations && tslib_1.__spread(options.defaultIntegrations)) || []; - var userIntegrations = options.integrations; - var integrations = []; - if (Array.isArray(userIntegrations)) { - var userIntegrationsNames_1 = userIntegrations.map(function (i) { return i.name; }); - var pickedIntegrationsNames_1 = []; - // Leave only unique default integrations, that were not overridden with provided user integrations - defaultIntegrations.forEach(function (defaultIntegration) { - if (userIntegrationsNames_1.indexOf(defaultIntegration.name) === -1 && - pickedIntegrationsNames_1.indexOf(defaultIntegration.name) === -1) { - integrations.push(defaultIntegration); - pickedIntegrationsNames_1.push(defaultIntegration.name); - } - }); - // Don't add same user integration twice - userIntegrations.forEach(function (userIntegration) { - if (pickedIntegrationsNames_1.indexOf(userIntegration.name) === -1) { - integrations.push(userIntegration); - pickedIntegrationsNames_1.push(userIntegration.name); - } - }); - } - else if (typeof userIntegrations === 'function') { - integrations = userIntegrations(defaultIntegrations); - integrations = Array.isArray(integrations) ? integrations : [integrations]; - } - else { - integrations = tslib_1.__spread(defaultIntegrations); - } - // Make sure that if present, `Debug` integration will always run last - var integrationsNames = integrations.map(function (i) { return i.name; }); - var alwaysLastToRun = 'Debug'; - if (integrationsNames.indexOf(alwaysLastToRun) !== -1) { - integrations.push.apply(integrations, tslib_1.__spread(integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1))); - } - return integrations; +"use strict"; + + + +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); } -exports.getIntegrationsToSetup = getIntegrationsToSetup; -/** Setup given integration */ -function setupIntegration(integration) { - if (exports.installedIntegrations.indexOf(integration.name) !== -1) { - return; - } - integration.setupOnce(hub_1.addGlobalEventProcessor, hub_1.getCurrentHub); - exports.installedIntegrations.push(integration.name); - utils_1.logger.log("Integration installed: " + integration.name); + + +function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); } -exports.setupIntegration = setupIntegration; -/** - * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default - * integrations are added unless they were already provided before. - * @param integrations array of integration instances - * @param withDefault should enable default integrations - */ -function setupIntegrations(options) { - var integrations = {}; - getIntegrationsToSetup(options).forEach(function (integration) { - integrations[integration.name] = integration; - setupIntegration(integration); - }); - return integrations; + + +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; + + return [ sequence ]; } -exports.setupIntegrations = setupIntegrations; -//# sourceMappingURL=integration.js.map -/***/ }), -/***/ 87349: -/***/ ((__unused_webpack_module, exports) => { +function extend(target, source) { + var index, length, key, sourceKeys; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var originalFunctionToString; -/** Patch toString calls to return proper name for wrapped functions */ -var FunctionToString = /** @class */ (function () { - function FunctionToString() { - /** - * @inheritDoc - */ - this.name = FunctionToString.id; + if (source) { + sourceKeys = Object.keys(source); + + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; } - /** - * @inheritDoc - */ - FunctionToString.prototype.setupOnce = function () { - // eslint-disable-next-line @typescript-eslint/unbound-method - originalFunctionToString = Function.prototype.toString; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Function.prototype.toString = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var context = this.__sentry_original__ || this; - return originalFunctionToString.apply(context, args); - }; - }; - /** - * @inheritDoc - */ - FunctionToString.id = 'FunctionToString'; - return FunctionToString; -}()); -exports.FunctionToString = FunctionToString; -//# sourceMappingURL=functiontostring.js.map + } + + return target; +} + + +function repeat(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; + } + + return result; +} + + +function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); +} + + +module.exports.isNothing = isNothing; +module.exports.isObject = isObject; +module.exports.toArray = toArray; +module.exports.repeat = repeat; +module.exports.isNegativeZero = isNegativeZero; +module.exports.extend = extend; + /***/ }), -/***/ 54838: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 73811: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); -// "Script error." is hard coded into browsers for errors that it can't read. -// this is the result of a script being pulled in from an external domain and CORS. -var DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/]; -/** Inbound filters configurable by the user */ -var InboundFilters = /** @class */ (function () { - function InboundFilters(_options) { - if (_options === void 0) { _options = {}; } - this._options = _options; - /** - * @inheritDoc - */ - this.name = InboundFilters.id; +"use strict"; + + +/*eslint-disable no-use-before-define*/ + +var common = __nccwpck_require__(44828); +var YAMLException = __nccwpck_require__(30780); +var DEFAULT_SCHEMA = __nccwpck_require__(77599); + +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +var CHAR_BOM = 0xFEFF; +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_EQUALS = 0x3D; /* = */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ + +var ESCAPE_SEQUENCES = {}; + +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; + +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; + +var DEPRECATED_BASE60_SYNTAX = /^[-+]?[0-9_]+(?::[0-9_]+)+(?:\.[0-9_]*)?$/; + +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; + + if (map === null) return {}; + + result = {}; + keys = Object.keys(map); + + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); + + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); } - /** - * @inheritDoc - */ - InboundFilters.prototype.setupOnce = function () { - hub_1.addGlobalEventProcessor(function (event) { - var hub = hub_1.getCurrentHub(); - if (!hub) { - return event; - } - var self = hub.getIntegration(InboundFilters); - if (self) { - var client = hub.getClient(); - var clientOptions = client ? client.getOptions() : {}; - var options = self._mergeOptions(clientOptions); - if (self._shouldDropEvent(event, options)) { - return null; - } - } - return event; - }); - }; - /** JSDoc */ - InboundFilters.prototype._shouldDropEvent = function (event, options) { - if (this._isSentryError(event, options)) { - utils_1.logger.warn("Event dropped due to being internal Sentry Error.\nEvent: " + utils_1.getEventDescription(event)); - return true; - } - if (this._isIgnoredError(event, options)) { - utils_1.logger.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: " + utils_1.getEventDescription(event)); - return true; - } - if (this._isDeniedUrl(event, options)) { - utils_1.logger.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: " + utils_1.getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event)); - return true; - } - if (!this._isAllowedUrl(event, options)) { - utils_1.logger.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: " + utils_1.getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event)); - return true; - } - return false; - }; - /** JSDoc */ - InboundFilters.prototype._isSentryError = function (event, options) { - if (!options.ignoreInternal) { - return false; - } - try { - return ((event && - event.exception && - event.exception.values && - event.exception.values[0] && - event.exception.values[0].type === 'SentryError') || - false); - } - catch (_oO) { - return false; - } - }; - /** JSDoc */ - InboundFilters.prototype._isIgnoredError = function (event, options) { - if (!options.ignoreErrors || !options.ignoreErrors.length) { - return false; - } - return this._getPossibleEventMessages(event).some(function (message) { - // Not sure why TypeScript complains here... - return options.ignoreErrors.some(function (pattern) { return utils_1.isMatchingPattern(message, pattern); }); - }); - }; - /** JSDoc */ - InboundFilters.prototype._isDeniedUrl = function (event, options) { - // TODO: Use Glob instead? - if (!options.denyUrls || !options.denyUrls.length) { - return false; - } - var url = this._getEventFilterUrl(event); - return !url ? false : options.denyUrls.some(function (pattern) { return utils_1.isMatchingPattern(url, pattern); }); - }; - /** JSDoc */ - InboundFilters.prototype._isAllowedUrl = function (event, options) { - // TODO: Use Glob instead? - if (!options.allowUrls || !options.allowUrls.length) { - return true; - } - var url = this._getEventFilterUrl(event); - return !url ? true : options.allowUrls.some(function (pattern) { return utils_1.isMatchingPattern(url, pattern); }); - }; - /** JSDoc */ - InboundFilters.prototype._mergeOptions = function (clientOptions) { - if (clientOptions === void 0) { clientOptions = {}; } - return { - allowUrls: tslib_1.__spread((this._options.whitelistUrls || []), (this._options.allowUrls || []), (clientOptions.whitelistUrls || []), (clientOptions.allowUrls || [])), - denyUrls: tslib_1.__spread((this._options.blacklistUrls || []), (this._options.denyUrls || []), (clientOptions.blacklistUrls || []), (clientOptions.denyUrls || [])), - ignoreErrors: tslib_1.__spread((this._options.ignoreErrors || []), (clientOptions.ignoreErrors || []), DEFAULT_IGNORE_ERRORS), - ignoreInternal: typeof this._options.ignoreInternal !== 'undefined' ? this._options.ignoreInternal : true, - }; - }; - /** JSDoc */ - InboundFilters.prototype._getPossibleEventMessages = function (event) { - if (event.message) { - return [event.message]; - } - if (event.exception) { - try { - var _a = (event.exception.values && event.exception.values[0]) || {}, _b = _a.type, type = _b === void 0 ? '' : _b, _c = _a.value, value = _c === void 0 ? '' : _c; - return ["" + value, type + ": " + value]; - } - catch (oO) { - utils_1.logger.error("Cannot extract message for event " + utils_1.getEventDescription(event)); - return []; - } - } - return []; - }; - /** JSDoc */ - InboundFilters.prototype._getEventFilterUrl = function (event) { - try { - if (event.stacktrace) { - var frames_1 = event.stacktrace.frames; - return (frames_1 && frames_1[frames_1.length - 1].filename) || null; - } - if (event.exception) { - var frames_2 = event.exception.values && event.exception.values[0].stacktrace && event.exception.values[0].stacktrace.frames; - return (frames_2 && frames_2[frames_2.length - 1].filename) || null; - } - return null; - } - catch (oO) { - utils_1.logger.error("Cannot extract url for event " + utils_1.getEventDescription(event)); - return null; - } - }; - /** - * @inheritDoc - */ - InboundFilters.id = 'InboundFilters'; - return InboundFilters; -}()); -exports.InboundFilters = InboundFilters; -//# sourceMappingURL=inboundfilters.js.map + type = schema.compiledTypeMap['fallback'][tag]; -/***/ }), + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } -/***/ 96727: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + result[tag] = style; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var functiontostring_1 = __nccwpck_require__(87349); -exports.FunctionToString = functiontostring_1.FunctionToString; -var inboundfilters_1 = __nccwpck_require__(54838); -exports.InboundFilters = inboundfilters_1.InboundFilters; -//# sourceMappingURL=index.js.map + return result; +} + +function encodeHex(character) { + var string, handle, length; + + string = character.toString(16).toUpperCase(); + + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + } + + return '\\' + handle + common.repeat('0', length - string.length) + string; +} + + +var QUOTING_TYPE_SINGLE = 1, + QUOTING_TYPE_DOUBLE = 2; + +function State(options) { + this.schema = options['schema'] || DEFAULT_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; + this.quotingType = options['quotingType'] === '"' ? QUOTING_TYPE_DOUBLE : QUOTING_TYPE_SINGLE; + this.forceQuotes = options['forceQuotes'] || false; + this.replacer = typeof options['replacer'] === 'function' ? options['replacer'] : null; + + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; + + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; +} + +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; -/***/ }), + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } -/***/ 1553: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (line.length && line !== '\n') result += ind; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -/** Creates a SentryRequest from an event. */ -function sessionToSentryRequest(session, api) { - var envelopeHeaders = JSON.stringify({ - sent_at: new Date().toISOString(), - }); - var itemHeaders = JSON.stringify({ - type: 'session', - }); - return { - body: envelopeHeaders + "\n" + itemHeaders + "\n" + JSON.stringify(session), - type: 'session', - url: api.getEnvelopeEndpointWithUrlEncodedAuth(), - }; + result += line; + } + + return result; } -exports.sessionToSentryRequest = sessionToSentryRequest; -/** Creates a SentryRequest from an event. */ -function eventToSentryRequest(event, api) { - // since JS has no Object.prototype.pop() - var _a = event.tags || {}, samplingMethod = _a.__sentry_samplingMethod, sampleRate = _a.__sentry_sampleRate, otherTags = tslib_1.__rest(_a, ["__sentry_samplingMethod", "__sentry_sampleRate"]); - event.tags = otherTags; - var useEnvelope = event.type === 'transaction'; - var req = { - body: JSON.stringify(event), - type: event.type || 'event', - url: useEnvelope ? api.getEnvelopeEndpointWithUrlEncodedAuth() : api.getStoreEndpointWithUrlEncodedAuth(), - }; - // https://develop.sentry.dev/sdk/envelopes/ - // Since we don't need to manipulate envelopes nor store them, there is no - // exported concept of an Envelope with operations including serialization and - // deserialization. Instead, we only implement a minimal subset of the spec to - // serialize events inline here. - if (useEnvelope) { - var envelopeHeaders = JSON.stringify({ - event_id: event.event_id, - sent_at: new Date().toISOString(), - }); - var itemHeaders = JSON.stringify({ - type: event.type, - // TODO: Right now, sampleRate may or may not be defined (it won't be in the cases of inheritance and - // explicitly-set sampling decisions). Are we good with that? - sample_rates: [{ id: samplingMethod, rate: sampleRate }], - }); - // The trailing newline is optional. We intentionally don't send it to avoid - // sending unnecessary bytes. - // - // const envelope = `${envelopeHeaders}\n${itemHeaders}\n${req.body}\n`; - var envelope = envelopeHeaders + "\n" + itemHeaders + "\n" + req.body; - req.body = envelope; - } - return req; + +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); } -exports.eventToSentryRequest = eventToSentryRequest; -//# sourceMappingURL=request.js.map -/***/ }), +function testImplicitResolving(state, str) { + var index, length, type; -/***/ 46406: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); -/** - * Internal function to create a new SDK client instance. The client is - * installed and then bound to the current scope. - * - * @param clientClass The client class to instantiate. - * @param options Options to pass to the client. - */ -function initAndBind(clientClass, options) { - if (options.debug === true) { - utils_1.logger.enable(); + if (type.resolve(str)) { + return true; } - var hub = hub_1.getCurrentHub(); - var client = new clientClass(options); - hub.bindClient(client); -} -exports.initAndBind = initAndBind; -//# sourceMappingURL=sdk.js.map + } -/***/ }), + return false; +} -/***/ 68641: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -/** Noop transport */ -var NoopTransport = /** @class */ (function () { - function NoopTransport() { - } - /** - * @inheritDoc - */ - NoopTransport.prototype.sendEvent = function (_) { - return utils_1.SyncPromise.resolve({ - reason: "NoopTransport: Event has been skipped because no Dsn is configured.", - status: types_1.Status.Skipped, - }); - }; - /** - * @inheritDoc - */ - NoopTransport.prototype.close = function (_) { - return utils_1.SyncPromise.resolve(true); - }; - return NoopTransport; -}()); -exports.NoopTransport = NoopTransport; -//# sourceMappingURL=noop.js.map +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== CHAR_BOM) + || (0x10000 <= c && c <= 0x10FFFF); +} -/***/ }), +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// Including s-white (for some reason, examples doesn't match specs in this aspect) +// ns-char ::= c-printable - b-line-feed - b-carriage-return - c-byte-order-mark +function isNsCharOrWhitespace(c) { + return isPrintable(c) + && c !== CHAR_BOM + // - b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} -/***/ 53536: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +// [127] ns-plain-safe(c) ::= c = flow-out ⇒ ns-plain-safe-out +// c = flow-in ⇒ ns-plain-safe-in +// c = block-key ⇒ ns-plain-safe-out +// c = flow-key ⇒ ns-plain-safe-in +// [128] ns-plain-safe-out ::= ns-char +// [129] ns-plain-safe-in ::= ns-char - c-flow-indicator +// [130] ns-plain-char(c) ::= ( ns-plain-safe(c) - “:” - “#” ) +// | ( /* An ns-char preceding */ “#” ) +// | ( “:” /* Followed by an ns-plain-safe(c) */ ) +function isPlainSafe(c, prev, inblock) { + var cIsNsCharOrWhitespace = isNsCharOrWhitespace(c); + var cIsNsChar = cIsNsCharOrWhitespace && !isWhitespace(c); + return ( + // ns-plain-safe + inblock ? // c = flow-in + cIsNsCharOrWhitespace + : cIsNsCharOrWhitespace + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + ) + // ns-plain-char + && c !== CHAR_SHARP // false on '#' + && !(prev === CHAR_COLON && !cIsNsChar) // false on ': ' + || (isNsCharOrWhitespace(prev) && !isWhitespace(prev) && c === CHAR_SHARP) // change to true on '[^ ]#' + || (prev === CHAR_COLON && cIsNsChar); // change to true on ':[^ ]' +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var scope_1 = __nccwpck_require__(4213); -var session_1 = __nccwpck_require__(12474); -/** - * API compatibility version of this hub. - * - * WARNING: This number should only be increased when the global interface - * changes and new methods are introduced. - * - * @hidden - */ -exports.API_VERSION = 3; -/** - * Default maximum number of breadcrumbs added to an event. Can be overwritten - * with {@link Options.maxBreadcrumbs}. - */ -var DEFAULT_BREADCRUMBS = 100; -/** - * Absolute maximum number of breadcrumbs added to an event. The - * `maxBreadcrumbs` option cannot be higher than this value. - */ -var MAX_BREADCRUMBS = 100; -/** - * @inheritDoc - */ -var Hub = /** @class */ (function () { - /** - * Creates a new instance of the hub, will push one {@link Layer} into the - * internal stack on creation. - * - * @param client bound to the hub. - * @param scope bound to the hub. - * @param version number, higher number means higher priority. - */ - function Hub(client, scope, _version) { - if (scope === void 0) { scope = new scope_1.Scope(); } - if (_version === void 0) { _version = exports.API_VERSION; } - this._version = _version; - /** Is a {@link Layer}[] containing the client and scope */ - this._stack = [{}]; - this.getStackTop().scope = scope; - this.bindClient(client); - } - /** - * @inheritDoc - */ - Hub.prototype.isOlderThan = function (version) { - return this._version < version; - }; - /** - * @inheritDoc - */ - Hub.prototype.bindClient = function (client) { - var top = this.getStackTop(); - top.client = client; - if (client && client.setupIntegrations) { - client.setupIntegrations(); - } - }; - /** - * @inheritDoc - */ - Hub.prototype.pushScope = function () { - // We want to clone the content of prev scope - var scope = scope_1.Scope.clone(this.getScope()); - this.getStack().push({ - client: this.getClient(), - scope: scope, - }); - return scope; - }; - /** - * @inheritDoc - */ - Hub.prototype.popScope = function () { - if (this.getStack().length <= 1) - return false; - return !!this.getStack().pop(); - }; - /** - * @inheritDoc - */ - Hub.prototype.withScope = function (callback) { - var scope = this.pushScope(); - try { - callback(scope); - } - finally { - this.popScope(); - } - }; - /** - * @inheritDoc - */ - Hub.prototype.getClient = function () { - return this.getStackTop().client; - }; - /** Returns the scope of the top stack. */ - Hub.prototype.getScope = function () { - return this.getStackTop().scope; - }; - /** Returns the scope stack for domains or the process. */ - Hub.prototype.getStack = function () { - return this._stack; - }; - /** Returns the topmost scope layer in the order domain > local > process. */ - Hub.prototype.getStackTop = function () { - return this._stack[this._stack.length - 1]; - }; - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - Hub.prototype.captureException = function (exception, hint) { - var eventId = (this._lastEventId = utils_1.uuid4()); - var finalHint = hint; - // If there's no explicit hint provided, mimick the same thing that would happen - // in the minimal itself to create a consistent behavior. - // We don't do this in the client, as it's the lowest level API, and doing this, - // would prevent user from having full control over direct calls. - if (!hint) { - var syntheticException = void 0; - try { - throw new Error('Sentry syntheticException'); - } - catch (exception) { - syntheticException = exception; - } - finalHint = { - originalException: exception, - syntheticException: syntheticException, - }; - } - this._invokeClient('captureException', exception, tslib_1.__assign(tslib_1.__assign({}, finalHint), { event_id: eventId })); - return eventId; - }; - /** - * @inheritDoc - */ - Hub.prototype.captureMessage = function (message, level, hint) { - var eventId = (this._lastEventId = utils_1.uuid4()); - var finalHint = hint; - // If there's no explicit hint provided, mimick the same thing that would happen - // in the minimal itself to create a consistent behavior. - // We don't do this in the client, as it's the lowest level API, and doing this, - // would prevent user from having full control over direct calls. - if (!hint) { - var syntheticException = void 0; - try { - throw new Error(message); - } - catch (exception) { - syntheticException = exception; - } - finalHint = { - originalException: message, - syntheticException: syntheticException, - }; - } - this._invokeClient('captureMessage', message, level, tslib_1.__assign(tslib_1.__assign({}, finalHint), { event_id: eventId })); - return eventId; - }; - /** - * @inheritDoc - */ - Hub.prototype.captureEvent = function (event, hint) { - var eventId = (this._lastEventId = utils_1.uuid4()); - this._invokeClient('captureEvent', event, tslib_1.__assign(tslib_1.__assign({}, hint), { event_id: eventId })); - return eventId; - }; - /** - * @inheritDoc - */ - Hub.prototype.lastEventId = function () { - return this._lastEventId; - }; - /** - * @inheritDoc - */ - Hub.prototype.addBreadcrumb = function (breadcrumb, hint) { - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - if (!scope || !client) - return; - // eslint-disable-next-line @typescript-eslint/unbound-method - var _b = (client.getOptions && client.getOptions()) || {}, _c = _b.beforeBreadcrumb, beforeBreadcrumb = _c === void 0 ? null : _c, _d = _b.maxBreadcrumbs, maxBreadcrumbs = _d === void 0 ? DEFAULT_BREADCRUMBS : _d; - if (maxBreadcrumbs <= 0) - return; - var timestamp = utils_1.dateTimestampInSeconds(); - var mergedBreadcrumb = tslib_1.__assign({ timestamp: timestamp }, breadcrumb); - var finalBreadcrumb = beforeBreadcrumb - ? utils_1.consoleSandbox(function () { return beforeBreadcrumb(mergedBreadcrumb, hint); }) - : mergedBreadcrumb; - if (finalBreadcrumb === null) - return; - scope.addBreadcrumb(finalBreadcrumb, Math.min(maxBreadcrumbs, MAX_BREADCRUMBS)); - }; - /** - * @inheritDoc - */ - Hub.prototype.setUser = function (user) { - var scope = this.getScope(); - if (scope) - scope.setUser(user); - }; - /** - * @inheritDoc - */ - Hub.prototype.setTags = function (tags) { - var scope = this.getScope(); - if (scope) - scope.setTags(tags); - }; - /** - * @inheritDoc - */ - Hub.prototype.setExtras = function (extras) { - var scope = this.getScope(); - if (scope) - scope.setExtras(extras); - }; - /** - * @inheritDoc - */ - Hub.prototype.setTag = function (key, value) { - var scope = this.getScope(); - if (scope) - scope.setTag(key, value); - }; - /** - * @inheritDoc - */ - Hub.prototype.setExtra = function (key, extra) { - var scope = this.getScope(); - if (scope) - scope.setExtra(key, extra); - }; - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Hub.prototype.setContext = function (name, context) { - var scope = this.getScope(); - if (scope) - scope.setContext(name, context); - }; - /** - * @inheritDoc - */ - Hub.prototype.configureScope = function (callback) { - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - if (scope && client) { - callback(scope); - } - }; - /** - * @inheritDoc - */ - Hub.prototype.run = function (callback) { - var oldHub = makeMain(this); - try { - callback(this); - } - finally { - makeMain(oldHub); - } - }; - /** - * @inheritDoc - */ - Hub.prototype.getIntegration = function (integration) { - var client = this.getClient(); - if (!client) - return null; - try { - return client.getIntegration(integration); - } - catch (_oO) { - utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Hub"); - return null; - } - }; - /** - * @inheritDoc - */ - Hub.prototype.startSpan = function (context) { - return this._callExtensionMethod('startSpan', context); - }; - /** - * @inheritDoc - */ - Hub.prototype.startTransaction = function (context, customSamplingContext) { - return this._callExtensionMethod('startTransaction', context, customSamplingContext); - }; - /** - * @inheritDoc - */ - Hub.prototype.traceHeaders = function () { - return this._callExtensionMethod('traceHeaders'); - }; - /** - * @inheritDoc - */ - Hub.prototype.startSession = function (context) { - // End existing session if there's one - this.endSession(); - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - var _b = (client && client.getOptions()) || {}, release = _b.release, environment = _b.environment; - var session = new session_1.Session(tslib_1.__assign(tslib_1.__assign({ release: release, - environment: environment }, (scope && { user: scope.getUser() })), context)); - if (scope) { - scope.setSession(session); - } - return session; - }; - /** - * @inheritDoc - */ - Hub.prototype.endSession = function () { - var _a = this.getStackTop(), scope = _a.scope, client = _a.client; - if (!scope) - return; - var session = scope.getSession && scope.getSession(); - if (session) { - session.close(); - if (client && client.captureSession) { - client.captureSession(session); - } - scope.setSession(); - } - }; - /** - * Internal helper function to call a method on the top client if it exists. - * - * @param method The method to call on the client. - * @param args Arguments to pass to the client function. - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Hub.prototype._invokeClient = function (method) { - var _a; - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var _b = this.getStackTop(), scope = _b.scope, client = _b.client; - if (client && client[method]) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - (_a = client)[method].apply(_a, tslib_1.__spread(args, [scope])); - } - }; - /** - * Calls global extension method and binding current instance to the function call - */ - // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Hub.prototype._callExtensionMethod = function (method) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; - } - var carrier = getMainCarrier(); - var sentry = carrier.__SENTRY__; - if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { - return sentry.extensions[method].apply(this, args); +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + // No support of ( ( “?” | “:” | “-” ) /* Followed by an ns-plain-safe(c)) */ ) part + return isPrintable(c) && c !== CHAR_BOM + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; +} + +// Simplified test for values allowed as the last character in plain style. +function isPlainSafeLast(c) { + // just not whitespace or colon, it will be checked to be plain character later + return !isWhitespace(c) && c !== CHAR_COLON; +} + +// Same as 'string'.codePointAt(pos), but works in older browsers. +function codePointAt(string, pos) { + var first = string.charCodeAt(pos), second; + if (first >= 0xD800 && first <= 0xDBFF && pos + 1 < string.length) { + second = string.charCodeAt(pos + 1); + if (second >= 0xDC00 && second <= 0xDFFF) { + // https://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae + return (first - 0xD800) * 0x400 + second - 0xDC00 + 0x10000; + } + } + return first; +} + +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} + +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; + +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, + testAmbiguousType, quotingType, forceQuotes, inblock) { + + var i; + var char = 0; + var prevChar = null; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(codePointAt(string, 0)) + && isPlainSafeLast(codePointAt(string, string.length - 1)); + + if (singleLineOnly || forceQuotes) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; } - utils_1.logger.warn("Extension method " + method + " couldn't be found, doing nothing."); - }; - return Hub; -}()); -exports.Hub = Hub; -/** Returns the global shim registry. */ -function getMainCarrier() { - var carrier = utils_1.getGlobalObject(); - carrier.__SENTRY__ = carrier.__SENTRY__ || { - extensions: {}, - hub: undefined, - }; - return carrier; + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + plain = plain && isPlainSafe(char, prevChar, inblock); + prevChar = char; + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + if (plain && !forceQuotes && !testAmbiguousType(string)) { + return STYLE_PLAIN; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + if (!forceQuotes) { + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; + } + return quotingType === QUOTING_TYPE_DOUBLE ? STYLE_DOUBLE : STYLE_SINGLE; } -exports.getMainCarrier = getMainCarrier; -/** - * Replaces the current main hub with the passed one on the global object - * - * @returns The old replaced hub - */ -function makeMain(hub) { - var registry = getMainCarrier(); - var oldHub = getHubFromCarrier(registry); - setHubOnCarrier(registry, hub); - return oldHub; + +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey, inblock) { + state.dump = (function () { + if (string.length === 0) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? '""' : "''"; + } + if (!state.noCompatMode) { + if (DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1 || DEPRECATED_BASE60_SYNTAX.test(string)) { + return state.quotingType === QUOTING_TYPE_DOUBLE ? ('"' + string + '"') : ("'" + string + "'"); + } + } + + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); + + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } + + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, + testAmbiguity, state.quotingType, state.forceQuotes && !iskey, inblock)) { + + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"'; + default: + throw new YAMLException('impossible error: invalid scalar style'); + } + }()); } -exports.makeMain = makeMain; -/** - * Returns the default hub instance. - * - * If a hub is already registered in the global carrier but this module - * contains a more recent version, it replaces the registered version. - * Otherwise, the currently registered hub will be returned. - */ -function getCurrentHub() { - // Get main carrier (global for every environment) - var registry = getMainCarrier(); - // If there's no hub, or its an old API, assign a new one - if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(exports.API_VERSION)) { - setHubOnCarrier(registry, new Hub()); + +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; + + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); + + return indentIndicator + chomp + '\n'; +} + +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; +} + +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; + + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; + + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + + return result; +} + +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; + + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; + + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 } - // Prefer domains over global if they are there (applicable only to Node environment) - if (utils_1.isNodeEnv()) { - return getHubFromActiveDomain(registry); + curr = next; + } + + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } + + return result.slice(1); // drop extra \n joiner +} + +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char = 0; + var escapeSeq; + + for (var i = 0; i < string.length; char >= 0x10000 ? i += 2 : i++) { + char = codePointAt(string, i); + escapeSeq = ESCAPE_SEQUENCES[char]; + + if (!escapeSeq && isPrintable(char)) { + result += string[i]; + if (char >= 0x10000) result += string[i + 1]; + } else { + result += escapeSeq || encodeHex(char); } - // Return hub that lives on a global object - return getHubFromCarrier(registry); + } + + return result; } -exports.getCurrentHub = getCurrentHub; -/** - * Returns the active domain, if one exists - * - * @returns The domain, or undefined if there is no active domain - */ -function getActiveDomain() { - var sentry = getMainCarrier().__SENTRY__; - return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active; + +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); + } + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level, value, false, false) || + (typeof value === 'undefined' && + writeNode(state, level, null, false, false))) { + + if (_result !== '') _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } + } + + state.tag = _tag; + state.dump = '[' + _result + ']'; } -exports.getActiveDomain = getActiveDomain; -/** - * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist - * @returns discovered hub - */ -function getHubFromActiveDomain(registry) { - try { - var activeDomain = getActiveDomain(); - // If there's no active domain, just return global hub - if (!activeDomain) { - return getHubFromCarrier(registry); - } - // If there's no hub on current domain, or it's an old API, assign a new one - if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(exports.API_VERSION)) { - var registryHubTopStack = getHubFromCarrier(registry).getStackTop(); - setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, scope_1.Scope.clone(registryHubTopStack.scope))); - } - // Return hub that lives on a domain - return getHubFromCarrier(activeDomain); + +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length, + value; + + for (index = 0, length = object.length; index < length; index += 1) { + value = object[index]; + + if (state.replacer) { + value = state.replacer.call(object, String(index), value); } - catch (_Oo) { - // Return hub that lives on a global object - return getHubFromCarrier(registry); + + // Write only valid elements, put null instead of invalid elements. + if (writeNode(state, level + 1, value, true, true, false, true) || + (typeof value === 'undefined' && + writeNode(state, level + 1, null, true, true, false, true))) { + + if (!compact || _result !== '') { + _result += generateNextLine(state, level); + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } + + _result += state.dump; } + } + + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. } -/** - * This will tell whether a carrier has a hub on it or not - * @param carrier object - */ -function hasHubOnCarrier(carrier) { - return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub); + +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + + pairBuffer = ''; + if (_result !== '') pairBuffer += ', '; + + if (state.condenseFlow) pairBuffer += '"'; + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } + + if (state.dump.length > 1024) pairBuffer += '? '; + + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); + + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = '{' + _result + '}'; } -/** - * This will create a new {@link Hub} and add to the passed object on - * __SENTRY__.hub. - * @param carrier object - * @hidden - */ -function getHubFromCarrier(carrier) { - if (carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub) - return carrier.__SENTRY__.hub; - carrier.__SENTRY__ = carrier.__SENTRY__ || {}; - carrier.__SENTRY__.hub = new Hub(); - return carrier.__SENTRY__.hub; + +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; + + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function'); + } + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + + if (!compact || _result !== '') { + pairBuffer += generateNextLine(state, level); + } + + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + + if (state.replacer) { + objectValue = state.replacer.call(object, objectKey, objectValue); + } + + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); + + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } + + pairBuffer += state.dump; + + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } + + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } + + pairBuffer += state.dump; + + // Both key and value are valid. + _result += pairBuffer; + } + + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. } -exports.getHubFromCarrier = getHubFromCarrier; -/** - * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute - * @param carrier object - * @param hub Hub - */ -function setHubOnCarrier(carrier, hub) { - if (!carrier) - return false; - carrier.__SENTRY__ = carrier.__SENTRY__ || {}; - carrier.__SENTRY__.hub = hub; - return true; + +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; + + typeList = explicit ? state.explicitTypes : state.implicitTypes; + + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; + + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { + + if (explicit) { + if (type.multi && type.representName) { + state.tag = type.representName(object); + } else { + state.tag = type.tag; + } + } else { + state.tag = '?'; + } + + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; + + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } + + state.dump = _result; + } + + return true; + } + } + + return false; } -exports.setHubOnCarrier = setHubOnCarrier; -//# sourceMappingURL=hub.js.map -/***/ }), +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey, isblockseq) { + state.tag = null; + state.dump = object; -/***/ 6393: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (!detectType(state, object, false)) { + detectType(state, object, true); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var scope_1 = __nccwpck_require__(4213); -exports.addGlobalEventProcessor = scope_1.addGlobalEventProcessor; -exports.Scope = scope_1.Scope; -var session_1 = __nccwpck_require__(12474); -exports.Session = session_1.Session; -var hub_1 = __nccwpck_require__(53536); -exports.getActiveDomain = hub_1.getActiveDomain; -exports.getCurrentHub = hub_1.getCurrentHub; -exports.getHubFromCarrier = hub_1.getHubFromCarrier; -exports.getMainCarrier = hub_1.getMainCarrier; -exports.Hub = hub_1.Hub; -exports.makeMain = hub_1.makeMain; -exports.setHubOnCarrier = hub_1.setHubOnCarrier; -//# sourceMappingURL=index.js.map + var type = _toString.call(state.dump); + var inblock = block; + var tagStr; -/***/ }), + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } -/***/ 4213: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -/** - * Holds additional event information. {@link Scope.applyToEvent} will be - * called by the client before an event will be sent. - */ -var Scope = /** @class */ (function () { - function Scope() { - /** Flag if notifiying is happening. */ - this._notifyingListeners = false; - /** Callback for client to receive scope changes. */ - this._scopeListeners = []; - /** Callback list that will be called after {@link applyToEvent}. */ - this._eventProcessors = []; - /** Array of breadcrumbs. */ - this._breadcrumbs = []; - /** User */ - this._user = {}; - /** Tags */ - this._tags = {}; - /** Extra */ - this._extra = {}; - /** Contexts */ - this._contexts = {}; + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } + + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; } - /** - * Inherit values from the parent scope. - * @param scope to clone. - */ - Scope.clone = function (scope) { - var newScope = new Scope(); - if (scope) { - newScope._breadcrumbs = tslib_1.__spread(scope._breadcrumbs); - newScope._tags = tslib_1.__assign({}, scope._tags); - newScope._extra = tslib_1.__assign({}, scope._extra); - newScope._contexts = tslib_1.__assign({}, scope._contexts); - newScope._user = scope._user; - newScope._level = scope._level; - newScope._span = scope._span; - newScope._session = scope._session; - newScope._transactionName = scope._transactionName; - newScope._fingerprint = scope._fingerprint; - newScope._eventProcessors = tslib_1.__spread(scope._eventProcessors); - } - return newScope; - }; - /** - * Add internal on change listener. Used for sub SDKs that need to store the scope. - * @hidden - */ - Scope.prototype.addScopeListener = function (callback) { - this._scopeListeners.push(callback); - }; - /** - * @inheritDoc - */ - Scope.prototype.addEventProcessor = function (callback) { - this._eventProcessors.push(callback); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setUser = function (user) { - this._user = user || {}; - if (this._session) { - this._session.update({ user: user }); - } - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.getUser = function () { - return this._user; - }; - /** - * @inheritDoc - */ - Scope.prototype.setTags = function (tags) { - this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), tags); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setTag = function (key, value) { - var _a; - this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), (_a = {}, _a[key] = value, _a)); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setExtras = function (extras) { - this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), extras); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setExtra = function (key, extra) { - var _a; - this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), (_a = {}, _a[key] = extra, _a)); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setFingerprint = function (fingerprint) { - this._fingerprint = fingerprint; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setLevel = function (level) { - this._level = level; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setTransactionName = function (name) { - this._transactionName = name; - this._notifyScopeListeners(); - return this; - }; - /** - * Can be removed in major version. - * @deprecated in favor of {@link this.setTransactionName} - */ - Scope.prototype.setTransaction = function (name) { - return this.setTransactionName(name); - }; - /** - * @inheritDoc - */ - Scope.prototype.setContext = function (key, context) { - var _a; - if (context === null) { - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete this._contexts[key]; - } - else { - this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), (_a = {}, _a[key] = context, _a)); - } - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.setSpan = function (span) { - this._span = span; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.getSpan = function () { - return this._span; - }; - /** - * @inheritDoc - */ - Scope.prototype.getTransaction = function () { - var _a, _b, _c, _d; - // often, this span will be a transaction, but it's not guaranteed to be - var span = this.getSpan(); - // try it the new way first - if ((_a = span) === null || _a === void 0 ? void 0 : _a.transaction) { - return (_b = span) === null || _b === void 0 ? void 0 : _b.transaction; - } - // fallback to the old way (known bug: this only finds transactions with sampled = true) - if ((_d = (_c = span) === null || _c === void 0 ? void 0 : _c.spanRecorder) === null || _d === void 0 ? void 0 : _d.spans[0]) { - return span.spanRecorder.spans[0]; - } - // neither way found a transaction - return undefined; - }; - /** - * @inheritDoc - */ - Scope.prototype.setSession = function (session) { - if (!session) { - delete this._session; - } - else { - this._session = session; - } - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.getSession = function () { - return this._session; - }; - /** - * @inheritDoc - */ - Scope.prototype.update = function (captureContext) { - if (!captureContext) { - return this; - } - if (typeof captureContext === 'function') { - var updatedScope = captureContext(this); - return updatedScope instanceof Scope ? updatedScope : this; - } - if (captureContext instanceof Scope) { - this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), captureContext._tags); - this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), captureContext._extra); - this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), captureContext._contexts); - if (captureContext._user && Object.keys(captureContext._user).length) { - this._user = captureContext._user; - } - if (captureContext._level) { - this._level = captureContext._level; - } - if (captureContext._fingerprint) { - this._fingerprint = captureContext._fingerprint; - } - } - else if (utils_1.isPlainObject(captureContext)) { - // eslint-disable-next-line no-param-reassign - captureContext = captureContext; - this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), captureContext.tags); - this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), captureContext.extra); - this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), captureContext.contexts); - if (captureContext.user) { - this._user = captureContext.user; - } - if (captureContext.level) { - this._level = captureContext.level; - } - if (captureContext.fingerprint) { - this._fingerprint = captureContext.fingerprint; - } - } - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.clear = function () { - this._breadcrumbs = []; - this._tags = {}; - this._extra = {}; - this._user = {}; - this._contexts = {}; - this._level = undefined; - this._transactionName = undefined; - this._fingerprint = undefined; - this._span = undefined; - this._session = undefined; - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.addBreadcrumb = function (breadcrumb, maxBreadcrumbs) { - var mergedBreadcrumb = tslib_1.__assign({ timestamp: utils_1.dateTimestampInSeconds() }, breadcrumb); - this._breadcrumbs = - maxBreadcrumbs !== undefined && maxBreadcrumbs >= 0 - ? tslib_1.__spread(this._breadcrumbs, [mergedBreadcrumb]).slice(-maxBreadcrumbs) - : tslib_1.__spread(this._breadcrumbs, [mergedBreadcrumb]); - this._notifyScopeListeners(); - return this; - }; - /** - * @inheritDoc - */ - Scope.prototype.clearBreadcrumbs = function () { - this._breadcrumbs = []; - this._notifyScopeListeners(); - return this; - }; - /** - * Applies the current context and fingerprint to the event. - * Note that breadcrumbs will be added by the client. - * Also if the event has already breadcrumbs on it, we do not merge them. - * @param event Event - * @param hint May contain additional informartion about the original exception. - * @hidden - */ - Scope.prototype.applyToEvent = function (event, hint) { - var _a; - if (this._extra && Object.keys(this._extra).length) { - event.extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), event.extra); - } - if (this._tags && Object.keys(this._tags).length) { - event.tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), event.tags); - } - if (this._user && Object.keys(this._user).length) { - event.user = tslib_1.__assign(tslib_1.__assign({}, this._user), event.user); - } - if (this._contexts && Object.keys(this._contexts).length) { - event.contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), event.contexts); + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; } - if (this._level) { - event.level = this._level; + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } - if (this._transactionName) { - event.transaction = this._transactionName; + } + } else if (type === '[object Array]') { + if (block && (state.dump.length !== 0)) { + if (state.noArrayIndent && !isblockseq && level > 0) { + writeBlockSequence(state, level - 1, state.dump, compact); + } else { + writeBlockSequence(state, level, state.dump, compact); } - // We want to set the trace context for normal events only if there isn't already - // a trace context on the event. There is a product feature in place where we link - // errors with transaction and it relys on that. - if (this._span) { - event.contexts = tslib_1.__assign({ trace: this._span.getTraceContext() }, event.contexts); - var transactionName = (_a = this._span.transaction) === null || _a === void 0 ? void 0 : _a.name; - if (transactionName) { - event.tags = tslib_1.__assign({ transaction: transactionName }, event.tags); - } + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; } - this._applyFingerprint(event); - event.breadcrumbs = tslib_1.__spread((event.breadcrumbs || []), this._breadcrumbs); - event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined; - return this._notifyEventProcessors(tslib_1.__spread(getGlobalEventProcessors(), this._eventProcessors), event, hint); - }; - /** - * This will be called after {@link applyToEvent} is finished. - */ - Scope.prototype._notifyEventProcessors = function (processors, event, hint, index) { - var _this = this; - if (index === void 0) { index = 0; } - return new utils_1.SyncPromise(function (resolve, reject) { - var processor = processors[index]; - if (event === null || typeof processor !== 'function') { - resolve(event); - } - else { - var result = processor(tslib_1.__assign({}, event), hint); - if (utils_1.isThenable(result)) { - result - .then(function (final) { return _this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve); }) - .then(null, reject); - } - else { - _this._notifyEventProcessors(processors, result, hint, index + 1) - .then(resolve) - .then(null, reject); - } - } - }); - }; - /** - * This will be called on every set call. - */ - Scope.prototype._notifyScopeListeners = function () { - var _this = this; - // We need this check for this._notifyingListeners to be able to work on scope during updates - // If this check is not here we'll produce endless recursion when something is done with the scope - // during the callback. - if (!this._notifyingListeners) { - this._notifyingListeners = true; - this._scopeListeners.forEach(function (callback) { - callback(_this); - }); - this._notifyingListeners = false; + } else { + writeFlowSequence(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; } - }; - /** - * Applies fingerprint from the scope to the event if there's one, - * uses message if there's one instead or get rid of empty fingerprint - */ - Scope.prototype._applyFingerprint = function (event) { - // Make sure it's an array first and we actually have something in place - event.fingerprint = event.fingerprint - ? Array.isArray(event.fingerprint) - ? event.fingerprint - : [event.fingerprint] - : []; - // If we have something on the scope, then merge it with event - if (this._fingerprint) { - event.fingerprint = event.fingerprint.concat(this._fingerprint); + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey, inblock); + } + } else if (type === '[object Undefined]') { + return false; + } else { + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + // Need to encode all characters except those allowed by the spec: + // + // [35] ns-dec-digit ::= [#x30-#x39] /* 0-9 */ + // [36] ns-hex-digit ::= ns-dec-digit + // | [#x41-#x46] /* A-F */ | [#x61-#x66] /* a-f */ + // [37] ns-ascii-letter ::= [#x41-#x5A] /* A-Z */ | [#x61-#x7A] /* a-z */ + // [38] ns-word-char ::= ns-dec-digit | ns-ascii-letter | “-” + // [39] ns-uri-char ::= “%” ns-hex-digit ns-hex-digit | ns-word-char | “#” + // | “;” | “/” | “?” | “:” | “@” | “&” | “=” | “+” | “$” | “,” + // | “_” | “.” | “!” | “~” | “*” | “'” | “(” | “)” | “[” | “]” + // + // Also need to encode '!' because it has special meaning (end of tag prefix). + // + tagStr = encodeURI( + state.tag[0] === '!' ? state.tag.slice(1) : state.tag + ).replace(/!/g, '%21'); + + if (state.tag[0] === '!') { + tagStr = '!' + tagStr; + } else if (tagStr.slice(0, 18) === 'tag:yaml.org,2002:') { + tagStr = '!!' + tagStr.slice(18); + } else { + tagStr = '!<' + tagStr + '>'; + } + + state.dump = tagStr + ' ' + state.dump; + } + } + + return true; +} + +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; + + inspectNode(object, objects, duplicatesIndexes); + + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} + +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; + + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); + } + } else { + objects.push(object); + + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); } - // If we have no data at all, remove empty array default - if (event.fingerprint && !event.fingerprint.length) { - delete event.fingerprint; + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); } - }; - return Scope; -}()); -exports.Scope = Scope; -/** - * Retruns the global event processors. - */ -function getGlobalEventProcessors() { - /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */ - var global = utils_1.getGlobalObject(); - global.__SENTRY__ = global.__SENTRY__ || {}; - global.__SENTRY__.globalEventProcessors = global.__SENTRY__.globalEventProcessors || []; - return global.__SENTRY__.globalEventProcessors; - /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */ + } + } + } } -/** - * Add a EventProcessor to be kept globally. - * @param callback EventProcessor to add - */ -function addGlobalEventProcessor(callback) { - getGlobalEventProcessors().push(callback); + +function dump(input, options) { + options = options || {}; + + var state = new State(options); + + if (!state.noRefs) getDuplicateReferences(input, state); + + var value = input; + + if (state.replacer) { + value = state.replacer.call({ '': value }, '', value); + } + + if (writeNode(state, 0, value, true, true)) return state.dump + '\n'; + + return ''; } -exports.addGlobalEventProcessor = addGlobalEventProcessor; -//# sourceMappingURL=scope.js.map + +module.exports.dump = dump; + /***/ }), -/***/ 12474: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 30780: +/***/ ((module) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -/** - * @inheritdoc - */ -var Session = /** @class */ (function () { - function Session(context) { - this.errors = 0; - this.sid = utils_1.uuid4(); - this.timestamp = Date.now(); - this.started = Date.now(); - this.duration = 0; - this.status = types_1.SessionStatus.Ok; - if (context) { - this.update(context); - } +"use strict"; +// YAML error class. http://stackoverflow.com/questions/8458984 +// + + + +function formatError(exception, compact) { + var where = '', message = exception.reason || '(unknown reason)'; + + if (!exception.mark) return message; + + if (exception.mark.name) { + where += 'in "' + exception.mark.name + '" '; + } + + where += '(' + (exception.mark.line + 1) + ':' + (exception.mark.column + 1) + ')'; + + if (!compact && exception.mark.snippet) { + where += '\n\n' + exception.mark.snippet; + } + + return message + ' ' + where; +} + + +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); + + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = formatError(this, false); + + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} + + +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; + + +YAMLException.prototype.toString = function toString(compact) { + return this.name + ': ' + formatError(this, compact); +}; + + +module.exports = YAMLException; + + +/***/ }), + +/***/ 26106: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +/*eslint-disable max-len,no-use-before-define*/ + +var common = __nccwpck_require__(44828); +var YAMLException = __nccwpck_require__(30780); +var makeSnippet = __nccwpck_require__(68947); +var DEFAULT_SCHEMA = __nccwpck_require__(77599); + + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + + +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; + + +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; + + +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; + + +function _class(obj) { return Object.prototype.toString.call(obj); } + +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} + +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} + +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} + +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} + +function fromHexCode(c) { + var lc; + + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + /*eslint-disable no-bitwise*/ + lc = c | 0x20; + + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } + + return -1; +} + +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} + +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } + + return -1; +} + +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} + +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} + +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} + + +function State(input, options) { + this.input = input; + + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_SCHEMA; + this.onWarning = options['onWarning'] || null; + // (Hidden) Remove? makes the loader to expect YAML 1.1 documents + // if such documents have no explicit %YAML directive + this.legacy = options['legacy'] || false; + + this.json = options['json'] || false; + this.listener = options['listener'] || null; + + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; + + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; + + // position of first leading tab in the current line, + // used to make sure there are no tabs in the indentation + this.firstTabInLine = -1; + + this.documents = []; + + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ + +} + + +function generateError(state, message) { + var mark = { + name: state.filename, + buffer: state.input.slice(0, -1), // omit trailing \0 + position: state.position, + line: state.line, + column: state.position - state.lineStart + }; + + mark.snippet = makeSnippet(mark); + + return new YAMLException(message, mark); +} + +function throwError(state, message) { + throw generateError(state, message); +} + +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} + + +var directiveHandlers = { + + YAML: function handleYamlDirective(state, name, args) { + + var match, major, minor; + + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); } - /** JSDoc */ - // eslint-disable-next-line complexity - Session.prototype.update = function (context) { - if (context === void 0) { context = {}; } - if (context.user) { - if (context.user.ip_address) { - this.ipAddress = context.user.ip_address; - } - if (!context.did) { - this.did = context.user.id || context.user.email || context.user.username; - } - } - this.timestamp = context.timestamp || Date.now(); - if (context.sid) { - // Good enough uuid validation. — Kamil - this.sid = context.sid.length === 32 ? context.sid : utils_1.uuid4(); - } - if (context.did) { - this.did = "" + context.did; - } - if (typeof context.started === 'number') { - this.started = context.started; - } - if (typeof context.duration === 'number') { - this.duration = context.duration; - } - else { - this.duration = this.timestamp - this.started; - } - if (context.release) { - this.release = context.release; - } - if (context.environment) { - this.environment = context.environment; - } - if (context.ipAddress) { - this.ipAddress = context.ipAddress; - } - if (context.userAgent) { - this.userAgent = context.userAgent; - } - if (typeof context.errors === 'number') { - this.errors = context.errors; - } - if (context.status) { - this.status = context.status; - } - }; - /** JSDoc */ - Session.prototype.close = function (status) { - if (status) { - this.update({ status: status }); - } - else if (this.status === types_1.SessionStatus.Ok) { - this.update({ status: types_1.SessionStatus.Exited }); - } - else { - this.update(); + + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } + + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); + + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } + + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); + + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } + + state.version = args[0]; + state.checkLineBreaks = (minor < 2); + + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, + + TAG: function handleTagDirective(state, name, args) { + + var handle, prefix; + + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } + + handle = args[0]; + prefix = args[1]; + + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } + + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } + + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + try { + prefix = decodeURIComponent(prefix); + } catch (err) { + throwError(state, 'tag prefix is malformed: ' + prefix); + } + + state.tagMap[handle] = prefix; + } +}; + + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); } - }; - /** JSDoc */ - Session.prototype.toJSON = function () { - return utils_1.dropUndefinedKeys({ - sid: "" + this.sid, - init: true, - started: new Date(this.started).toISOString(), - timestamp: new Date(this.timestamp).toISOString(), - status: this.status, - errors: this.errors, - did: typeof this.did === 'number' || typeof this.did === 'string' ? "" + this.did : undefined, - duration: this.duration, - attrs: utils_1.dropUndefinedKeys({ - release: this.release, - environment: this.environment, - ip_address: this.ipAddress, - user_agent: this.userAgent, - }), - }); - }; - return Session; -}()); -exports.Session = Session; -//# sourceMappingURL=session.js.map + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); + } + + state.result += _result; + } +} + +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; + + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); + } + + sourceKeys = Object.keys(source); + + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } + } +} + +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, + startLine, startLineStart, startPos) { + + var index, quantity; + + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); + + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } + + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } + } + } + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; + } -/***/ }), -/***/ 88455: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + keyNode = String(keyNode); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var hub_1 = __nccwpck_require__(6393); -/** - * This calls a function on the current hub. - * @param method function to call on hub. - * @param args to pass to function. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function callOnHub(method) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; + if (_result === null) { + _result = {}; + } + + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); } - var hub = hub_1.getCurrentHub(); - if (hub && hub[method]) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return hub[method].apply(hub, tslib_1.__spread(args)); + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line; + state.lineStart = startLineStart || state.lineStart; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); } - throw new Error("No hub defined or " + method + " was not found on the hub, please open a bug report."); -} -/** - * Captures an exception event and sends it to Sentry. - * - * @param exception An exception-like object. - * @returns The generated eventId. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types -function captureException(exception, captureContext) { - var syntheticException; - try { - throw new Error('Sentry syntheticException'); + + // used for this specific key only because Object.defineProperty is slow + if (keyNode === '__proto__') { + Object.defineProperty(_result, keyNode, { + configurable: true, + enumerable: true, + writable: true, + value: valueNode + }); + } else { + _result[keyNode] = valueNode; } - catch (exception) { - syntheticException = exception; + delete overridableKeys[keyNode]; + } + + return _result; +} + +function readLineBreak(state) { + var ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; } - return callOnHub('captureException', exception, { - captureContext: captureContext, - originalException: exception, - syntheticException: syntheticException, - }); + } else { + throwError(state, 'a line break is expected'); + } + + state.line += 1; + state.lineStart = state.position; + state.firstTabInLine = -1; } -exports.captureException = captureException; -/** - * Captures a message event and sends it to Sentry. - * - * @param message The message to send to Sentry. - * @param level Define the level of the message. - * @returns The generated eventId. - */ -function captureMessage(message, captureContext) { - var syntheticException; - try { - throw new Error(message); + +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + if (ch === 0x09/* Tab */ && state.firstTabInLine === -1) { + state.firstTabInLine = state.position; + } + ch = state.input.charCodeAt(++state.position); } - catch (exception) { - syntheticException = exception; + + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); } - // This is necessary to provide explicit scopes upgrade, without changing the original - // arity of the `captureMessage(message, level)` method. - var level = typeof captureContext === 'string' ? captureContext : undefined; - var context = typeof captureContext !== 'string' ? { captureContext: captureContext } : undefined; - return callOnHub('captureMessage', message, level, tslib_1.__assign({ originalException: message, syntheticException: syntheticException }, context)); -} -exports.captureMessage = captureMessage; -/** - * Captures a manually created event and sends it to Sentry. - * - * @param event The event to send to Sentry. - * @returns The generated eventId. - */ -function captureEvent(event) { - return callOnHub('captureEvent', event); -} -exports.captureEvent = captureEvent; -/** - * Callback to set context information onto the scope. - * @param callback Callback function that receives Scope. - */ -function configureScope(callback) { - callOnHub('configureScope', callback); -} -exports.configureScope = configureScope; -/** - * Records a new breadcrumb which will be attached to future events. - * - * Breadcrumbs will be added to subsequent events to provide more context on - * user's actions prior to an error or crash. - * - * @param breadcrumb The breadcrumb to record. - */ -function addBreadcrumb(breadcrumb) { - callOnHub('addBreadcrumb', breadcrumb); -} -exports.addBreadcrumb = addBreadcrumb; -/** - * Sets context data with the given name. - * @param name of the context - * @param context Any kind of data. This data will be normalized. - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setContext(name, context) { - callOnHub('setContext', name, context); -} -exports.setContext = setContext; -/** - * Set an object that will be merged sent as extra data with the event. - * @param extras Extras object to merge into current context. - */ -function setExtras(extras) { - callOnHub('setExtras', extras); -} -exports.setExtras = setExtras; -/** - * Set an object that will be merged sent as tags data with the event. - * @param tags Tags context object to merge into current context. - */ -function setTags(tags) { - callOnHub('setTags', tags); + + if (is_EOL(ch)) { + readLineBreak(state); + + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); + } + } else { + break; + } + } + + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); + } + + return lineBreaks; } -exports.setTags = setTags; -/** - * Set key:value that will be sent as extra data with the event. - * @param key String of extra - * @param extra Any kind of data. This data will be normalized. - */ -function setExtra(key, extra) { - callOnHub('setExtra', key, extra); + +function testDocumentSeparator(state) { + var _position = state.position, + ch; + + ch = state.input.charCodeAt(_position); + + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } + } + + return false; } -exports.setExtra = setExtra; -/** - * Set key:value that will be sent as tags data with the event. - * - * Can also be used to unset a tag, by passing `undefined`. - * - * @param key String key of tag - * @param value Value of tag - */ -function setTag(key, value) { - callOnHub('setTag', key, value); + +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); + } } -exports.setTag = setTag; -/** - * Updates user context information for future events. - * - * @param user User context object to be set in the current context. Pass `null` to unset the user. - */ -function setUser(user) { - callOnHub('setUser', user); + + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; + } + + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } + + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; + } + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; + } + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; + } else { + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; + } + } + + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } + + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); + } + + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; + } + + state.kind = _kind; + state.result = _result; + return false; } -exports.setUser = setUser; -/** - * Creates a new scope with and executes the given operation within. - * The scope is automatically removed once the operation - * finishes or throws. - * - * This is essentially a convenience function for: - * - * pushScope(); - * callback(); - * popScope(); - * - * @param callback that will be enclosed into push/popScope. - */ -function withScope(callback) { - callOnHub('withScope', callback); + +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; + } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); } -exports.withScope = withScope; -/** - * Calls a function on the latest client. Use this with caution, it's meant as - * in "internal" helper so we don't need to expose every possible function in - * the shim. It is not guaranteed that the client actually implements the - * function. - * - * @param method The method to call on the client/client. - * @param args Arguments to pass to the client/fontend. - * @hidden - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function _callOnClient(method) { - var args = []; - for (var _i = 1; _i < arguments.length; _i++) { - args[_i - 1] = arguments[_i]; + +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x22/* " */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; + + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); + + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; + + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; + + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); + + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; + + } else { + throwError(state, 'expected hexadecimal character'); + } + } + + state.result += charFromCodepoint(hexResult); + + state.position++; + + } else { + throwError(state, 'unknown escape sequence'); + } + + captureStart = captureEnd = state.position; + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; } - callOnHub.apply(void 0, tslib_1.__spread(['_invokeClient', method], args)); -} -exports._callOnClient = _callOnClient; -/** - * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation. - * - * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a - * new child span within the transaction or any span, call the respective `.startChild()` method. - * - * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded. - * - * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its - * finished child spans will be sent to Sentry. - * - * @param context Properties of the new `Transaction`. - * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent - * default values). See {@link Options.tracesSampler}. - * - * @returns The transaction which was just started - */ -function startTransaction(context, customSamplingContext) { - return callOnHub('startTransaction', tslib_1.__assign({}, context), customSamplingContext); + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); } -exports.startTransaction = startTransaction; -//# sourceMappingURL=index.js.map -/***/ }), +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _lineStart, + _pos, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = Object.create(null), + keyNode, + keyTag, + valueNode, + ch; -/***/ 40508: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + ch = state.input.charCodeAt(state.position); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var parsers_1 = __nccwpck_require__(19090); -var transports_1 = __nccwpck_require__(21437); -/** - * The Sentry Node SDK Backend. - * @hidden - */ -var NodeBackend = /** @class */ (function (_super) { - tslib_1.__extends(NodeBackend, _super); - function NodeBackend() { - return _super !== null && _super.apply(this, arguments) || this; - } - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - NodeBackend.prototype.eventFromException = function (exception, hint) { - var _this = this; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var ex = exception; - var mechanism = { - handled: true, - type: 'generic', - }; - if (!utils_1.isError(exception)) { - if (utils_1.isPlainObject(exception)) { - // This will allow us to group events based on top-level keys - // which is much better than creating new group when any key/value change - var message = "Non-Error exception captured with keys: " + utils_1.extractExceptionKeysForMessage(exception); - core_1.getCurrentHub().configureScope(function (scope) { - scope.setExtra('__serialized__', utils_1.normalizeToSize(exception)); - }); - ex = (hint && hint.syntheticException) || new Error(message); - ex.message = message; - } - else { - // This handles when someone does: `throw "something awesome";` - // We use synthesized Error here so we can extract a (rough) stack trace. - ex = (hint && hint.syntheticException) || new Error(exception); - ex.message = exception; - } - mechanism.synthetic = true; - } - return new utils_1.SyncPromise(function (resolve, reject) { - return parsers_1.parseError(ex, _this._options) - .then(function (event) { - utils_1.addExceptionTypeValue(event, undefined, undefined); - utils_1.addExceptionMechanism(event, mechanism); - resolve(tslib_1.__assign(tslib_1.__assign({}, event), { event_id: hint && hint.event_id })); - }) - .then(null, reject); - }); - }; - /** - * @inheritDoc - */ - NodeBackend.prototype.eventFromMessage = function (message, level, hint) { - var _this = this; - if (level === void 0) { level = types_1.Severity.Info; } - var event = { - event_id: hint && hint.event_id, - level: level, - message: message, - }; - return new utils_1.SyncPromise(function (resolve) { - if (_this._options.attachStacktrace && hint && hint.syntheticException) { - var stack = hint.syntheticException ? parsers_1.extractStackFromError(hint.syntheticException) : []; - parsers_1.parseStack(stack, _this._options) - .then(function (frames) { - event.stacktrace = { - frames: parsers_1.prepareFramesForEvent(frames), - }; - resolve(event); - }) - .then(null, function () { - resolve(event); - }); - } - else { - resolve(event); - } - }); - }; - /** - * @inheritDoc - */ - NodeBackend.prototype._setupTransport = function () { - if (!this._options.dsn) { - // We return the noop transport here in case there is no Dsn. - return _super.prototype._setupTransport.call(this); - } - var dsn = new utils_1.Dsn(this._options.dsn); - var transportOptions = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, this._options.transportOptions), (this._options.httpProxy && { httpProxy: this._options.httpProxy })), (this._options.httpsProxy && { httpsProxy: this._options.httpsProxy })), (this._options.caCerts && { caCerts: this._options.caCerts })), { dsn: this._options.dsn }); - if (this._options.transport) { - return new this._options.transport(transportOptions); - } - if (dsn.protocol === 'http') { - return new transports_1.HTTPTransport(transportOptions); - } - return new transports_1.HTTPSTransport(transportOptions); - }; - return NodeBackend; -}(core_1.BaseBackend)); -exports.NodeBackend = NodeBackend; -//# sourceMappingURL=backend.js.map + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } -/***/ }), + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } -/***/ 86147: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + ch = state.input.charCodeAt(++state.position); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var backend_1 = __nccwpck_require__(40508); -var version_1 = __nccwpck_require__(31271); -/** - * The Sentry Node SDK Client. - * - * @see NodeOptions for documentation on configuration options. - * @see SentryClient for usage documentation. - */ -var NodeClient = /** @class */ (function (_super) { - tslib_1.__extends(NodeClient, _super); - /** - * Creates a new Node SDK instance. - * @param options Configuration options for this SDK. - */ - function NodeClient(options) { - return _super.call(this, backend_1.NodeBackend, options) || this; + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } else if (ch === 0x2C/* , */) { + // "flow collection entries can never be completely empty", as per YAML 1.2, section 7.4 + throwError(state, "expected the node content, but found ','"); } - /** - * @inheritDoc - */ - NodeClient.prototype._prepareEvent = function (event, scope, hint) { - event.platform = event.platform || 'node'; - event.sdk = tslib_1.__assign(tslib_1.__assign({}, event.sdk), { name: version_1.SDK_NAME, packages: tslib_1.__spread(((event.sdk && event.sdk.packages) || []), [ - { - name: 'npm:@sentry/node', - version: version_1.SDK_VERSION, - }, - ]), version: version_1.SDK_VERSION }); - if (this.getOptions().serverName) { - event.server_name = this.getOptions().serverName; - } - return _super.prototype._prepareEvent.call(this, event, scope, hint); - }; - return NodeClient; -}(core_1.BaseClient)); -exports.NodeClient = NodeClient; -//# sourceMappingURL=client.js.map -/***/ }), + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; -/***/ 45400: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -/* eslint-disable max-lines */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -var core_1 = __nccwpck_require__(79212); -var tracing_1 = __nccwpck_require__(64358); -var utils_1 = __nccwpck_require__(1620); -var domain = __nccwpck_require__(85229); -var os = __nccwpck_require__(12087); -var sdk_1 = __nccwpck_require__(38836); -var DEFAULT_SHUTDOWN_TIMEOUT = 2000; -/** - * Express-compatible tracing handler. - * @see Exposed as `Handlers.tracingHandler` - */ -function tracingHandler() { - return function sentryTracingMiddleware(req, res, next) { - // If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision) - var traceparentData; - if (req.headers && utils_1.isString(req.headers['sentry-trace'])) { - traceparentData = tracing_1.extractTraceparentData(req.headers['sentry-trace']); - } - var transaction = core_1.startTransaction(tslib_1.__assign({ name: extractExpressTransactionName(req, { path: true, method: true }), op: 'http.server' }, traceparentData)); - // We put the transaction on the scope so users can attach children to it - core_1.getCurrentHub().configureScope(function (scope) { - scope.setSpan(transaction); - }); - // We also set __sentry_transaction on the response so people can grab the transaction there to add - // spans to it later. - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - res.__sentry_transaction = transaction; - res.once('finish', function () { - // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction - // closes - setImmediate(function () { - addExpressReqToTransaction(transaction, req); - transaction.setHttpStatus(res.statusCode); - transaction.finish(); - }); - }); - next(); - }; -} -exports.tracingHandler = tracingHandler; -/** - * Set parameterized as transaction name e.g.: `GET /users/:id` - * Also adds more context data on the transaction from the request - */ -function addExpressReqToTransaction(transaction, req) { - if (!transaction) - return; - transaction.name = extractExpressTransactionName(req, { path: true, method: true }); - transaction.setData('url', req.originalUrl); - transaction.setData('baseUrl', req.baseUrl); - transaction.setData('query', req.query); -} -/** - * Extracts complete generalized path from the request object and uses it to construct transaction name. - * - * eg. GET /mountpoint/user/:id - * - * @param req The ExpressRequest object - * @param options What to include in the transaction name (method, path, or both) - * - * @returns The fully constructed transaction name - */ -function extractExpressTransactionName(req, options) { - if (options === void 0) { options = {}; } - var _a; - var method = (_a = req.method) === null || _a === void 0 ? void 0 : _a.toUpperCase(); - var path = ''; - if (req.route) { - // if the mountpoint is `/`, req.baseUrl is '' (not undefined), so it's safe to include it here - // see https://github.com/expressjs/express/blob/508936853a6e311099c9985d4c11a4b1b8f6af07/test/req.baseUrl.js#L7 - path = "" + req.baseUrl + req.route.path; - } - else if (req.originalUrl || req.url) { - path = utils_1.stripUrlQueryAndFragment(req.originalUrl || req.url || ''); + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } } - var info = ''; - if (options.method && method) { - info += method; + + _line = state.line; // Save the current line. + _lineStart = state.lineStart; + _pos = state.position; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; } - if (options.method && options.path) { - info += " "; + + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode, _line, _lineStart, _pos)); + } else { + _result.push(keyNode); } - if (options.path && path) { - info += path; + + skipSeparationSpace(state, true, nodeIndent); + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; } - return info; + } + + throwError(state, 'unexpected end of the stream within a flow collection'); } -/** JSDoc */ -function extractTransaction(req, type) { - var _a; - switch (type) { - case 'path': { - return extractExpressTransactionName(req, { path: true }); - } - case 'handler': { - return ((_a = req.route) === null || _a === void 0 ? void 0 : _a.stack[0].name) || ''; - } - case 'methodPath': - default: { - return extractExpressTransactionName(req, { path: true, method: true }); - } + +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } + + } else { + break; } -} -/** Default user keys that'll be used to extract data from the request */ -var DEFAULT_USER_KEYS = ['id', 'username', 'email']; -/** JSDoc */ -function extractUserData(user, keys) { - var extractedUser = {}; - var attributes = Array.isArray(keys) ? keys : DEFAULT_USER_KEYS; - attributes.forEach(function (key) { - if (user && key in user) { - extractedUser[key] = user[key]; - } - }); - return extractedUser; -} -/** - * Enriches passed event with request data. - * - * @param event Will be mutated and enriched with req data - * @param req Request object - * @param options object containing flags to enable functionality - * @hidden - */ -function parseRequest(event, req, options) { - // eslint-disable-next-line no-param-reassign - options = tslib_1.__assign({ ip: false, request: true, serverName: true, transaction: true, user: true, version: true }, options); - if (options.version) { - event.contexts = tslib_1.__assign(tslib_1.__assign({}, event.contexts), { runtime: { - name: 'node', - version: global.process.version, - } }); + } + + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); } - if (options.request) { - // if the option value is `true`, use the default set of keys by not passing anything to `extractNodeRequestData()` - var extractedRequestData = Array.isArray(options.request) - ? utils_1.extractNodeRequestData(req, options.request) - : utils_1.extractNodeRequestData(req); - event.request = tslib_1.__assign(tslib_1.__assign({}, event.request), extractedRequestData); + } + + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; + + ch = state.input.charCodeAt(state.position); + + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); } - if (options.serverName && !event.server_name) { - event.server_name = global.process.env.SENTRY_NAME || os.hostname(); + + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; } - if (options.user) { - var extractedUser = req.user && utils_1.isPlainObject(req.user) ? extractUserData(req.user, options.user) : {}; - if (Object.keys(extractedUser)) { - event.user = tslib_1.__assign(tslib_1.__assign({}, event.user), extractedUser); + + if (is_EOL(ch)) { + emptyLines++; + continue; + } + + // End of the scalar. + if (state.lineIndent < textIndent) { + + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; } + } + + // Break this `while` cycle and go to the funciton's epilogue. + break; } - // client ip: - // node: req.connection.remoteAddress - // express, koa: req.ip - if (options.ip) { - var ip = req.ip || (req.connection && req.connection.remoteAddress); - if (ip) { - event.user = tslib_1.__assign(tslib_1.__assign({}, event.user), { ip_address: ip }); + + // Folded style: use fancy rules to handle line breaks. + if (folding) { + + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); + + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; } + + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } + + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } - if (options.transaction && !event.transaction) { - event.transaction = extractTransaction(req, options.transaction); + + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; + + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); } - return event; -} -exports.parseRequest = parseRequest; -/** - * Express compatible request handler. - * @see Exposed as `Handlers.requestHandler` - */ -function requestHandler(options) { - return function sentryRequestMiddleware(req, res, next) { - if (options && options.flushTimeout && options.flushTimeout > 0) { - // eslint-disable-next-line @typescript-eslint/unbound-method - var _end_1 = res.end; - res.end = function (chunk, encoding, cb) { - var _this = this; - sdk_1.flush(options.flushTimeout) - .then(function () { - _end_1.call(_this, chunk, encoding, cb); - }) - .then(null, function (e) { - utils_1.logger.error(e); - }); - }; - } - var local = domain.create(); - local.add(req); - local.add(res); - local.on('error', next); - local.run(function () { - core_1.getCurrentHub().configureScope(function (scope) { - return scope.addEventProcessor(function (event) { return parseRequest(event, req, options); }); - }); - next(); - }); - }; -} -exports.requestHandler = requestHandler; -/** JSDoc */ -function getStatusCodeFromResponse(error) { - var statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode); - return statusCode ? parseInt(statusCode, 10) : 500; -} -/** Returns true if response code is internal server error */ -function defaultShouldHandleError(error) { - var status = getStatusCodeFromResponse(error); - return status >= 500; -} -/** - * Express compatible error handler. - * @see Exposed as `Handlers.errorHandler` - */ -function errorHandler(options) { - return function sentryErrorMiddleware(error, _req, res, next) { - // eslint-disable-next-line @typescript-eslint/unbound-method - var shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError; - if (shouldHandleError(error)) { - core_1.withScope(function (_scope) { - // For some reason we need to set the transaction on the scope again - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - var transaction = res.__sentry_transaction; - if (transaction && _scope.getSpan() === undefined) { - _scope.setSpan(transaction); - } - var eventId = core_1.captureException(error); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - res.sentry = eventId; - next(error); - }); - return; - } - next(error); - }; + + captureSegment(state, captureStart, state.position, false); + } + + return true; } -exports.errorHandler = errorHandler; -/** - * @hidden - */ -function logAndExitProcess(error) { - // eslint-disable-next-line no-console - console.error(error && error.stack ? error.stack : error); - var client = core_1.getCurrentHub().getClient(); - if (client === undefined) { - utils_1.logger.warn('No NodeClient was defined, we are exiting the process now.'); - global.process.exit(1); - return; + +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); } - var options = client.getOptions(); - var timeout = (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) || - DEFAULT_SHUTDOWN_TIMEOUT; - utils_1.forget(client.close(timeout).then(function (result) { - if (!result) { - utils_1.logger.warn('We reached the timeout for emptying the request buffer, still exiting now!'); - } - global.process.exit(1); - })); -} -exports.logAndExitProcess = logAndExitProcess; -//# sourceMappingURL=handlers.js.map -/***/ }), + if (ch !== 0x2D/* - */) { + break; + } -/***/ 22783: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + following = state.input.charCodeAt(state.position + 1); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var types_1 = __nccwpck_require__(83789); -exports.Severity = types_1.Severity; -exports.Status = types_1.Status; -var core_1 = __nccwpck_require__(79212); -exports.addGlobalEventProcessor = core_1.addGlobalEventProcessor; -exports.addBreadcrumb = core_1.addBreadcrumb; -exports.captureException = core_1.captureException; -exports.captureEvent = core_1.captureEvent; -exports.captureMessage = core_1.captureMessage; -exports.configureScope = core_1.configureScope; -exports.getHubFromCarrier = core_1.getHubFromCarrier; -exports.getCurrentHub = core_1.getCurrentHub; -exports.Hub = core_1.Hub; -exports.makeMain = core_1.makeMain; -exports.Scope = core_1.Scope; -exports.startTransaction = core_1.startTransaction; -exports.setContext = core_1.setContext; -exports.setExtra = core_1.setExtra; -exports.setExtras = core_1.setExtras; -exports.setTag = core_1.setTag; -exports.setTags = core_1.setTags; -exports.setUser = core_1.setUser; -exports.withScope = core_1.withScope; -var backend_1 = __nccwpck_require__(40508); -exports.NodeBackend = backend_1.NodeBackend; -var client_1 = __nccwpck_require__(86147); -exports.NodeClient = client_1.NodeClient; -var sdk_1 = __nccwpck_require__(38836); -exports.defaultIntegrations = sdk_1.defaultIntegrations; -exports.init = sdk_1.init; -exports.lastEventId = sdk_1.lastEventId; -exports.flush = sdk_1.flush; -exports.close = sdk_1.close; -var version_1 = __nccwpck_require__(31271); -exports.SDK_NAME = version_1.SDK_NAME; -exports.SDK_VERSION = version_1.SDK_VERSION; -var core_2 = __nccwpck_require__(79212); -var hub_1 = __nccwpck_require__(6393); -var domain = __nccwpck_require__(85229); -var Handlers = __nccwpck_require__(45400); -exports.Handlers = Handlers; -var NodeIntegrations = __nccwpck_require__(72310); -var Transports = __nccwpck_require__(21437); -exports.Transports = Transports; -var INTEGRATIONS = tslib_1.__assign(tslib_1.__assign({}, core_2.Integrations), NodeIntegrations); -exports.Integrations = INTEGRATIONS; -// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like -// @sentry/hub. If we don't do this, browser bundlers will have troubles resolving `require('domain')`. -var carrier = hub_1.getMainCarrier(); -if (carrier.__SENTRY__) { - carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; - carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain; -} -//# sourceMappingURL=index.js.map + if (!is_WS_OR_EOL(following)) { + break; + } -/***/ }), + detected = true; + state.position++; -/***/ 29552: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var util = __nccwpck_require__(31669); -/** Console module integration */ -var Console = /** @class */ (function () { - function Console() { - /** - * @inheritDoc - */ - this.name = Console.id; + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; } - /** - * @inheritDoc - */ - Console.prototype.setupOnce = function () { - var e_1, _a; - var consoleModule = __nccwpck_require__(57082); - try { - for (var _b = tslib_1.__values(['debug', 'info', 'warn', 'error', 'log']), _c = _b.next(); !_c.done; _c = _b.next()) { - var level = _c.value; - utils_1.fill(consoleModule, level, createConsoleWrapper(level)); - } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); - } - finally { if (e_1) throw e_1.error; } - } - }; - /** - * @inheritDoc - */ - Console.id = 'Console'; - return Console; -}()); -exports.Console = Console; -/** - * Wrapper function that'll be used for every console level - */ -function createConsoleWrapper(level) { - return function consoleWrapper(originalConsoleMethod) { - var sentryLevel; - switch (level) { - case 'debug': - sentryLevel = types_1.Severity.Debug; - break; - case 'error': - sentryLevel = types_1.Severity.Error; - break; - case 'info': - sentryLevel = types_1.Severity.Info; - break; - case 'warn': - sentryLevel = types_1.Severity.Warning; - break; - default: - sentryLevel = types_1.Severity.Log; - } - return function () { - if (core_1.getCurrentHub().getIntegration(Console)) { - core_1.getCurrentHub().addBreadcrumb({ - category: 'console', - level: sentryLevel, - message: util.format.apply(undefined, arguments), - }, { - input: tslib_1.__spread(arguments), - level: level, - }); - } - originalConsoleMethod.apply(this, arguments); - }; - }; + } + + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; } -//# sourceMappingURL=console.js.map -/***/ }), +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _keyLine, + _keyLineStart, + _keyPos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = Object.create(null), + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; -/***/ 76280: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // there is a leading tab before this token, so it can't be a block sequence/mapping; + // it can still be flow sequence/mapping or a scalar + if (state.firstTabInLine !== -1) return false; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var http_1 = __nccwpck_require__(84103); -var NODE_VERSION = utils_1.parseSemver(process.versions.node); -/** http module integration */ -var Http = /** @class */ (function () { - /** - * @inheritDoc - */ - function Http(options) { - if (options === void 0) { options = {}; } - /** - * @inheritDoc - */ - this.name = Http.id; - this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs; - this._tracing = typeof options.tracing === 'undefined' ? false : options.tracing; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } + + ch = state.input.charCodeAt(state.position); + + while (ch !== 0) { + if (!atExplicitKey && state.firstTabInLine !== -1) { + state.position = state.firstTabInLine; + throwError(state, 'tab characters must not be used in indentation'); } - /** - * @inheritDoc - */ - Http.prototype.setupOnce = function () { - // No need to instrument if we don't want to track anything - if (!this._breadcrumbs && !this._tracing) { - return; - } - var wrappedHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, this._tracing); - var httpModule = __nccwpck_require__(98605); - utils_1.fill(httpModule, 'get', wrappedHandlerMaker); - utils_1.fill(httpModule, 'request', wrappedHandlerMaker); - // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. - // If we do, we'd get double breadcrumbs and double spans for `https` calls. - // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately. - if (NODE_VERSION.major && NODE_VERSION.major > 8) { - var httpsModule = __nccwpck_require__(57211); - utils_1.fill(httpsModule, 'get', wrappedHandlerMaker); - utils_1.fill(httpsModule, 'request', wrappedHandlerMaker); + + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; } - }; - /** - * @inheritDoc - */ - Http.id = 'Http'; - return Http; -}()); -exports.Http = Http; -/** - * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http` - * and `https` modules. (NB: Not a typo - this is a creator^2!) - * - * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs - * @param tracingEnabled Whether or not to record outgoing requests as tracing spans - * - * @returns A function which accepts the exiting handler and returns a wrapped handler - */ -function _createWrappedRequestMethodFactory(breadcrumbsEnabled, tracingEnabled) { - return function wrappedRequestMethodFactory(originalRequestMethod) { - return function wrappedMethod() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - // eslint-disable-next-line @typescript-eslint/no-this-alias - var httpModule = this; - var requestArgs = http_1.normalizeRequestArgs(args); - var requestOptions = requestArgs[0]; - var requestUrl = http_1.extractUrl(requestOptions); - // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method - if (http_1.isSentryRequest(requestUrl)) { - return originalRequestMethod.apply(httpModule, requestArgs); - } - var span; - var parentSpan; - var scope = core_1.getCurrentHub().getScope(); - if (scope && tracingEnabled) { - parentSpan = scope.getSpan(); - if (parentSpan) { - span = parentSpan.startChild({ - description: (requestOptions.method || 'GET') + " " + requestUrl, - op: 'request', - }); - var sentryTraceHeader = span.toTraceparent(); - utils_1.logger.log("[Tracing] Adding sentry-trace header to outgoing request: " + sentryTraceHeader); - requestOptions.headers = tslib_1.__assign(tslib_1.__assign({}, requestOptions.headers), { 'sentry-trace': sentryTraceHeader }); - } - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return originalRequestMethod - .apply(httpModule, requestArgs) - .once('response', function (res) { - // eslint-disable-next-line @typescript-eslint/no-this-alias - var req = this; - if (breadcrumbsEnabled) { - addRequestBreadcrumb('response', requestUrl, req, res); - } - if (tracingEnabled && span) { - if (res.statusCode) { - span.setHttpStatus(res.statusCode); - } - span.description = http_1.cleanSpanDescription(span.description, requestOptions, req); - span.finish(); - } - }) - .once('error', function () { - // eslint-disable-next-line @typescript-eslint/no-this-alias - var req = this; - if (breadcrumbsEnabled) { - addRequestBreadcrumb('error', requestUrl, req); - } - if (tracingEnabled && span) { - span.setHttpStatus(500); - span.description = http_1.cleanSpanDescription(span.description, requestOptions, req); - span.finish(); - } - }); - }; - }; -} -/** - * Captures Breadcrumb based on provided request/response pair - */ -function addRequestBreadcrumb(event, url, req, res) { - if (!core_1.getCurrentHub().getIntegration(Http)) { - return; - } - core_1.getCurrentHub().addBreadcrumb({ - category: 'http', - data: { - method: req.method, - status_code: res && res.statusCode, - url: url, - }, - type: 'http', - }, { - event: event, - request: req, - response: res, - }); -} -//# sourceMappingURL=http.js.map -/***/ }), + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); + } + + state.position += 1; + ch = following; + + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + + if (!composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { + // Neither implicit nor explicit notation. + // Reading is done. Go to the epilogue. + break; + } -/***/ 72310: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var console_1 = __nccwpck_require__(29552); -exports.Console = console_1.Console; -var http_1 = __nccwpck_require__(76280); -exports.Http = http_1.Http; -var onuncaughtexception_1 = __nccwpck_require__(50443); -exports.OnUncaughtException = onuncaughtexception_1.OnUncaughtException; -var onunhandledrejection_1 = __nccwpck_require__(87344); -exports.OnUnhandledRejection = onunhandledrejection_1.OnUnhandledRejection; -var linkederrors_1 = __nccwpck_require__(70208); -exports.LinkedErrors = linkederrors_1.LinkedErrors; -var modules_1 = __nccwpck_require__(90046); -exports.Modules = modules_1.Modules; -//# sourceMappingURL=index.js.map + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } -/***/ }), + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); -/***/ 70208: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var parsers_1 = __nccwpck_require__(19090); -var DEFAULT_KEY = 'cause'; -var DEFAULT_LIMIT = 5; -/** Adds SDK info to an event. */ -var LinkedErrors = /** @class */ (function () { - /** - * @inheritDoc - */ - function LinkedErrors(options) { - if (options === void 0) { options = {}; } - /** - * @inheritDoc - */ - this.name = LinkedErrors.id; - this._key = options.key || DEFAULT_KEY; - this._limit = options.limit || DEFAULT_LIMIT; - } - /** - * @inheritDoc - */ - LinkedErrors.prototype.setupOnce = function () { - core_1.addGlobalEventProcessor(function (event, hint) { - var self = core_1.getCurrentHub().getIntegration(LinkedErrors); - if (self) { - var handler = self._handler && self._handler.bind(self); - return typeof handler === 'function' ? handler(event, hint) : event; - } - return event; - }); - }; - /** - * @inheritDoc - */ - LinkedErrors.prototype._handler = function (event, hint) { - var _this = this; - if (!event.exception || !event.exception.values || !hint || !utils_1.isInstanceOf(hint.originalException, Error)) { - return utils_1.SyncPromise.resolve(event); + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } + + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; + + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. } - return new utils_1.SyncPromise(function (resolve) { - _this._walkErrorTree(hint.originalException, _this._key) - .then(function (linkedErrors) { - if (event && event.exception && event.exception.values) { - event.exception.values = tslib_1.__spread(linkedErrors, event.exception.values); - } - resolve(event); - }) - .then(null, function () { - resolve(event); - }); - }); - }; - /** - * @inheritDoc - */ - LinkedErrors.prototype._walkErrorTree = function (error, key, stack) { - var _this = this; - if (stack === void 0) { stack = []; } - if (!utils_1.isInstanceOf(error[key], Error) || stack.length + 1 >= this._limit) { - return utils_1.SyncPromise.resolve(stack); + + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); + + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + } + + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (atExplicitKey) { + _keyLine = state.line; + _keyLineStart = state.lineStart; + _keyPos = state.position; + } + + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; } - return new utils_1.SyncPromise(function (resolve, reject) { - parsers_1.getExceptionFromError(error[key]) - .then(function (exception) { - _this._walkErrorTree(error[key], key, tslib_1.__spread([exception], stack)) - .then(resolve) - .then(null, function () { - reject(); - }); - }) - .then(null, function () { - reject(); - }); - }); - }; - /** - * @inheritDoc - */ - LinkedErrors.id = 'LinkedErrors'; - return LinkedErrors; -}()); -exports.LinkedErrors = LinkedErrors; -//# sourceMappingURL=linkederrors.js.map + } -/***/ }), + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _keyLine, _keyLineStart, _keyPos); + keyTag = keyNode = valueNode = null; + } -/***/ 90046: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var fs_1 = __nccwpck_require__(35747); -var path_1 = __nccwpck_require__(85622); -var moduleCache; -/** Extract information about package.json modules */ -function collectModules() { - var mainPaths = (require.main && require.main.paths) || []; - var paths = require.cache ? Object.keys(require.cache) : []; - var infos = {}; - var seen = {}; - paths.forEach(function (path) { - var dir = path; - /** Traverse directories upward in the search of package.json file */ - var updir = function () { - var orig = dir; - dir = path_1.dirname(orig); - if (!dir || orig === dir || seen[orig]) { - return undefined; - } - if (mainPaths.indexOf(dir) < 0) { - return updir(); - } - var pkgfile = path_1.join(orig, 'package.json'); - seen[orig] = true; - if (!fs_1.existsSync(pkgfile)) { - return updir(); - } - try { - var info = JSON.parse(fs_1.readFileSync(pkgfile, 'utf8')); - infos[info.name] = info.version; - } - catch (_oO) { - // no-empty - } - }; - updir(); - }); - return infos; + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } + } + + // + // Epilogue. + // + + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null, _keyLine, _keyLineStart, _keyPos); + } + + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; + } + + return detected; } -/** Add node modules / packages to the event */ -var Modules = /** @class */ (function () { - function Modules() { - /** - * @inheritDoc - */ - this.name = Modules.id; + +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); + } + + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); + + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; + } + + _position = state.position; + + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); + + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); } - /** - * @inheritDoc - */ - Modules.prototype.setupOnce = function (addGlobalEventProcessor, getCurrentHub) { - var _this = this; - addGlobalEventProcessor(function (event) { - if (!getCurrentHub().getIntegration(Modules)) { - return event; - } - return tslib_1.__assign(tslib_1.__assign({}, event), { modules: _this._getModules() }); - }); - }; - /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ - Modules.prototype._getModules = function () { - if (!moduleCache) { - moduleCache = collectModules(); + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); + + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } + + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); } - return moduleCache; - }; - /** - * @inheritDoc - */ - Modules.id = 'Modules'; - return Modules; -}()); -exports.Modules = Modules; -//# sourceMappingURL=modules.js.map + } -/***/ }), + ch = state.input.charCodeAt(++state.position); + } -/***/ 50443: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + tagName = state.input.slice(_position, state.position); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var core_1 = __nccwpck_require__(79212); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var handlers_1 = __nccwpck_require__(45400); -/** Global Promise Rejection handler */ -var OnUncaughtException = /** @class */ (function () { - /** - * @inheritDoc - */ - function OnUncaughtException(_options) { - if (_options === void 0) { _options = {}; } - this._options = _options; - /** - * @inheritDoc - */ - this.name = OnUncaughtException.id; - /** - * @inheritDoc - */ - this.handler = this._makeErrorHandler(); + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); } - /** - * @inheritDoc - */ - OnUncaughtException.prototype.setupOnce = function () { - global.process.on('uncaughtException', this.handler.bind(this)); - }; - /** - * @hidden - */ - OnUncaughtException.prototype._makeErrorHandler = function () { - var _this = this; - var timeout = 2000; - var caughtFirstError = false; - var caughtSecondError = false; - var calledFatalError = false; - var firstError; - return function (error) { - var onFatalError = handlers_1.logAndExitProcess; - var client = core_1.getCurrentHub().getClient(); - if (_this._options.onFatalError) { - // eslint-disable-next-line @typescript-eslint/unbound-method - onFatalError = _this._options.onFatalError; - } - else if (client && client.getOptions().onFatalError) { - // eslint-disable-next-line @typescript-eslint/unbound-method - onFatalError = client.getOptions().onFatalError; - } - if (!caughtFirstError) { - var hub_1 = core_1.getCurrentHub(); - // this is the first uncaught error and the ultimate reason for shutting down - // we want to do absolutely everything possible to ensure it gets captured - // also we want to make sure we don't go recursion crazy if more errors happen after this one - firstError = error; - caughtFirstError = true; - if (hub_1.getIntegration(OnUncaughtException)) { - hub_1.withScope(function (scope) { - scope.setLevel(types_1.Severity.Fatal); - hub_1.captureException(error, { originalException: error }); - if (!calledFatalError) { - calledFatalError = true; - onFatalError(error); - } - }); - } - else { - if (!calledFatalError) { - calledFatalError = true; - onFatalError(error); - } - } - } - else if (calledFatalError) { - // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down - utils_1.logger.warn('uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown'); - handlers_1.logAndExitProcess(error); - } - else if (!caughtSecondError) { - // two cases for how we can hit this branch: - // - capturing of first error blew up and we just caught the exception from that - // - quit trying to capture, proceed with shutdown - // - a second independent error happened while waiting for first error to capture - // - want to avoid causing premature shutdown before first error capture finishes - // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff - // so let's instead just delay a bit before we proceed with our action here - // in case 1, we just wait a bit unnecessarily but ultimately do the same thing - // in case 2, the delay hopefully made us wait long enough for the capture to finish - // two potential nonideal outcomes: - // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError - // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error - // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError) - // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish - caughtSecondError = true; - setTimeout(function () { - if (!calledFatalError) { - // it was probably case 1, let's treat err as the sendErr and call onFatalError - calledFatalError = true; - onFatalError(firstError, error); - } - else { - // it was probably case 2, our first error finished capturing while we waited, cool, do nothing - } - }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc - } - }; - }; - /** - * @inheritDoc - */ - OnUncaughtException.id = 'OnUncaughtException'; - return OnUncaughtException; -}()); -exports.OnUncaughtException = OnUncaughtException; -//# sourceMappingURL=onuncaughtexception.js.map + } + + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } + + try { + tagName = decodeURIComponent(tagName); + } catch (err) { + throwError(state, 'tag name is malformed: ' + tagName); + } + + if (isVerbatim) { + state.tag = tagName; + + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; + + } else if (tagHandle === '!') { + state.tag = '!' + tagName; + + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; + + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); + } + + return true; +} + +function readAnchorProperty(state) { + var _position, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); + } + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; +} + +function readAlias(state) { + var _position, alias, + ch; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x2A/* * */) return false; + + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } -/***/ }), + alias = state.input.slice(_position, state.position); -/***/ 87344: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var core_1 = __nccwpck_require__(79212); -var utils_1 = __nccwpck_require__(1620); -var handlers_1 = __nccwpck_require__(45400); -/** Global Promise Rejection handler */ -var OnUnhandledRejection = /** @class */ (function () { - /** - * @inheritDoc - */ - function OnUnhandledRejection(_options) { - if (_options === void 0) { _options = { mode: 'warn' }; } - this._options = _options; - /** - * @inheritDoc - */ - this.name = OnUnhandledRejection.id; + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; +} + +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } } - /** - * @inheritDoc - */ - OnUnhandledRejection.prototype.setupOnce = function () { - global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this)); - }; - /** - * Send an exception with reason - * @param reason string - * @param promise promise - */ - // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any - OnUnhandledRejection.prototype.sendUnhandledPromise = function (reason, promise) { - var hub = core_1.getCurrentHub(); - if (!hub.getIntegration(OnUnhandledRejection)) { - this._handleRejection(reason); - return; + } + + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; + + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; } - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - var context = (promise.domain && promise.domain.sentryContext) || {}; - hub.withScope(function (scope) { - scope.setExtra('unhandledPromiseRejection', true); - // Preserve backwards compatibility with raven-node for now - if (context.user) { - scope.setUser(context.user); - } - if (context.tags) { - scope.setTags(context.tags); - } - if (context.extra) { - scope.setExtras(context.extra); - } - hub.captureException(reason, { originalException: promise }); - }); - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - this._handleRejection(reason); - }; - /** - * Handler for `mode` option - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - OnUnhandledRejection.prototype._handleRejection = function (reason) { - // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240 - var rejectionWarning = 'This error originated either by ' + - 'throwing inside of an async function without a catch block, ' + - 'or by rejecting a promise which was not handled with .catch().' + - ' The promise rejected with the reason:'; - /* eslint-disable no-console */ - if (this._options.mode === 'warn') { - utils_1.consoleSandbox(function () { - console.warn(rejectionWarning); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - console.error(reason && reason.stack ? reason.stack : reason); - }); + } else { + allowBlockCollections = false; + } + } + } + + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; + } + + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; + } + + blockIndent = state.position - state.lineStart; + + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; + + } else if (readAlias(state)) { + hasContent = true; + + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } + + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; + + if (state.tag === null) { + state.tag = '?'; + } } - else if (this._options.mode === 'strict') { - utils_1.consoleSandbox(function () { - console.warn(rejectionWarning); - }); - handlers_1.logAndExitProcess(reason); + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; } - /* eslint-enable no-console */ - }; - /** - * @inheritDoc - */ - OnUnhandledRejection.id = 'OnUnhandledRejection'; - return OnUnhandledRejection; -}()); -exports.OnUnhandledRejection = OnUnhandledRejection; -//# sourceMappingURL=onunhandledrejection.js.map + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); + } + } -/***/ }), + if (state.tag === null) { + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } -/***/ 84103: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + } else if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var url_1 = __nccwpck_require__(78835); -/** - * Checks whether given url points to Sentry server - * @param url url to verify - */ -function isSentryRequest(url) { - var _a; - var dsn = (_a = core_1.getCurrentHub() - .getClient()) === null || _a === void 0 ? void 0 : _a.getDsn(); - return dsn ? url.includes(dsn.host) : false; -} -exports.isSentryRequest = isSentryRequest; -/** - * Assemble a URL to be used for breadcrumbs and spans. - * - * @param requestOptions RequestOptions object containing the component parts for a URL - * @returns Fully-formed URL - */ -function extractUrl(requestOptions) { - var protocol = requestOptions.protocol || ''; - var hostname = requestOptions.hostname || requestOptions.host || ''; - // Don't log standard :80 (http) and :443 (https) ports to reduce the noise - var port = !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 ? '' : ":" + requestOptions.port; - var path = requestOptions.path ? requestOptions.path : '/'; - return protocol + "//" + hostname + port + path; -} -exports.extractUrl = extractUrl; -/** - * Handle various edge cases in the span description (for spans representing http(s) requests). - * - * @param description current `description` property of the span representing the request - * @param requestOptions Configuration data for the request - * @param Request Request object - * - * @returns The cleaned description - */ -function cleanSpanDescription(description, requestOptions, request) { - var _a, _b, _c; - // nothing to clean - if (!description) { - return description; + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } } - // eslint-disable-next-line prefer-const - var _d = tslib_1.__read(description.split(' '), 2), method = _d[0], requestUrl = _d[1]; - // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing, - // we're likely dealing with an internal route and this doesn't apply) - if (requestOptions.host && !requestOptions.protocol) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - requestOptions.protocol = (_b = (_a = request) === null || _a === void 0 ? void 0 : _a.agent) === null || _b === void 0 ? void 0 : _b.protocol; // worst comes to worst, this is undefined and nothing changes - requestUrl = extractUrl(requestOptions); + } else if (state.tag !== '!') { + if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; + } else { + // looking for multi type + type = null; + typeList = state.typeMap.multi[state.kind || 'fallback']; + + for (typeIndex = 0, typeQuantity = typeList.length; typeIndex < typeQuantity; typeIndex += 1) { + if (state.tag.slice(0, typeList[typeIndex].tag.length) === typeList[typeIndex].tag) { + type = typeList[typeIndex]; + break; + } + } } - // internal routes can end up starting with a triple slash rather than a single one - if ((_c = requestUrl) === null || _c === void 0 ? void 0 : _c.startsWith('///')) { - requestUrl = requestUrl.slice(2); + + if (!type) { + throwError(state, 'unknown tag !<' + state.tag + '>'); } - return method + " " + requestUrl; -} -exports.cleanSpanDescription = cleanSpanDescription; -/** - * Convert a URL object into a RequestOptions object. - * - * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the - * RequestOptions type above. - * - * See https://github.com/nodejs/node/blob/master/lib/internal/url.js. - */ -function urlToOptions(url) { - var options = { - protocol: url.protocol, - hostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, - hash: url.hash, - search: url.search, - pathname: url.pathname, - path: "" + (url.pathname || '') + (url.search || ''), - href: url.href, - }; - if (url.port !== '') { - options.port = Number(url.port); + + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); } - if (url.username || url.password) { - options.auth = url.username + ":" + url.password; + + if (!type.resolve(state.result, state.tag)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result, state.tag); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } } - return options; + } + + if (state.listener !== null) { + state.listener('close', state); + } + return state.tag !== null || state.anchor !== null || hasContent; } -exports.urlToOptions = urlToOptions; -/** - * Normalize inputs to `http(s).request()` and `http(s).get()`. - * - * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms: - * [ RequestOptions | string | URL ], - * [ RequestOptions | string | URL, RequestCallback ], - * [ string | URL, RequestOptions ], and - * [ string | URL, RequestOptions, RequestCallback ]. - * - * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is - * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact - * with the args in a standard way. - * - * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array. - * - * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ]. - */ -function normalizeRequestArgs(requestArgs) { - var callback, requestOptions; - // pop off the callback, if there is one - if (typeof requestArgs[requestArgs.length - 1] === 'function') { - callback = requestArgs.pop(); + +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; + + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = Object.create(null); + state.anchorMap = Object.create(null); + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); + + ch = state.input.charCodeAt(state.position); + + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; } - // create a RequestOptions object of whatever's at index 0 - if (typeof requestArgs[0] === 'string') { - requestOptions = urlToOptions(new url_1.URL(requestArgs[0])); + + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); } - else if (requestArgs[0] instanceof url_1.URL) { - requestOptions = urlToOptions(requestArgs[0]); + + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; + + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); } - else { - requestOptions = requestArgs[0]; + + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } + + if (is_EOL(ch)) break; + + _position = state.position; + + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } + + directiveArgs.push(state.input.slice(_position, state.position)); } - // if the options were given separately from the URL, fold them in - if (requestArgs.length === 2) { - requestOptions = tslib_1.__assign(tslib_1.__assign({}, requestOptions), requestArgs[1]); + + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); } - // return args in standardized form - if (callback) { - return [requestOptions, callback]; + } + + skipSeparationSpace(state, true, -1); + + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); + } + + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); + + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); + } + + state.documents.push(state.result); + + if (state.position === state.lineStart && testDocumentSeparator(state)) { + + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); } - else { - return [requestOptions]; + return; + } + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; + } +} + + +function loadDocuments(input, options) { + input = String(input); + options = options || {}; + + if (input.length !== 0) { + + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; + } + + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); } + } + + var state = new State(input, options); + + var nullpos = input.indexOf('\0'); + + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } + + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; + + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } + + while (state.position < (state.length - 1)) { + readDocument(state); + } + + return state.documents; +} + + +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } + + var documents = loadDocuments(input, options); + + if (typeof iterator !== 'function') { + return documents; + } + + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} + + +function load(input, options) { + var documents = loadDocuments(input, options); + + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new YAMLException('expected a single document in the stream, but found more'); } -exports.normalizeRequestArgs = normalizeRequestArgs; -//# sourceMappingURL=http.js.map + + +module.exports.loadAll = loadAll; +module.exports.load = load; + /***/ }), -/***/ 19090: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 22258: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var fs_1 = __nccwpck_require__(35747); -var lru_map_1 = __nccwpck_require__(18424); -var stacktrace = __nccwpck_require__(46276); -var DEFAULT_LINES_OF_CONTEXT = 7; -var FILE_CONTENT_CACHE = new lru_map_1.LRUMap(100); -/** - * Resets the file cache. Exists for testing purposes. - * @hidden - */ -function resetFileContentCache() { - FILE_CONTENT_CACHE.clear(); -} -exports.resetFileContentCache = resetFileContentCache; -/** JSDoc */ -function getFunction(frame) { - try { - return frame.functionName || frame.typeName + "." + (frame.methodName || ''); - } - catch (e) { - // This seems to happen sometimes when using 'use strict', - // stemming from `getTypeName`. - // [TypeError: Cannot read property 'constructor' of undefined] - return ''; - } +"use strict"; + + +/*eslint-disable max-len*/ + +var YAMLException = __nccwpck_require__(30780); +var Type = __nccwpck_require__(57480); + + +function compileList(schema, name) { + var result = []; + + schema[name].forEach(function (currentType) { + var newIndex = result.length; + + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && + previousType.kind === currentType.kind && + previousType.multi === currentType.multi) { + + newIndex = previousIndex; + } + }); + + result[newIndex] = currentType; + }); + + return result; } -var mainModule = ((require.main && require.main.filename && utils_1.dirname(require.main.filename)) || - global.process.cwd()) + "/"; -/** JSDoc */ -function getModule(filename, base) { - if (!base) { - // eslint-disable-next-line no-param-reassign - base = mainModule; - } - // It's specifically a module - var file = utils_1.basename(filename, '.js'); - // eslint-disable-next-line no-param-reassign - filename = utils_1.dirname(filename); - var n = filename.lastIndexOf('/node_modules/'); - if (n > -1) { - // /node_modules/ is 14 chars - return filename.substr(n + 14).replace(/\//g, '.') + ":" + file; - } - // Let's see if it's a part of the main module - // To be a part of main module, it has to share the same base - n = (filename + "/").lastIndexOf(base, 0); - if (n === 0) { - var moduleName = filename.substr(base.length).replace(/\//g, '.'); - if (moduleName) { - moduleName += ':'; + + +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {}, + multi: { + scalar: [], + sequence: [], + mapping: [], + fallback: [] } - moduleName += file; - return moduleName; + }, index, length; + + function collectType(type) { + if (type.multi) { + result.multi[type.kind].push(type); + result.multi['fallback'].push(type); + } else { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; } - return file; + } + + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; } -/** - * This function reads file contents and caches them in a global LRU cache. - * Returns a Promise filepath => content array for all files that we were able to read. - * - * @param filenames Array of filepaths to read content from. - */ -function readSourceFiles(filenames) { - // we're relying on filenames being de-duped already - if (filenames.length === 0) { - return utils_1.SyncPromise.resolve({}); - } - return new utils_1.SyncPromise(function (resolve) { - var sourceFiles = {}; - var count = 0; - var _loop_1 = function (i) { - var filename = filenames[i]; - var cache = FILE_CONTENT_CACHE.get(filename); - // We have a cache hit - if (cache !== undefined) { - // If it's not null (which means we found a file and have a content) - // we set the content and return it later. - if (cache !== null) { - sourceFiles[filename] = cache; - } - // eslint-disable-next-line no-plusplus - count++; - // In any case we want to skip here then since we have a content already or we couldn't - // read the file and don't want to try again. - if (count === filenames.length) { - resolve(sourceFiles); - } - return "continue"; - } - fs_1.readFile(filename, function (err, data) { - var content = err ? null : data.toString(); - sourceFiles[filename] = content; - // We always want to set the cache, even to null which means there was an error reading the file. - // We do not want to try to read the file again. - FILE_CONTENT_CACHE.set(filename, content); - // eslint-disable-next-line no-plusplus - count++; - if (count === filenames.length) { - resolve(sourceFiles); - } - }); - }; - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (var i = 0; i < filenames.length; i++) { - _loop_1(i); - } - }); + + +function Schema(definition) { + return this.extend(definition); } -/** - * @hidden - */ -function extractStackFromError(error) { - var stack = stacktrace.parse(error); - if (!stack) { - return []; + + +Schema.prototype.extend = function extend(definition) { + var implicit = []; + var explicit = []; + + if (definition instanceof Type) { + // Schema.extend(type) + explicit.push(definition); + + } else if (Array.isArray(definition)) { + // Schema.extend([ type1, type2, ... ]) + explicit = explicit.concat(definition); + + } else if (definition && (Array.isArray(definition.implicit) || Array.isArray(definition.explicit))) { + // Schema.extend({ explicit: [ type1, type2, ... ], implicit: [ type1, type2, ... ] }) + if (definition.implicit) implicit = implicit.concat(definition.implicit); + if (definition.explicit) explicit = explicit.concat(definition.explicit); + + } else { + throw new YAMLException('Schema.extend argument should be a Type, [ Type ], ' + + 'or a schema definition ({ implicit: [...], explicit: [...] })'); + } + + implicit.forEach(function (type) { + if (!(type instanceof Type)) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } - return stack; -} -exports.extractStackFromError = extractStackFromError; -/** - * @hidden - */ -function parseStack(stack, options) { - var filesToRead = []; - var linesOfContext = options && options.frameContextLines !== undefined ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; - var frames = stack.map(function (frame) { - var parsedFrame = { - colno: frame.columnNumber, - filename: frame.fileName || '', - function: getFunction(frame), - lineno: frame.lineNumber, - }; - var isInternal = frame.native || - (parsedFrame.filename && - !parsedFrame.filename.startsWith('/') && - !parsedFrame.filename.startsWith('.') && - parsedFrame.filename.indexOf(':\\') !== 1); - // in_app is all that's not an internal Node function or a module within node_modules - // note that isNative appears to return true even for node core libraries - // see https://github.com/getsentry/raven-node/issues/176 - parsedFrame.in_app = - !isInternal && parsedFrame.filename !== undefined && parsedFrame.filename.indexOf('node_modules/') === -1; - // Extract a module name based on the filename - if (parsedFrame.filename) { - parsedFrame.module = getModule(parsedFrame.filename); - if (!isInternal && linesOfContext > 0 && filesToRead.indexOf(parsedFrame.filename) === -1) { - filesToRead.push(parsedFrame.filename); - } - } - return parsedFrame; - }); - // We do an early return if we do not want to fetch context liens - if (linesOfContext <= 0) { - return utils_1.SyncPromise.resolve(frames); + + if (type.loadKind && type.loadKind !== 'scalar') { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); } - try { - return addPrePostContext(filesToRead, frames, linesOfContext); + + if (type.multi) { + throw new YAMLException('There is a multi type in the implicit list of a schema. Multi tags can only be listed as explicit.'); } - catch (_) { - // This happens in electron for example where we are not able to read files from asar. - // So it's fine, we recover be just returning all frames without pre/post context. - return utils_1.SyncPromise.resolve(frames); + }); + + explicit.forEach(function (type) { + if (!(type instanceof Type)) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); } + }); + + var result = Object.create(Schema.prototype); + + result.implicit = (this.implicit || []).concat(implicit); + result.explicit = (this.explicit || []).concat(explicit); + + result.compiledImplicit = compileList(result, 'implicit'); + result.compiledExplicit = compileList(result, 'explicit'); + result.compiledTypeMap = compileMap(result.compiledImplicit, result.compiledExplicit); + + return result; +}; + + +module.exports = Schema; + + +/***/ }), + +/***/ 90085: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. + + + + + +module.exports = __nccwpck_require__(70265); + + +/***/ }), + +/***/ 77599: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) + + + + + +module.exports = __nccwpck_require__(90085).extend({ + implicit: [ + __nccwpck_require__(9561), + __nccwpck_require__(70884) + ], + explicit: [ + __nccwpck_require__(56942), + __nccwpck_require__(65894), + __nccwpck_require__(18978), + __nccwpck_require__(87424) + ] +}); + + +/***/ }), + +/***/ 54323: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 + + + + + +var Schema = __nccwpck_require__(22258); + + +module.exports = new Schema({ + explicit: [ + __nccwpck_require__(32568), + __nccwpck_require__(89695), + __nccwpck_require__(74352) + ] +}); + + +/***/ }), + +/***/ 70265: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. + + + + + +module.exports = __nccwpck_require__(54323).extend({ + implicit: [ + __nccwpck_require__(61002), + __nccwpck_require__(85327), + __nccwpck_require__(2848), + __nccwpck_require__(56128) + ] +}); + + +/***/ }), + +/***/ 68947: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + + +var common = __nccwpck_require__(44828); + + +// get snippet for a single line, respecting maxLength +function getLine(buffer, lineStart, lineEnd, position, maxLineLength) { + var head = ''; + var tail = ''; + var maxHalfLength = Math.floor(maxLineLength / 2) - 1; + + if (position - lineStart > maxHalfLength) { + head = ' ... '; + lineStart = position - maxHalfLength + head.length; + } + + if (lineEnd - position > maxHalfLength) { + tail = ' ...'; + lineEnd = position + maxHalfLength - tail.length; + } + + return { + str: head + buffer.slice(lineStart, lineEnd).replace(/\t/g, '→') + tail, + pos: position - lineStart + head.length // relative position + }; } -exports.parseStack = parseStack; -/** - * This function tries to read the source files + adding pre and post context (source code) - * to a frame. - * @param filesToRead string[] of filepaths - * @param frames StackFrame[] containg all frames - */ -function addPrePostContext(filesToRead, frames, linesOfContext) { - return new utils_1.SyncPromise(function (resolve) { - return readSourceFiles(filesToRead).then(function (sourceFiles) { - var result = frames.map(function (frame) { - if (frame.filename && sourceFiles[frame.filename]) { - try { - var lines = sourceFiles[frame.filename].split('\n'); - utils_1.addContextToFrame(lines, frame, linesOfContext); - } - catch (e) { - // anomaly, being defensive in case - // unlikely to ever happen in practice but can definitely happen in theory - } - } - return frame; - }); - resolve(result); - }); - }); + + +function padStart(string, max) { + return common.repeat(' ', max - string.length) + string; } -/** - * @hidden - */ -function getExceptionFromError(error, options) { - var name = error.name || error.constructor.name; - var stack = extractStackFromError(error); - return new utils_1.SyncPromise(function (resolve) { - return parseStack(stack, options).then(function (frames) { - var result = { - stacktrace: { - frames: prepareFramesForEvent(frames), - }, - type: name, - value: error.message, - }; - resolve(result); - }); - }); + + +function makeSnippet(mark, options) { + options = Object.create(options || null); + + if (!mark.buffer) return null; + + if (!options.maxLength) options.maxLength = 79; + if (typeof options.indent !== 'number') options.indent = 1; + if (typeof options.linesBefore !== 'number') options.linesBefore = 3; + if (typeof options.linesAfter !== 'number') options.linesAfter = 2; + + var re = /\r?\n|\r|\0/g; + var lineStarts = [ 0 ]; + var lineEnds = []; + var match; + var foundLineNo = -1; + + while ((match = re.exec(mark.buffer))) { + lineEnds.push(match.index); + lineStarts.push(match.index + match[0].length); + + if (mark.position <= match.index && foundLineNo < 0) { + foundLineNo = lineStarts.length - 2; + } + } + + if (foundLineNo < 0) foundLineNo = lineStarts.length - 1; + + var result = '', i, line; + var lineNoLength = Math.min(mark.line + options.linesAfter, lineEnds.length).toString().length; + var maxLineLength = options.maxLength - (options.indent + lineNoLength + 3); + + for (i = 1; i <= options.linesBefore; i++) { + if (foundLineNo - i < 0) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo - i], + lineEnds[foundLineNo - i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo - i]), + maxLineLength + ); + result = common.repeat(' ', options.indent) + padStart((mark.line - i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n' + result; + } + + line = getLine(mark.buffer, lineStarts[foundLineNo], lineEnds[foundLineNo], mark.position, maxLineLength); + result += common.repeat(' ', options.indent) + padStart((mark.line + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + result += common.repeat('-', options.indent + lineNoLength + 3 + line.pos) + '^' + '\n'; + + for (i = 1; i <= options.linesAfter; i++) { + if (foundLineNo + i >= lineEnds.length) break; + line = getLine( + mark.buffer, + lineStarts[foundLineNo + i], + lineEnds[foundLineNo + i], + mark.position - (lineStarts[foundLineNo] - lineStarts[foundLineNo + i]), + maxLineLength + ); + result += common.repeat(' ', options.indent) + padStart((mark.line + i + 1).toString(), lineNoLength) + + ' | ' + line.str + '\n'; + } + + return result.replace(/\n$/, ''); } -exports.getExceptionFromError = getExceptionFromError; -/** - * @hidden - */ -function parseError(error, options) { - return new utils_1.SyncPromise(function (resolve) { - return getExceptionFromError(error, options).then(function (exception) { - resolve({ - exception: { - values: [exception], - }, - }); - }); + + +module.exports = makeSnippet; + + +/***/ }), + +/***/ 57480: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var YAMLException = __nccwpck_require__(30780); + +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'multi', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'representName', + 'defaultStyle', + 'styleAliases' +]; + +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; + +function compileStyleAliases(map) { + var result = {}; + + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); }); + } + + return result; } -exports.parseError = parseError; -/** - * @hidden - */ -function prepareFramesForEvent(stack) { - if (!stack || !stack.length) { - return []; - } - var localStack = stack; - var firstFrameFunction = localStack[0].function || ''; - if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) { - localStack = localStack.slice(1); + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); } - // The frame where the crash happened, should be the last entry in the array - return localStack.reverse(); + }); + + // TODO: Add tag format check. + this.options = options; // keep original options in case user wants to extend this type later + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.representName = options['representName'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.multi = options['multi'] || false; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } +} + +module.exports = Type; + + +/***/ }), + +/***/ 56942: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +/*eslint-disable no-bitwise*/ + + +var Type = __nccwpck_require__(57480); + + +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + + +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; + + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; } -exports.prepareFramesForEvent = prepareFramesForEvent; -//# sourceMappingURL=parsers.js.map -/***/ }), +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; -/***/ 38836: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // Collect by 6*4 bits (3 bytes) -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); -var domain = __nccwpck_require__(85229); -var client_1 = __nccwpck_require__(86147); -var integrations_1 = __nccwpck_require__(72310); -exports.defaultIntegrations = [ - // Common - new core_1.Integrations.InboundFilters(), - new core_1.Integrations.FunctionToString(), - // Native Wrappers - new integrations_1.Console(), - new integrations_1.Http(), - // Global Handlers - new integrations_1.OnUncaughtException(), - new integrations_1.OnUnhandledRejection(), - // Misc - new integrations_1.LinkedErrors(), -]; -/** - * The Sentry Node SDK Client. - * - * To use this SDK, call the {@link init} function as early as possible in the - * main entry module. To set context information or send manual events, use the - * provided methods. - * - * @example - * ``` - * - * const { init } = require('@sentry/node'); - * - * init({ - * dsn: '__DSN__', - * // ... - * }); - * ``` - * - * @example - * ``` - * - * const { configureScope } = require('@sentry/node'); - * configureScope((scope: Scope) => { - * scope.setExtra({ battery: 0.7 }); - * scope.setTag({ user_mode: 'admin' }); - * scope.setUser({ id: '4711' }); - * }); - * ``` - * - * @example - * ``` - * - * const { addBreadcrumb } = require('@sentry/node'); - * addBreadcrumb({ - * message: 'My Breadcrumb', - * // ... - * }); - * ``` - * - * @example - * ``` - * - * const Sentry = require('@sentry/node'); - * Sentry.captureMessage('Hello, world!'); - * Sentry.captureException(new Error('Good bye')); - * Sentry.captureEvent({ - * message: 'Manual', - * stacktrace: [ - * // ... - * ], - * }); - * ``` - * - * @see {@link NodeOptions} for documentation on configuration options. - */ -function init(options) { - if (options === void 0) { options = {}; } - if (options.defaultIntegrations === undefined) { - options.defaultIntegrations = exports.defaultIntegrations; - } - if (options.dsn === undefined && process.env.SENTRY_DSN) { - options.dsn = process.env.SENTRY_DSN; - } - if (options.release === undefined) { - var global_1 = utils_1.getGlobalObject(); - // Prefer env var over global - if (process.env.SENTRY_RELEASE) { - options.release = process.env.SENTRY_RELEASE; - } - // This supports the variable that sentry-webpack-plugin injects - else if (global_1.SENTRY_RELEASE && global_1.SENTRY_RELEASE.id) { - options.release = global_1.SENTRY_RELEASE.id; - } - } - if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) { - options.environment = process.env.SENTRY_ENVIRONMENT; + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); } - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - if (domain.active) { - hub_1.setHubOnCarrier(hub_1.getMainCarrier(), core_1.getCurrentHub()); + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); + } + + // Dump tail + + tailbits = (max % 4) * 6; + + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); + } + + return new Uint8Array(result); +} + +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; } - core_1.initAndBind(client_1.NodeClient, options); + + bits = (bits << 8) + object[idx]; + } + + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; } -exports.init = init; -/** - * This is the getter for lastEventId. - * - * @returns The last event id of a captured event. - */ -function lastEventId() { - return core_1.getCurrentHub().lastEventId(); + +function isBinary(obj) { + return Object.prototype.toString.call(obj) === '[object Uint8Array]'; } -exports.lastEventId = lastEventId; -/** - * A promise that resolves when all current events have been sent. - * If you provide a timeout and the queue takes longer to drain the promise returns false. - * - * @param timeout Maximum time in ms the client should wait. - */ -function flush(timeout) { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var client; - return tslib_1.__generator(this, function (_a) { - client = core_1.getCurrentHub().getClient(); - if (client) { - return [2 /*return*/, client.flush(timeout)]; - } - return [2 /*return*/, Promise.reject(false)]; - }); - }); + +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); + + +/***/ }), + +/***/ 85327: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Type = __nccwpck_require__(57480); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); } -exports.flush = flush; -/** - * A promise that resolves when all current events have been sent. - * If you provide a timeout and the queue takes longer to drain the promise returns false. - * - * @param timeout Maximum time in ms the client should wait. - */ -function close(timeout) { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var client; - return tslib_1.__generator(this, function (_a) { - client = core_1.getCurrentHub().getClient(); - if (client) { - return [2 /*return*/, client.close(timeout)]; - } - return [2 /*return*/, Promise.reject(false)]; - }); - }); + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; } -exports.close = close; -//# sourceMappingURL=sdk.js.map + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); + /***/ }), -/***/ 46276: -/***/ ((__unused_webpack_module, exports) => { +/***/ 56128: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * stack-trace - Parses node.js stack traces - * - * This was originally forked to fix this issue: - * https://github.com/felixge/node-stack-trace/issues/31 - * - * Mar 19,2019 - #4fd379e - * - * https://github.com/felixge/node-stack-trace/ - * @license MIT - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** Extracts StackFrames from the Error */ -function parse(err) { - if (!err.stack) { - return []; - } - var lines = err.stack.split('\n').slice(1); - return lines - .map(function (line) { - if (line.match(/^\s*[-]{4,}$/)) { - return { - columnNumber: null, - fileName: line, - functionName: null, - lineNumber: null, - methodName: null, - native: null, - typeName: null, - }; - } - var lineMatch = line.match(/at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/); - if (!lineMatch) { - return undefined; - } - var object = null; - var method = null; - var functionName = null; - var typeName = null; - var methodName = null; - var isNative = lineMatch[5] === 'native'; - if (lineMatch[1]) { - functionName = lineMatch[1]; - var methodStart = functionName.lastIndexOf('.'); - if (functionName[methodStart - 1] === '.') { - // eslint-disable-next-line no-plusplus - methodStart--; - } - if (methodStart > 0) { - object = functionName.substr(0, methodStart); - method = functionName.substr(methodStart + 1); - var objectEnd = object.indexOf('.Module'); - if (objectEnd > 0) { - functionName = functionName.substr(objectEnd + 1); - object = object.substr(0, objectEnd); - } - } - typeName = null; - } - if (method) { - typeName = object; - methodName = method; - } - if (method === '') { - methodName = null; - functionName = null; - } - var properties = { - columnNumber: parseInt(lineMatch[4], 10) || null, - fileName: lineMatch[2] || null, - functionName: functionName, - lineNumber: parseInt(lineMatch[3], 10) || null, - methodName: methodName, - native: isNative, - typeName: typeName, - }; - return properties; - }) - .filter(function (callSite) { return !!callSite; }); +"use strict"; + + +var common = __nccwpck_require__(44828); +var Type = __nccwpck_require__(57480); + +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:[0-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); + +function resolveYamlFloat(data) { + if (data === null) return false; + + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; + } + + return true; } -exports.parse = parse; -//# sourceMappingURL=stacktrace.js.map -/***/ }), +function constructYamlFloat(data) { + var value, sign; -/***/ 43240: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var core_1 = __nccwpck_require__(79212); -var types_1 = __nccwpck_require__(83789); -var utils_1 = __nccwpck_require__(1620); -var fs = __nccwpck_require__(35747); -var url = __nccwpck_require__(78835); -var version_1 = __nccwpck_require__(31271); -/** Base Transport class implementation */ -var BaseTransport = /** @class */ (function () { - /** Create instance and set this.dsn */ - function BaseTransport(options) { - this.options = options; - /** A simple buffer holding all requests. */ - this._buffer = new utils_1.PromiseBuffer(30); - /** Locks transport after receiving 429 response */ - this._disabledUntil = new Date(Date.now()); - this._api = new core_1.API(options.dsn); - } - /** - * @inheritDoc - */ - BaseTransport.prototype.sendEvent = function (_) { - throw new utils_1.SentryError('Transport Class has to implement `sendEvent` method.'); - }; - /** - * @inheritDoc - */ - BaseTransport.prototype.close = function (timeout) { - return this._buffer.drain(timeout); - }; - /** Returns a build request option object used by request */ - BaseTransport.prototype._getRequestOptions = function (uri) { - var headers = tslib_1.__assign(tslib_1.__assign({}, this._api.getRequestHeaders(version_1.SDK_NAME, version_1.SDK_VERSION)), this.options.headers); - var hostname = uri.hostname, pathname = uri.pathname, port = uri.port, protocol = uri.protocol; - // See https://github.com/nodejs/node/blob/38146e717fed2fabe3aacb6540d839475e0ce1c6/lib/internal/url.js#L1268-L1290 - // We ignore the query string on purpose - var path = "" + pathname; - return tslib_1.__assign({ agent: this.client, headers: headers, - hostname: hostname, method: 'POST', path: path, - port: port, - protocol: protocol }, (this.options.caCerts && { - ca: fs.readFileSync(this.options.caCerts), - })); - }; - /** JSDoc */ - BaseTransport.prototype._sendWithModule = function (httpModule, event) { - return tslib_1.__awaiter(this, void 0, void 0, function () { - var _this = this; - return tslib_1.__generator(this, function (_a) { - if (new Date(Date.now()) < this._disabledUntil) { - return [2 /*return*/, Promise.reject(new utils_1.SentryError("Transport locked till " + this._disabledUntil + " due to too many requests."))]; - } - if (!this._buffer.isReady()) { - return [2 /*return*/, Promise.reject(new utils_1.SentryError('Not adding Promise due to buffer limit reached.'))]; - } - return [2 /*return*/, this._buffer.add(new Promise(function (resolve, reject) { - var sentryReq = core_1.eventToSentryRequest(event, _this._api); - var options = _this._getRequestOptions(new url.URL(sentryReq.url)); - var req = httpModule.request(options, function (res) { - var statusCode = res.statusCode || 500; - var status = types_1.Status.fromHttpCode(statusCode); - res.setEncoding('utf8'); - if (status === types_1.Status.Success) { - resolve({ status: status }); - } - else { - if (status === types_1.Status.RateLimit) { - var now = Date.now(); - /** - * "Key-value pairs of header names and values. Header names are lower-cased." - * https://nodejs.org/api/http.html#http_message_headers - */ - var retryAfterHeader = res.headers ? res.headers['retry-after'] : ''; - retryAfterHeader = (Array.isArray(retryAfterHeader) ? retryAfterHeader[0] : retryAfterHeader); - _this._disabledUntil = new Date(now + utils_1.parseRetryAfterHeader(now, retryAfterHeader)); - utils_1.logger.warn("Too many requests, backing off till: " + _this._disabledUntil); - } - var rejectionMessage = "HTTP Error (" + statusCode + ")"; - if (res.headers && res.headers['x-sentry-error']) { - rejectionMessage += ": " + res.headers['x-sentry-error']; - } - reject(new utils_1.SentryError(rejectionMessage)); - } - // Force the socket to drain - res.on('data', function () { - // Drain - }); - res.on('end', function () { - // Drain - }); - }); - req.on('error', reject); - req.end(sentryReq.body); - }))]; - }); - }); - }; - return BaseTransport; -}()); -exports.BaseTransport = BaseTransport; -//# sourceMappingURL=base.js.map + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); + } -/***/ }), + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; -/***/ 84490: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + } else if (value === '.nan') { + return NaN; + } + return sign * parseFloat(value, 10); +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var http = __nccwpck_require__(98605); -var base_1 = __nccwpck_require__(43240); -/** Node http module transport */ -var HTTPTransport = /** @class */ (function (_super) { - tslib_1.__extends(HTTPTransport, _super); - /** Create a new instance and set this.agent */ - function HTTPTransport(options) { - var _this = _super.call(this, options) || this; - _this.options = options; - var proxy = options.httpProxy || process.env.http_proxy; - _this.module = http; - _this.client = proxy - ? new (__nccwpck_require__(77219))(proxy) - : new http.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 }); - return _this; - } - /** - * @inheritDoc - */ - HTTPTransport.prototype.sendEvent = function (event) { - if (!this.module) { - throw new utils_1.SentryError('No module available in HTTPTransport'); - } - return this._sendWithModule(this.module, event); - }; - return HTTPTransport; -}(base_1.BaseTransport)); -exports.HTTPTransport = HTTPTransport; -//# sourceMappingURL=http.js.map -/***/ }), +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; -/***/ 68621: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function representYamlFloat(object, style) { + var res; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var https = __nccwpck_require__(57211); -var base_1 = __nccwpck_require__(43240); -/** Node https module transport */ -var HTTPSTransport = /** @class */ (function (_super) { - tslib_1.__extends(HTTPSTransport, _super); - /** Create a new instance and set this.agent */ - function HTTPSTransport(options) { - var _this = _super.call(this, options) || this; - _this.options = options; - var proxy = options.httpsProxy || options.httpProxy || process.env.https_proxy || process.env.http_proxy; - _this.module = https; - _this.client = proxy - ? new (__nccwpck_require__(77219))(proxy) - : new https.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 }); - return _this; + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; } - /** - * @inheritDoc - */ - HTTPSTransport.prototype.sendEvent = function (event) { - if (!this.module) { - throw new utils_1.SentryError('No module available in HTTPSTransport'); - } - return this._sendWithModule(this.module, event); - }; - return HTTPSTransport; -}(base_1.BaseTransport)); -exports.HTTPSTransport = HTTPSTransport; -//# sourceMappingURL=https.js.map + } else if (common.isNegativeZero(object)) { + return '-0.0'; + } -/***/ }), + res = object.toString(10); -/***/ 21437: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack -Object.defineProperty(exports, "__esModule", ({ value: true })); -var base_1 = __nccwpck_require__(43240); -exports.BaseTransport = base_1.BaseTransport; -var http_1 = __nccwpck_require__(84490); -exports.HTTPTransport = http_1.HTTPTransport; -var https_1 = __nccwpck_require__(68621); -exports.HTTPSTransport = https_1.HTTPSTransport; -//# sourceMappingURL=index.js.map + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; +} -/***/ }), +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); +} -/***/ 31271: -/***/ ((__unused_webpack_module, exports) => { +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SDK_NAME = 'sentry.javascript.node'; -exports.SDK_VERSION = '5.29.2'; -//# sourceMappingURL=version.js.map /***/ }), -/***/ 81867: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 2848: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var spanstatus_1 = __nccwpck_require__(58522); -var utils_2 = __nccwpck_require__(31386); -var global = utils_1.getGlobalObject(); -/** - * Add a listener that cancels and finishes a transaction when the global - * document is hidden. - */ -function registerBackgroundTabDetection() { - if (global && global.document) { - global.document.addEventListener('visibilitychange', function () { - var activeTransaction = utils_2.getActiveTransaction(); - if (global.document.hidden && activeTransaction) { - utils_1.logger.log("[Tracing] Transaction: " + spanstatus_1.SpanStatus.Cancelled + " -> since tab moved to the background, op: " + activeTransaction.op); - // We should not set status if it is already set, this prevent important statuses like - // error or data loss from being overwritten on transaction. - if (!activeTransaction.status) { - activeTransaction.setStatus(spanstatus_1.SpanStatus.Cancelled); - } - activeTransaction.setTag('visibilitychange', 'document.hidden'); - activeTransaction.finish(); - } - }); - } - else { - utils_1.logger.warn('[Tracing] Could not set up background tab detection due to lack of global document'); - } -} -exports.registerBackgroundTabDetection = registerBackgroundTabDetection; -//# sourceMappingURL=backgroundtab.js.map +"use strict"; -/***/ }), -/***/ 33577: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var common = __nccwpck_require__(44828); +var Type = __nccwpck_require__(57480); -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var hubextensions_1 = __nccwpck_require__(31409); -var idletransaction_1 = __nccwpck_require__(2171); -var spanstatus_1 = __nccwpck_require__(58522); -var utils_2 = __nccwpck_require__(31386); -var backgroundtab_1 = __nccwpck_require__(81867); -var metrics_1 = __nccwpck_require__(68451); -var request_1 = __nccwpck_require__(27854); -var router_1 = __nccwpck_require__(40348); -exports.DEFAULT_MAX_TRANSACTION_DURATION_SECONDS = 600; -var DEFAULT_BROWSER_TRACING_OPTIONS = tslib_1.__assign({ idleTimeout: idletransaction_1.DEFAULT_IDLE_TIMEOUT, markBackgroundTransactions: true, maxTransactionDuration: exports.DEFAULT_MAX_TRANSACTION_DURATION_SECONDS, routingInstrumentation: router_1.defaultRoutingInstrumentation, startTransactionOnLocationChange: true, startTransactionOnPageLoad: true }, request_1.defaultRequestInstrumentationOptions); -/** - * The Browser Tracing integration automatically instruments browser pageload/navigation - * actions as transactions, and captures requests, metrics and errors as spans. - * - * The integration can be configured with a variety of options, and can be extended to use - * any routing library. This integration uses {@see IdleTransaction} to create transactions. - */ -var BrowserTracing = /** @class */ (function () { - function BrowserTracing(_options) { - /** - * @inheritDoc - */ - this.name = BrowserTracing.id; - this._metrics = new metrics_1.MetricsInstrumentation(); - this._emitOptionsWarning = false; - var tracingOrigins = request_1.defaultRequestInstrumentationOptions.tracingOrigins; - // NOTE: Logger doesn't work in constructors, as it's initialized after integrations instances - if (_options && - _options.tracingOrigins && - Array.isArray(_options.tracingOrigins) && - _options.tracingOrigins.length !== 0) { - tracingOrigins = _options.tracingOrigins; - } - else { - this._emitOptionsWarning = true; - } - this.options = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, DEFAULT_BROWSER_TRACING_OPTIONS), _options), { tracingOrigins: tracingOrigins }); - } - /** - * @inheritDoc - */ - BrowserTracing.prototype.setupOnce = function (_, getCurrentHub) { - var _this = this; - this._getCurrentHub = getCurrentHub; - if (this._emitOptionsWarning) { - utils_1.logger.warn('[Tracing] You need to define `tracingOrigins` in the options. Set an array of urls or patterns to trace.'); - utils_1.logger.warn("[Tracing] We added a reasonable default for you: " + request_1.defaultRequestInstrumentationOptions.tracingOrigins); - } - // eslint-disable-next-line @typescript-eslint/unbound-method - var _a = this.options, routingInstrumentation = _a.routingInstrumentation, startTransactionOnLocationChange = _a.startTransactionOnLocationChange, startTransactionOnPageLoad = _a.startTransactionOnPageLoad, markBackgroundTransactions = _a.markBackgroundTransactions, traceFetch = _a.traceFetch, traceXHR = _a.traceXHR, tracingOrigins = _a.tracingOrigins, shouldCreateSpanForRequest = _a.shouldCreateSpanForRequest; - routingInstrumentation(function (context) { return _this._createRouteTransaction(context); }, startTransactionOnPageLoad, startTransactionOnLocationChange); - if (markBackgroundTransactions) { - backgroundtab_1.registerBackgroundTabDetection(); - } - request_1.registerRequestInstrumentation({ traceFetch: traceFetch, traceXHR: traceXHR, tracingOrigins: tracingOrigins, shouldCreateSpanForRequest: shouldCreateSpanForRequest }); - }; - /** Create routing idle transaction. */ - BrowserTracing.prototype._createRouteTransaction = function (context) { - var _this = this; - if (!this._getCurrentHub) { - utils_1.logger.warn("[Tracing] Did not create " + context.op + " transaction because _getCurrentHub is invalid."); - return undefined; - } - // eslint-disable-next-line @typescript-eslint/unbound-method - var _a = this.options, beforeNavigate = _a.beforeNavigate, idleTimeout = _a.idleTimeout, maxTransactionDuration = _a.maxTransactionDuration; - var parentContextFromHeader = context.op === 'pageload' ? getHeaderContext() : undefined; - var expandedContext = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, context), parentContextFromHeader), { trimEnd: true }); - var modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext; - // For backwards compatibility reasons, beforeNavigate can return undefined to "drop" the transaction (prevent it - // from being sent to Sentry). - var finalContext = modifiedContext === undefined ? tslib_1.__assign(tslib_1.__assign({}, expandedContext), { sampled: false }) : modifiedContext; - if (finalContext.sampled === false) { - utils_1.logger.log("[Tracing] Will not send " + finalContext.op + " transaction because of beforeNavigate."); - } - var hub = this._getCurrentHub(); - var idleTransaction = hubextensions_1.startIdleTransaction(hub, finalContext, idleTimeout, true); - utils_1.logger.log("[Tracing] Starting " + finalContext.op + " transaction on scope"); - idleTransaction.registerBeforeFinishCallback(function (transaction, endTimestamp) { - _this._metrics.addPerformanceEntries(transaction); - adjustTransactionDuration(utils_2.secToMs(maxTransactionDuration), transaction, endTimestamp); - }); - return idleTransaction; - }; - /** - * @inheritDoc - */ - BrowserTracing.id = 'BrowserTracing'; - return BrowserTracing; -}()); -exports.BrowserTracing = BrowserTracing; -/** - * Gets transaction context from a sentry-trace meta. - * - * @returns Transaction context data from the header or undefined if there's no header or the header is malformed - */ -function getHeaderContext() { - var header = getMetaContent('sentry-trace'); - if (header) { - return utils_2.extractTraceparentData(header); - } - return undefined; +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); } -exports.getHeaderContext = getHeaderContext; -/** Returns the value of a meta tag */ -function getMetaContent(metaName) { - var el = document.querySelector("meta[name=" + metaName + "]"); - return el ? el.getAttribute('content') : null; + +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); } -exports.getMetaContent = getMetaContent; -/** Adjusts transaction value based on max transaction duration */ -function adjustTransactionDuration(maxDuration, transaction, endTimestamp) { - var diff = endTimestamp - transaction.startTimestamp; - var isOutdatedTransaction = endTimestamp && (diff > maxDuration || diff < 0); - if (isOutdatedTransaction) { - transaction.setStatus(spanstatus_1.SpanStatus.DeadlineExceeded); - transaction.setTag('maxTransactionDurationExceeded', 'true'); - } + +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); } -//# sourceMappingURL=browsertracing.js.map -/***/ }), +function resolveYamlInteger(data) { + if (data === null) return false; -/***/ 71425: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + var max = data.length, + index = 0, + hasDigits = false, + ch; -Object.defineProperty(exports, "__esModule", ({ value: true })); -var browsertracing_1 = __nccwpck_require__(33577); -exports.BrowserTracing = browsertracing_1.BrowserTracing; -//# sourceMappingURL=index.js.map + if (!max) return false; -/***/ }), + ch = data[index]; -/***/ 68451: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var utils_2 = __nccwpck_require__(31386); -var getCLS_1 = __nccwpck_require__(56982); -var getFID_1 = __nccwpck_require__(82496); -var getLCP_1 = __nccwpck_require__(99382); -var getTTFB_1 = __nccwpck_require__(55909); -var getFirstHidden_1 = __nccwpck_require__(88493); -var global = utils_1.getGlobalObject(); -/** Class tracking metrics */ -var MetricsInstrumentation = /** @class */ (function () { - function MetricsInstrumentation() { - this._measurements = {}; - this._performanceCursor = 0; - if (global && global.performance) { - if (global.performance.mark) { - global.performance.mark('sentry-tracing-init'); - } - this._trackCLS(); - this._trackLCP(); - this._trackFID(); - this._trackTTFB(); - } - } - /** Add performance related spans to a transaction */ - MetricsInstrumentation.prototype.addPerformanceEntries = function (transaction) { - var _this = this; - if (!global || !global.performance || !global.performance.getEntries || !utils_1.browserPerformanceTimeOrigin) { - // Gatekeeper if performance API not available - return; - } - utils_1.logger.log('[Tracing] Adding & adjusting spans using Performance API'); - var timeOrigin = utils_2.msToSec(utils_1.browserPerformanceTimeOrigin); - var entryScriptSrc; - if (global.document) { - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (var i = 0; i < document.scripts.length; i++) { - // We go through all scripts on the page and look for 'data-entry' - // We remember the name and measure the time between this script finished loading and - // our mark 'sentry-tracing-init' - if (document.scripts[i].dataset.entry === 'true') { - entryScriptSrc = document.scripts[i].src; - break; - } - } - } - var entryScriptStartTimestamp; - var tracingInitMarkStartTime; - global.performance - .getEntries() - .slice(this._performanceCursor) - .forEach(function (entry) { - var startTime = utils_2.msToSec(entry.startTime); - var duration = utils_2.msToSec(entry.duration); - if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) { - return; - } - switch (entry.entryType) { - case 'navigation': - addNavigationSpans(transaction, entry, timeOrigin); - break; - case 'mark': - case 'paint': - case 'measure': { - var startTimestamp = addMeasureSpans(transaction, entry, startTime, duration, timeOrigin); - if (tracingInitMarkStartTime === undefined && entry.name === 'sentry-tracing-init') { - tracingInitMarkStartTime = startTimestamp; - } - // capture web vitals - var firstHidden = getFirstHidden_1.getFirstHidden(); - // Only report if the page wasn't hidden prior to the web vital. - var shouldRecord = entry.startTime < firstHidden.timeStamp; - if (entry.name === 'first-paint' && shouldRecord) { - utils_1.logger.log('[Measurements] Adding FP'); - _this._measurements['fp'] = { value: entry.startTime }; - _this._measurements['mark.fp'] = { value: startTimestamp }; - } - if (entry.name === 'first-contentful-paint' && shouldRecord) { - utils_1.logger.log('[Measurements] Adding FCP'); - _this._measurements['fcp'] = { value: entry.startTime }; - _this._measurements['mark.fcp'] = { value: startTimestamp }; - } - break; - } - case 'resource': { - var resourceName = entry.name.replace(window.location.origin, ''); - var endTimestamp = addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin); - // We remember the entry script end time to calculate the difference to the first init mark - if (entryScriptStartTimestamp === undefined && (entryScriptSrc || '').indexOf(resourceName) > -1) { - entryScriptStartTimestamp = endTimestamp; - } - break; - } - default: - // Ignore other entry types. - } - }); - if (entryScriptStartTimestamp !== undefined && tracingInitMarkStartTime !== undefined) { - _startChild(transaction, { - description: 'evaluation', - endTimestamp: tracingInitMarkStartTime, - op: 'script', - startTimestamp: entryScriptStartTimestamp, - }); - } - this._performanceCursor = Math.max(performance.getEntries().length - 1, 0); - this._trackNavigator(transaction); - // Measurements are only available for pageload transactions - if (transaction.op === 'pageload') { - // normalize applicable web vital values to be relative to transaction.startTimestamp - var timeOrigin_1 = utils_2.msToSec(utils_1.browserPerformanceTimeOrigin); - ['fcp', 'fp', 'lcp', 'ttfb'].forEach(function (name) { - if (!_this._measurements[name] || timeOrigin_1 >= transaction.startTimestamp) { - return; - } - // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin. - // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need - // to be adjusted to be relative to transaction.startTimestamp. - var oldValue = _this._measurements[name].value; - var measurementTimestamp = timeOrigin_1 + utils_2.msToSec(oldValue); - // normalizedValue should be in milliseconds - var normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000); - var delta = normalizedValue - oldValue; - utils_1.logger.log("[Measurements] Normalized " + name + " from " + oldValue + " to " + normalizedValue + " (" + delta + ")"); - _this._measurements[name].value = normalizedValue; - }); - if (this._measurements['mark.fid'] && this._measurements['fid']) { - // create span for FID - _startChild(transaction, { - description: 'first input delay', - endTimestamp: this._measurements['mark.fid'].value + utils_2.msToSec(this._measurements['fid'].value), - op: 'web.vitals', - startTimestamp: this._measurements['mark.fid'].value, - }); - } - transaction.setMeasurements(this._measurements); - } - }; - /** Starts tracking the Cumulative Layout Shift on the current page. */ - MetricsInstrumentation.prototype._trackCLS = function () { - var _this = this; - getCLS_1.getCLS(function (metric) { - var entry = metric.entries.pop(); - if (!entry) { - return; - } - utils_1.logger.log('[Measurements] Adding CLS'); - _this._measurements['cls'] = { value: metric.value }; - }); - }; - /** - * Capture the information of the user agent. - */ - MetricsInstrumentation.prototype._trackNavigator = function (transaction) { - var navigator = global.navigator; - if (!navigator) { - return; - } - // track network connectivity - var connection = navigator.connection; - if (connection) { - if (connection.effectiveType) { - transaction.setTag('effectiveConnectionType', connection.effectiveType); - } - if (connection.type) { - transaction.setTag('connectionType', connection.type); - } - if (isMeasurementValue(connection.rtt)) { - this._measurements['connection.rtt'] = { value: connection.rtt }; - } - if (isMeasurementValue(connection.downlink)) { - this._measurements['connection.downlink'] = { value: connection.downlink }; - } - } - if (isMeasurementValue(navigator.deviceMemory)) { - transaction.setTag('deviceMemory', String(navigator.deviceMemory)); - } - if (isMeasurementValue(navigator.hardwareConcurrency)) { - transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency)); - } - }; - /** Starts tracking the Largest Contentful Paint on the current page. */ - MetricsInstrumentation.prototype._trackLCP = function () { - var _this = this; - getLCP_1.getLCP(function (metric) { - var entry = metric.entries.pop(); - if (!entry) { - return; - } - var timeOrigin = utils_2.msToSec(performance.timeOrigin); - var startTime = utils_2.msToSec(entry.startTime); - utils_1.logger.log('[Measurements] Adding LCP'); - _this._measurements['lcp'] = { value: metric.value }; - _this._measurements['mark.lcp'] = { value: timeOrigin + startTime }; - }); - }; - /** Starts tracking the First Input Delay on the current page. */ - MetricsInstrumentation.prototype._trackFID = function () { - var _this = this; - getFID_1.getFID(function (metric) { - var entry = metric.entries.pop(); - if (!entry) { - return; - } - var timeOrigin = utils_2.msToSec(performance.timeOrigin); - var startTime = utils_2.msToSec(entry.startTime); - utils_1.logger.log('[Measurements] Adding FID'); - _this._measurements['fid'] = { value: metric.value }; - _this._measurements['mark.fid'] = { value: timeOrigin + startTime }; - }); - }; - /** Starts tracking the Time to First Byte on the current page. */ - MetricsInstrumentation.prototype._trackTTFB = function () { - var _this = this; - getTTFB_1.getTTFB(function (metric) { - var _a; - var entry = metric.entries.pop(); - if (!entry) { - return; - } - utils_1.logger.log('[Measurements] Adding TTFB'); - _this._measurements['ttfb'] = { value: metric.value }; - // Capture the time spent making the request and receiving the first byte of the response - var requestTime = metric.value - (_a = metric.entries[0], (_a !== null && _a !== void 0 ? _a : entry)).requestStart; - _this._measurements['ttfb.requestTime'] = { value: requestTime }; - }); - }; - return MetricsInstrumentation; -}()); -exports.MetricsInstrumentation = MetricsInstrumentation; -/** Instrument navigation entries */ -function addNavigationSpans(transaction, entry, timeOrigin) { - addPerformanceNavigationTiming(transaction, entry, 'unloadEvent', timeOrigin); - addPerformanceNavigationTiming(transaction, entry, 'redirect', timeOrigin); - addPerformanceNavigationTiming(transaction, entry, 'domContentLoadedEvent', timeOrigin); - addPerformanceNavigationTiming(transaction, entry, 'loadEvent', timeOrigin); - addPerformanceNavigationTiming(transaction, entry, 'connect', timeOrigin); - addPerformanceNavigationTiming(transaction, entry, 'secureConnection', timeOrigin, 'connectEnd'); - addPerformanceNavigationTiming(transaction, entry, 'fetch', timeOrigin, 'domainLookupStart'); - addPerformanceNavigationTiming(transaction, entry, 'domainLookup', timeOrigin); - addRequest(transaction, entry, timeOrigin); -} -/** Create measure related spans */ -function addMeasureSpans(transaction, entry, startTime, duration, timeOrigin) { - var measureStartTimestamp = timeOrigin + startTime; - var measureEndTimestamp = measureStartTimestamp + duration; - _startChild(transaction, { - description: entry.name, - endTimestamp: measureEndTimestamp, - op: entry.entryType, - startTimestamp: measureStartTimestamp, - }); - return measureStartTimestamp; -} -/** Create resource related spans */ -function addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin) { - // we already instrument based on fetch and xhr, so we don't need to - // duplicate spans here. - if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') { - return undefined; - } - var data = {}; - if ('transferSize' in entry) { - data['Transfer Size'] = entry.transferSize; + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; + + // base 2, base 8, base 16 + + if (ch === 'b') { + // base 2 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; } - if ('encodedBodySize' in entry) { - data['Encoded Body Size'] = entry.encodedBodySize; + + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; } - if ('decodedBodySize' in entry) { - data['Decoded Body Size'] = entry.decodedBodySize; + + + if (ch === 'o') { + // base 8 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; } - var startTimestamp = timeOrigin + startTime; - var endTimestamp = startTimestamp + duration; - _startChild(transaction, { - description: resourceName, - endTimestamp: endTimestamp, - op: entry.initiatorType ? "resource." + entry.initiatorType : 'resource', - startTimestamp: startTimestamp, - data: data, - }); - return endTimestamp; -} -exports.addResourceSpans = addResourceSpans; -/** Create performance navigation related spans */ -function addPerformanceNavigationTiming(transaction, entry, event, timeOrigin, eventEnd) { - var end = eventEnd ? entry[eventEnd] : entry[event + "End"]; - var start = entry[event + "Start"]; - if (!start || !end) { - return; + } + + // base 10 (except 0) + + // value should not start with `_`; + if (ch === '_') return false; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isDecCode(data.charCodeAt(index))) { + return false; } - _startChild(transaction, { - description: event, - endTimestamp: timeOrigin + utils_2.msToSec(end), - op: 'browser', - startTimestamp: timeOrigin + utils_2.msToSec(start), - }); + hasDigits = true; + } + + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; + + return true; } -/** Create request and response related spans */ -function addRequest(transaction, entry, timeOrigin) { - _startChild(transaction, { - description: 'request', - endTimestamp: timeOrigin + utils_2.msToSec(entry.responseEnd), - op: 'browser', - startTimestamp: timeOrigin + utils_2.msToSec(entry.requestStart), - }); - _startChild(transaction, { - description: 'response', - endTimestamp: timeOrigin + utils_2.msToSec(entry.responseEnd), - op: 'browser', - startTimestamp: timeOrigin + utils_2.msToSec(entry.responseStart), - }); + +function constructYamlInteger(data) { + var value = data, sign = 1, ch; + + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } + + ch = value[0]; + + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; + } + + if (value === '0') return 0; + + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value.slice(2), 16); + if (value[1] === 'o') return sign * parseInt(value.slice(2), 8); + } + + return sign * parseInt(value, 10); } -/** - * Helper function to start child on transactions. This function will make sure that the transaction will - * use the start timestamp of the created child span if it is earlier than the transactions actual - * start timestamp. - */ -function _startChild(transaction, _a) { - var startTimestamp = _a.startTimestamp, ctx = tslib_1.__rest(_a, ["startTimestamp"]); - if (startTimestamp && transaction.startTimestamp > startTimestamp) { - transaction.startTimestamp = startTimestamp; - } - return transaction.startChild(tslib_1.__assign({ startTimestamp: startTimestamp }, ctx)); + +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); } -exports._startChild = _startChild; -/** - * Checks if a given value is a valid measurement value. - */ -function isMeasurementValue(value) { - return typeof value === 'number' && isFinite(value); + +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0o' + obj.toString(8) : '-0o' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] + } +}); + + +/***/ }), + +/***/ 74352: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Type = __nccwpck_require__(57480); + +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); + + +/***/ }), + +/***/ 70884: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Type = __nccwpck_require__(57480); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; } -//# sourceMappingURL=metrics.js.map + +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); + /***/ }), -/***/ 27854: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 61002: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); -var utils_2 = __nccwpck_require__(31386); -exports.DEFAULT_TRACING_ORIGINS = ['localhost', /^\//]; -exports.defaultRequestInstrumentationOptions = { - traceFetch: true, - traceXHR: true, - tracingOrigins: exports.DEFAULT_TRACING_ORIGINS, -}; -/** Registers span creators for xhr and fetch requests */ -function registerRequestInstrumentation(_options) { - // eslint-disable-next-line @typescript-eslint/unbound-method - var _a = tslib_1.__assign(tslib_1.__assign({}, exports.defaultRequestInstrumentationOptions), _options), traceFetch = _a.traceFetch, traceXHR = _a.traceXHR, tracingOrigins = _a.tracingOrigins, shouldCreateSpanForRequest = _a.shouldCreateSpanForRequest; - // We should cache url -> decision so that we don't have to compute - // regexp everytime we create a request. - var urlMap = {}; - var defaultShouldCreateSpan = function (url) { - if (urlMap[url]) { - return urlMap[url]; - } - var origins = tracingOrigins; - urlMap[url] = - origins.some(function (origin) { return utils_1.isMatchingPattern(url, origin); }) && - !utils_1.isMatchingPattern(url, 'sentry_key'); - return urlMap[url]; - }; - // We want that our users don't have to re-implement shouldCreateSpanForRequest themselves - // That's why we filter out already unwanted Spans from tracingOrigins - var shouldCreateSpan = defaultShouldCreateSpan; - if (typeof shouldCreateSpanForRequest === 'function') { - shouldCreateSpan = function (url) { - return defaultShouldCreateSpan(url) && shouldCreateSpanForRequest(url); - }; - } - var spans = {}; - if (traceFetch) { - utils_1.addInstrumentationHandler({ - callback: function (handlerData) { - fetchCallback(handlerData, shouldCreateSpan, spans); - }, - type: 'fetch', - }); - } - if (traceXHR) { - utils_1.addInstrumentationHandler({ - callback: function (handlerData) { - xhrCallback(handlerData, shouldCreateSpan, spans); - }, - type: 'xhr', - }); - } +"use strict"; + + +var Type = __nccwpck_require__(57480); + +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); } -exports.registerRequestInstrumentation = registerRequestInstrumentation; -/** - * Create and track fetch request spans - */ -function fetchCallback(handlerData, shouldCreateSpan, spans) { - var _a; - var currentClientOptions = (_a = hub_1.getCurrentHub() - .getClient()) === null || _a === void 0 ? void 0 : _a.getOptions(); - if (!(currentClientOptions && utils_2.hasTracingEnabled(currentClientOptions)) || - !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) { - return; - } - if (handlerData.endTimestamp && handlerData.fetchData.__span) { - var span = spans[handlerData.fetchData.__span]; - if (span) { - var response = handlerData.response; - if (response) { - // TODO (kmclb) remove this once types PR goes through - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - span.setHttpStatus(response.status); - } - span.finish(); - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete spans[handlerData.fetchData.__span]; - } - return; - } - var activeTransaction = utils_2.getActiveTransaction(); - if (activeTransaction) { - var span = activeTransaction.startChild({ - data: tslib_1.__assign(tslib_1.__assign({}, handlerData.fetchData), { type: 'fetch' }), - description: handlerData.fetchData.method + " " + handlerData.fetchData.url, - op: 'http', - }); - handlerData.fetchData.__span = span.spanId; - spans[span.spanId] = span; - var request = (handlerData.args[0] = handlerData.args[0]); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var options = (handlerData.args[1] = handlerData.args[1] || {}); - var headers = options.headers; - if (utils_1.isInstanceOf(request, Request)) { - headers = request.headers; - } - if (headers) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (typeof headers.append === 'function') { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - headers.append('sentry-trace', span.toTraceparent()); - } - else if (Array.isArray(headers)) { - headers = tslib_1.__spread(headers, [['sentry-trace', span.toTraceparent()]]); - } - else { - headers = tslib_1.__assign(tslib_1.__assign({}, headers), { 'sentry-trace': span.toTraceparent() }); - } - } - else { - headers = { 'sentry-trace': span.toTraceparent() }; - } - options.headers = headers; - } + +function constructYamlNull() { + return null; } -exports.fetchCallback = fetchCallback; -/** - * Create and track xhr request spans - */ -function xhrCallback(handlerData, shouldCreateSpan, spans) { - var _a; - var currentClientOptions = (_a = hub_1.getCurrentHub() - .getClient()) === null || _a === void 0 ? void 0 : _a.getOptions(); - if (!(currentClientOptions && utils_2.hasTracingEnabled(currentClientOptions)) || - !(handlerData.xhr && handlerData.xhr.__sentry_xhr__ && shouldCreateSpan(handlerData.xhr.__sentry_xhr__.url)) || - handlerData.xhr.__sentry_own_request__) { - return; - } - var xhr = handlerData.xhr.__sentry_xhr__; - // check first if the request has finished and is tracked by an existing span which should now end - if (handlerData.endTimestamp && handlerData.xhr.__sentry_xhr_span_id__) { - var span = spans[handlerData.xhr.__sentry_xhr_span_id__]; - if (span) { - span.setHttpStatus(xhr.status_code); - span.finish(); - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete spans[handlerData.xhr.__sentry_xhr_span_id__]; - } - return; - } - // if not, create a new span to track it - var activeTransaction = utils_2.getActiveTransaction(); - if (activeTransaction) { - var span = activeTransaction.startChild({ - data: tslib_1.__assign(tslib_1.__assign({}, xhr.data), { type: 'xhr', method: xhr.method, url: xhr.url }), - description: xhr.method + " " + xhr.url, - op: 'http', - }); - handlerData.xhr.__sentry_xhr_span_id__ = span.spanId; - spans[handlerData.xhr.__sentry_xhr_span_id__] = span; - if (handlerData.xhr.setRequestHeader) { - try { - handlerData.xhr.setRequestHeader('sentry-trace', span.toTraceparent()); - } - catch (_) { - // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED. - } - } - } + +function isNull(object) { + return object === null; } -exports.xhrCallback = xhrCallback; -//# sourceMappingURL=request.js.map + +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; }, + empty: function () { return ''; } + }, + defaultStyle: 'lowercase' +}); + /***/ }), -/***/ 40348: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 65894: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var global = utils_1.getGlobalObject(); -/** - * Default function implementing pageload and navigation transactions - */ -function defaultRoutingInstrumentation(startTransaction, startTransactionOnPageLoad, startTransactionOnLocationChange) { - if (startTransactionOnPageLoad === void 0) { startTransactionOnPageLoad = true; } - if (startTransactionOnLocationChange === void 0) { startTransactionOnLocationChange = true; } - if (!global || !global.location) { - utils_1.logger.warn('Could not initialize routing instrumentation due to invalid location'); - return; - } - var startingUrl = global.location.href; - var activeTransaction; - if (startTransactionOnPageLoad) { - activeTransaction = startTransaction({ name: global.location.pathname, op: 'pageload' }); - } - if (startTransactionOnLocationChange) { - utils_1.addInstrumentationHandler({ - callback: function (_a) { - var to = _a.to, from = _a.from; - /** - * This early return is there to account for some cases where a navigation transaction starts right after - * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't - * create an uneccessary navigation transaction. - * - * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also - * only be caused in certain development environments where the usage of a hot module reloader is causing - * errors. - */ - if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) { - startingUrl = undefined; - return; - } - if (from !== to) { - startingUrl = undefined; - if (activeTransaction) { - utils_1.logger.log("[Tracing] Finishing current transaction with op: " + activeTransaction.op); - // If there's an open transaction on the scope, we need to finish it before creating an new one. - activeTransaction.finish(); - } - activeTransaction = startTransaction({ name: global.location.pathname, op: 'navigation' }); - } - }, - type: 'history', - }); +"use strict"; + + +var Type = __nccwpck_require__(57480); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; + +function resolveYamlOmap(data) { + if (data === null) return true; + + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; + + if (_toString.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; + } } + + if (!pairHasKey) return false; + + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; + } + + return true; } -exports.defaultRoutingInstrumentation = defaultRoutingInstrumentation; -//# sourceMappingURL=router.js.map + +function constructYamlOmap(data) { + return data !== null ? data : []; +} + +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); + /***/ }), -/***/ 56982: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 18978: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Type = __nccwpck_require__(57480); + +var _toString = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; +} + +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; +} + +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs +}); -/* - * Copyright 2020 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 - * - * https://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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var bindReporter_1 = __nccwpck_require__(54592); -var initMetric_1 = __nccwpck_require__(45300); -var observe_1 = __nccwpck_require__(17984); -var onHidden_1 = __nccwpck_require__(9658); -exports.getCLS = function (onReport, reportAllChanges) { - if (reportAllChanges === void 0) { reportAllChanges = false; } - var metric = initMetric_1.initMetric('CLS', 0); - var report; - var entryHandler = function (entry) { - // Only count layout shifts without recent user input. - if (!entry.hadRecentInput) { - metric.value += entry.value; - metric.entries.push(entry); - report(); - } - }; - var po = observe_1.observe('layout-shift', entryHandler); - if (po) { - report = bindReporter_1.bindReporter(onReport, metric, po, reportAllChanges); - onHidden_1.onHidden(function (_a) { - var isUnloading = _a.isUnloading; - po.takeRecords().map(entryHandler); - if (isUnloading) { - metric.isFinal = true; - } - report(); - }); - } -}; -//# sourceMappingURL=getCLS.js.map /***/ }), -/***/ 82496: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 89695: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* - * Copyright 2020 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 - * - * https://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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var bindReporter_1 = __nccwpck_require__(54592); -var getFirstHidden_1 = __nccwpck_require__(88493); -var initMetric_1 = __nccwpck_require__(45300); -var observe_1 = __nccwpck_require__(17984); -var onHidden_1 = __nccwpck_require__(9658); -exports.getFID = function (onReport) { - var metric = initMetric_1.initMetric('FID'); - var firstHidden = getFirstHidden_1.getFirstHidden(); - var entryHandler = function (entry) { - // Only report if the page wasn't hidden prior to the first input. - if (entry.startTime < firstHidden.timeStamp) { - metric.value = entry.processingStart - entry.startTime; - metric.entries.push(entry); - metric.isFinal = true; - report(); - } - }; - var po = observe_1.observe('first-input', entryHandler); - var report = bindReporter_1.bindReporter(onReport, metric, po); - if (po) { - onHidden_1.onHidden(function () { - po.takeRecords().map(entryHandler); - po.disconnect(); - }, true); - } - else { - if (window.perfMetrics && window.perfMetrics.onFirstInputDelay) { - window.perfMetrics.onFirstInputDelay(function (value, event) { - // Only report if the page wasn't hidden prior to the first input. - if (event.timeStamp < firstHidden.timeStamp) { - metric.value = value; - metric.isFinal = true; - metric.entries = [ - { - entryType: 'first-input', - name: event.type, - target: event.target, - cancelable: event.cancelable, - startTime: event.timeStamp, - processingStart: event.timeStamp + value, - }, - ]; - report(); - } - }); - } - } -}; -//# sourceMappingURL=getFID.js.map +"use strict"; -/***/ }), -/***/ 99382: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +var Type = __nccwpck_require__(57480); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } +}); -/* - * Copyright 2020 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 - * - * https://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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var bindReporter_1 = __nccwpck_require__(54592); -var getFirstHidden_1 = __nccwpck_require__(88493); -var initMetric_1 = __nccwpck_require__(45300); -var observe_1 = __nccwpck_require__(17984); -var onHidden_1 = __nccwpck_require__(9658); -var whenInput_1 = __nccwpck_require__(45181); -exports.getLCP = function (onReport, reportAllChanges) { - if (reportAllChanges === void 0) { reportAllChanges = false; } - var metric = initMetric_1.initMetric('LCP'); - var firstHidden = getFirstHidden_1.getFirstHidden(); - var report; - var entryHandler = function (entry) { - // The startTime attribute returns the value of the renderTime if it is not 0, - // and the value of the loadTime otherwise. - var value = entry.startTime; - // If the page was hidden prior to paint time of the entry, - // ignore it and mark the metric as final, otherwise add the entry. - if (value < firstHidden.timeStamp) { - metric.value = value; - metric.entries.push(entry); - } - else { - metric.isFinal = true; - } - report(); - }; - var po = observe_1.observe('largest-contentful-paint', entryHandler); - if (po) { - report = bindReporter_1.bindReporter(onReport, metric, po, reportAllChanges); - var onFinal = function () { - if (!metric.isFinal) { - po.takeRecords().map(entryHandler); - metric.isFinal = true; - report(); - } - }; - void whenInput_1.whenInput().then(onFinal); - onHidden_1.onHidden(onFinal, true); - } -}; -//# sourceMappingURL=getLCP.js.map /***/ }), -/***/ 55909: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 87424: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* - * Copyright 2020 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 - * - * https://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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -var initMetric_1 = __nccwpck_require__(45300); -var global = utils_1.getGlobalObject(); -var afterLoad = function (callback) { - if (document.readyState === 'complete') { - // Queue a task so the callback runs after `loadEventEnd`. - setTimeout(callback, 0); - } - else { - // Use `pageshow` so the callback runs after `loadEventEnd`. - addEventListener('pageshow', callback); - } -}; -var getNavigationEntryFromPerformanceTiming = function () { - // Really annoying that TypeScript errors when using `PerformanceTiming`. - // eslint-disable-next-line deprecation/deprecation - var timing = global.performance.timing; - var navigationEntry = { - entryType: 'navigation', - startTime: 0, - }; - for (var key in timing) { - if (key !== 'navigationStart' && key !== 'toJSON') { - navigationEntry[key] = Math.max(timing[key] - timing.navigationStart, 0); - } +"use strict"; + + +var Type = __nccwpck_require__(57480); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; } - return navigationEntry; -}; -exports.getTTFB = function (onReport) { - var metric = initMetric_1.initMetric('TTFB'); - afterLoad(function () { - try { - // Use the NavigationTiming L2 entry if available. - var navigationEntry = global.performance.getEntriesByType('navigation')[0] || getNavigationEntryFromPerformanceTiming(); - metric.value = metric.delta = navigationEntry.responseStart; - metric.entries = [navigationEntry]; - onReport(metric); - } - catch (error) { - // Do nothing. - } - }); -}; -//# sourceMappingURL=getTTFB.js.map + } -/***/ }), + return true; +} -/***/ 54592: -/***/ ((__unused_webpack_module, exports) => { +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); -/* - * Copyright 2020 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 - * - * https://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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.bindReporter = function (callback, metric, po, observeAllUpdates) { - var prevValue; - return function () { - if (po && metric.isFinal) { - po.disconnect(); - } - if (metric.value >= 0) { - if (observeAllUpdates || metric.isFinal || document.visibilityState === 'hidden') { - metric.delta = metric.value - (prevValue || 0); - // Report the metric if there's a non-zero delta, if the metric is - // final, or if no previous value exists (which can happen in the case - // of the document becoming hidden when the metric value is 0). - // See: https://github.com/GoogleChrome/web-vitals/issues/14 - if (metric.delta || metric.isFinal || prevValue === undefined) { - callback(metric); - prevValue = metric.value; - } - } - } - }; -}; -//# sourceMappingURL=bindReporter.js.map /***/ }), -/***/ 70093: -/***/ ((__unused_webpack_module, exports) => { +/***/ 32568: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Type = __nccwpck_require__(57480); + +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); -/* - * Copyright 2020 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 - * - * https://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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Performantly generate a unique, 27-char string by combining the current - * timestamp with a 13-digit random number. - * @return {string} - */ -exports.generateUniqueID = function () { - return Date.now() + "-" + (Math.floor(Math.random() * (9e12 - 1)) + 1e12); -}; -//# sourceMappingURL=generateUniqueID.js.map /***/ }), -/***/ 88493: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 9561: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* - * Copyright 2020 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 - * - * https://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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var onHidden_1 = __nccwpck_require__(9658); -var firstHiddenTime; -exports.getFirstHidden = function () { - if (firstHiddenTime === undefined) { - // If the document is hidden when this code runs, assume it was hidden - // since navigation start. This isn't a perfect heuristic, but it's the - // best we can do until an API is available to support querying past - // visibilityState. - firstHiddenTime = document.visibilityState === 'hidden' ? 0 : Infinity; - // Update the time if/when the document becomes hidden. - onHidden_1.onHidden(function (_a) { - var timeStamp = _a.timeStamp; - return (firstHiddenTime = timeStamp); - }, true); +"use strict"; + + +var Type = __nccwpck_require__(57480); + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; +} + +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; + + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + + if (match === null) throw new Error('Date resolve error'); + + // match: [1] year [2] month [3] day + + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); + + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } + + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; } - return { - get timeStamp() { - return firstHiddenTime; - }, - }; -}; -//# sourceMappingURL=getFirstHidden.js.map + fraction = +fraction; + } -/***/ }), + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute -/***/ 45300: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } + + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); + + if (delta) date.setTime(date.getTime() - delta); + + return date; +} + +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); +} + +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); -/* - * Copyright 2020 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 - * - * https://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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var generateUniqueID_1 = __nccwpck_require__(70093); -exports.initMetric = function (name, value) { - if (value === void 0) { value = -1; } - return { - name: name, - value: value, - delta: 0, - entries: [], - id: generateUniqueID_1.generateUniqueID(), - isFinal: false, - }; -}; -//# sourceMappingURL=initMetric.js.map /***/ }), -/***/ 17984: -/***/ ((__unused_webpack_module, exports) => { +/***/ 39662: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = { getTransformStream }; + +const { Transform } = __nccwpck_require__(51642); + +const prettyFactory = __nccwpck_require__(31691); +const Sentry = __nccwpck_require__(22783); + +const LEVEL_MAP = { + 10: "trace", + 20: "debug", + 30: "info", + 40: "warn", + 50: "error", + 60: "fatal", +}; -/* - * Copyright 2020 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 - * - * https://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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); /** - * Takes a performance entry type and a callback function, and creates a - * `PerformanceObserver` instance that will observe the specified entry type - * with buffering enabled and call the callback _for each entry_. + * Implements Probot's default logging formatting and error captionaing using Sentry. * - * This function also feature-detects entry support and wraps the logic in a - * try/catch to avoid errors in unsupporting browsers. + * @param {import("./").Options} options + * @returns Transform + * @see https://getpino.io/#/docs/transports */ -exports.observe = function (type, callback) { - try { - if (PerformanceObserver.supportedEntryTypes.includes(type)) { - var po = new PerformanceObserver(function (l) { return l.getEntries().map(callback); }); - po.observe({ type: type, buffered: true }); - return po; +function getTransformStream(options = {}) { + const formattingEnabled = options.logFormat !== "json"; + + const levelAsString = options.logLevelInString; + const sentryEnabled = !!options.sentryDsn; + + if (sentryEnabled) { + Sentry.init({ + dsn: options.sentryDsn, + // See https://github.com/getsentry/sentry-javascript/issues/1964#issuecomment-688482615 + // 6 is enough to serialize the deepest property across all GitHub Event payloads + normalizeDepth: 6, + }); + } + + const pretty = prettyFactory({ + ignore: [ + // default pino keys + "time", + "pid", + "hostname", + // remove keys from pino-http + "req", + "res", + "responseTime", + ].join(","), + errorProps: ["event", "status", "headers", "request", "sentryEventId"].join( + "," + ), + }); + + return new Transform({ + objectMode: true, + transform(chunk, enc, cb) { + const line = chunk.toString().trim(); + + /* istanbul ignore if */ + if (line === undefined) return cb(); + + const data = sentryEnabled ? JSON.parse(line) : null; + + if (!sentryEnabled || data.level < 50) { + if (formattingEnabled) { + return cb(null, pretty(line)); } - } - catch (e) { - // Do nothing. - } - return; -}; -//# sourceMappingURL=observe.js.map -/***/ }), + if (levelAsString) { + return cb(null, stringifyLogLevel(JSON.parse(line))); + } -/***/ 9658: -/***/ ((__unused_webpack_module, exports) => { + cb(null, line + "\n"); + return; + } -/* - * Copyright 2020 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 - * - * https://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. - */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -var isUnloading = false; -var listenersAdded = false; -var onPageHide = function (event) { - isUnloading = !event.persisted; -}; -var addListeners = function () { - addEventListener('pagehide', onPageHide); - // `beforeunload` is needed to fix this bug: - // https://bugs.chromium.org/p/chromium/issues/detail?id=987409 - // eslint-disable-next-line @typescript-eslint/no-empty-function - addEventListener('beforeunload', function () { }); -}; -exports.onHidden = function (cb, once) { - if (once === void 0) { once = false; } - if (!listenersAdded) { - addListeners(); - listenersAdded = true; - } - addEventListener('visibilitychange', function (_a) { - var timeStamp = _a.timeStamp; - if (document.visibilityState === 'hidden') { - cb({ timeStamp: timeStamp, isUnloading: isUnloading }); + Sentry.withScope(function (scope) { + const sentryLevelName = + data.level === 50 ? Sentry.Severity.Error : Sentry.Severity.Fatal; + scope.setLevel(sentryLevelName); + + for (const extra of ["event", "headers", "request", "status"]) { + if (!data[extra]) continue; + + scope.setExtra(extra, data[extra]); } - }, { capture: true, once: once }); -}; -//# sourceMappingURL=onHidden.js.map + + // set user id and username to installation ID and account login + if (data.event && data.event.payload) { + const { + // When GitHub App is installed organization wide + installation: { id, account: { login: account } = {} } = {}, + + // When the repository belongs to an organization + organization: { login: organization } = {}, + // When the repository belongs to a user + repository: { owner: { login: owner } = {} } = {}, + } = data.event.payload; + + scope.setUser({ + id: id, + username: account || organization || owner, + }); + } + + const sentryEventId = Sentry.captureException(toSentryError(data)); + + // reduce logging data and add reference to sentry event instead + if (data.event) { + data.event = { id: data.event.id }; + } + if (data.request) { + data.request = { + method: data.request.method, + url: data.request.url, + }; + } + data.sentryEventId = sentryEventId; + + if (formattingEnabled) { + return cb(null, pretty(data)); + } + + // istanbul ignore if + if (levelAsString) { + return cb(null, stringifyLogLevel(data)); + } + + cb(null, JSON.stringify(data) + "\n"); + }); + }, + }); +} + +function stringifyLogLevel(data) { + data.level = LEVEL_MAP[data.level]; + return JSON.stringify(data) + "\n"; +} + +function toSentryError(data) { + const error = new Error(data.msg); + error.name = data.type; + error.stack = data.stack; + return error; +} + /***/ }), -/***/ 45181: -/***/ ((__unused_webpack_module, exports) => { +/***/ 90785: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* - * Copyright 2020 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 - * - * https://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. - */ Object.defineProperty(exports, "__esModule", ({ value: true })); -var inputPromise; -exports.whenInput = function () { - if (!inputPromise) { - inputPromise = new Promise(function (r) { - return ['scroll', 'keydown', 'pointerdown'].map(function (type) { - addEventListener(type, r, { - once: true, - passive: true, - capture: true, - }); - }); - }); +var utils_1 = __nccwpck_require__(1620); +var SENTRY_API_VERSION = '7'; +/** + * Helper class to provide urls, headers and metadata that can be used to form + * different types of requests to Sentry endpoints. + * Supports both envelopes and regular event requests. + **/ +var API = /** @class */ (function () { + /** Create a new instance of API */ + function API(dsn, metadata, tunnel) { + if (metadata === void 0) { metadata = {}; } + this.dsn = dsn; + this._dsnObject = new utils_1.Dsn(dsn); + this.metadata = metadata; + this._tunnel = tunnel; } - return inputPromise; -}; -//# sourceMappingURL=whenInput.js.map + /** Returns the Dsn object. */ + API.prototype.getDsn = function () { + return this._dsnObject; + }; + /** Does this transport force envelopes? */ + API.prototype.forceEnvelope = function () { + return !!this._tunnel; + }; + /** Returns the prefix to construct Sentry ingestion API endpoints. */ + API.prototype.getBaseApiEndpoint = function () { + var dsn = this.getDsn(); + var protocol = dsn.protocol ? dsn.protocol + ":" : ''; + var port = dsn.port ? ":" + dsn.port : ''; + return protocol + "//" + dsn.host + port + (dsn.path ? "/" + dsn.path : '') + "/api/"; + }; + /** Returns the store endpoint URL. */ + API.prototype.getStoreEndpoint = function () { + return this._getIngestEndpoint('store'); + }; + /** + * Returns the store endpoint URL with auth in the query string. + * + * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. + */ + API.prototype.getStoreEndpointWithUrlEncodedAuth = function () { + return this.getStoreEndpoint() + "?" + this._encodedAuth(); + }; + /** + * Returns the envelope endpoint URL with auth in the query string. + * + * Sending auth as part of the query string and not as custom HTTP headers avoids CORS preflight requests. + */ + API.prototype.getEnvelopeEndpointWithUrlEncodedAuth = function () { + if (this.forceEnvelope()) { + return this._tunnel; + } + return this._getEnvelopeEndpoint() + "?" + this._encodedAuth(); + }; + /** Returns only the path component for the store endpoint. */ + API.prototype.getStoreEndpointPath = function () { + var dsn = this.getDsn(); + return (dsn.path ? "/" + dsn.path : '') + "/api/" + dsn.projectId + "/store/"; + }; + /** + * Returns an object that can be used in request headers. + * This is needed for node and the old /store endpoint in sentry + */ + API.prototype.getRequestHeaders = function (clientName, clientVersion) { + // CHANGE THIS to use metadata but keep clientName and clientVersion compatible + var dsn = this.getDsn(); + var header = ["Sentry sentry_version=" + SENTRY_API_VERSION]; + header.push("sentry_client=" + clientName + "/" + clientVersion); + header.push("sentry_key=" + dsn.publicKey); + if (dsn.pass) { + header.push("sentry_secret=" + dsn.pass); + } + return { + 'Content-Type': 'application/json', + 'X-Sentry-Auth': header.join(', '), + }; + }; + /** Returns the url to the report dialog endpoint. */ + API.prototype.getReportDialogEndpoint = function (dialogOptions) { + if (dialogOptions === void 0) { dialogOptions = {}; } + var dsn = this.getDsn(); + var endpoint = this.getBaseApiEndpoint() + "embed/error-page/"; + var encodedOptions = []; + encodedOptions.push("dsn=" + dsn.toString()); + for (var key in dialogOptions) { + if (key === 'dsn') { + continue; + } + if (key === 'user') { + if (!dialogOptions.user) { + continue; + } + if (dialogOptions.user.name) { + encodedOptions.push("name=" + encodeURIComponent(dialogOptions.user.name)); + } + if (dialogOptions.user.email) { + encodedOptions.push("email=" + encodeURIComponent(dialogOptions.user.email)); + } + } + else { + encodedOptions.push(encodeURIComponent(key) + "=" + encodeURIComponent(dialogOptions[key])); + } + } + if (encodedOptions.length) { + return endpoint + "?" + encodedOptions.join('&'); + } + return endpoint; + }; + /** Returns the envelope endpoint URL. */ + API.prototype._getEnvelopeEndpoint = function () { + return this._getIngestEndpoint('envelope'); + }; + /** Returns the ingest API endpoint for target. */ + API.prototype._getIngestEndpoint = function (target) { + if (this._tunnel) { + return this._tunnel; + } + var base = this.getBaseApiEndpoint(); + var dsn = this.getDsn(); + return "" + base + dsn.projectId + "/" + target + "/"; + }; + /** Returns a URL-encoded string with auth config suitable for a query string. */ + API.prototype._encodedAuth = function () { + var dsn = this.getDsn(); + var auth = { + // We send only the minimum set of required information. See + // https://github.com/getsentry/sentry-javascript/issues/2572. + sentry_key: dsn.publicKey, + sentry_version: SENTRY_API_VERSION, + }; + return utils_1.urlEncode(auth); + }; + return API; +}()); +exports.API = API; +//# sourceMappingURL=api.js.map /***/ }), -/***/ 47906: +/***/ 25886: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); var utils_1 = __nccwpck_require__(1620); -var spanstatus_1 = __nccwpck_require__(58522); -var utils_2 = __nccwpck_require__(31386); -/** - * Configures global error listeners - */ -function registerErrorInstrumentation() { - utils_1.addInstrumentationHandler({ - callback: errorCallback, - type: 'error', - }); - utils_1.addInstrumentationHandler({ - callback: errorCallback, - type: 'unhandledrejection', - }); -} -exports.registerErrorInstrumentation = registerErrorInstrumentation; +var noop_1 = __nccwpck_require__(68641); /** - * If an error or unhandled promise occurs, we mark the active transaction as failed + * This is the base implemention of a Backend. + * @hidden */ -function errorCallback() { - var activeTransaction = utils_2.getActiveTransaction(); - if (activeTransaction) { - utils_1.logger.log("[Tracing] Transaction: " + spanstatus_1.SpanStatus.InternalError + " -> Global error occured"); - activeTransaction.setStatus(spanstatus_1.SpanStatus.InternalError); +var BaseBackend = /** @class */ (function () { + /** Creates a new backend instance. */ + function BaseBackend(options) { + this._options = options; + if (!this._options.dsn) { + utils_1.logger.warn('No DSN provided, backend will not do anything.'); + } + this._transport = this._setupTransport(); } -} -//# sourceMappingURL=errors.js.map + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + BaseBackend.prototype.eventFromException = function (_exception, _hint) { + throw new utils_1.SentryError('Backend has to implement `eventFromException` method'); + }; + /** + * @inheritDoc + */ + BaseBackend.prototype.eventFromMessage = function (_message, _level, _hint) { + throw new utils_1.SentryError('Backend has to implement `eventFromMessage` method'); + }; + /** + * @inheritDoc + */ + BaseBackend.prototype.sendEvent = function (event) { + void this._transport.sendEvent(event).then(null, function (reason) { + utils_1.logger.error("Error while sending event: " + reason); + }); + }; + /** + * @inheritDoc + */ + BaseBackend.prototype.sendSession = function (session) { + if (!this._transport.sendSession) { + utils_1.logger.warn("Dropping session because custom transport doesn't implement sendSession"); + return; + } + void this._transport.sendSession(session).then(null, function (reason) { + utils_1.logger.error("Error while sending session: " + reason); + }); + }; + /** + * @inheritDoc + */ + BaseBackend.prototype.getTransport = function () { + return this._transport; + }; + /** + * Sets up the transport so it can be used later to send requests. + */ + BaseBackend.prototype._setupTransport = function () { + return new noop_1.NoopTransport(); + }; + return BaseBackend; +}()); +exports.BaseBackend = BaseBackend; +//# sourceMappingURL=basebackend.js.map /***/ }), -/***/ 31409: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 25684: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* module decorator */ module = __nccwpck_require__.nmd(module); Object.defineProperty(exports, "__esModule", ({ value: true })); var tslib_1 = __nccwpck_require__(4351); +/* eslint-disable max-lines */ var hub_1 = __nccwpck_require__(6393); var types_1 = __nccwpck_require__(83789); var utils_1 = __nccwpck_require__(1620); -var errors_1 = __nccwpck_require__(47906); -var idletransaction_1 = __nccwpck_require__(2171); -var transaction_1 = __nccwpck_require__(8186); -var utils_2 = __nccwpck_require__(31386); -/** Returns all trace headers that are currently on the top scope. */ -function traceHeaders() { - var scope = this.getScope(); - if (scope) { - var span = scope.getSpan(); - if (span) { - return { - 'sentry-trace': span.toTraceparent(), - }; - } - } - return {}; -} +var integration_1 = __nccwpck_require__(58500); /** - * Makes a sampling decision for the given transaction and stores it on the transaction. + * Base implementation for all JavaScript SDK clients. * - * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be - * sent to Sentry. + * Call the constructor with the corresponding backend constructor and options + * specific to the client subclass. To access these options later, use + * {@link Client.getOptions}. Also, the Backend instance is available via + * {@link Client.getBackend}. * - * @param hub: The hub off of which to read config options - * @param transaction: The transaction needing a sampling decision - * @param samplingContext: Default and user-provided data which may be used to help make the decision + * If a Dsn is specified in the options, it will be parsed and stored. Use + * {@link Client.getDsn} to retrieve the Dsn at any moment. In case the Dsn is + * invalid, the constructor will throw a {@link SentryException}. Note that + * without a valid Dsn, the SDK will not send any events to Sentry. * - * @returns The given transaction with its `sampled` value set - */ -function sample(hub, transaction, samplingContext) { - var _a; - var client = hub.getClient(); - var options = (client && client.getOptions()) || {}; - // nothing to do if there's no client or if tracing is disabled - if (!client || !utils_2.hasTracingEnabled(options)) { - transaction.sampled = false; - return transaction; - } - // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that - if (transaction.sampled !== undefined) { - transaction.tags = tslib_1.__assign(tslib_1.__assign({}, transaction.tags), { __sentry_samplingMethod: types_1.TransactionSamplingMethod.Explicit }); - return transaction; - } - // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` were defined, so one of these should - // work; prefer the hook if so - var sampleRate; - if (typeof options.tracesSampler === 'function') { - sampleRate = options.tracesSampler(samplingContext); - // cast the rate to a number first in case it's a boolean - transaction.tags = tslib_1.__assign(tslib_1.__assign({}, transaction.tags), { __sentry_samplingMethod: types_1.TransactionSamplingMethod.Sampler, - // TODO kmclb - once tag types are loosened, don't need to cast to string here - __sentry_sampleRate: String(Number(sampleRate)) }); - } - else if (samplingContext.parentSampled !== undefined) { - sampleRate = samplingContext.parentSampled; - transaction.tags = tslib_1.__assign(tslib_1.__assign({}, transaction.tags), { __sentry_samplingMethod: types_1.TransactionSamplingMethod.Inheritance }); - } - else { - sampleRate = options.tracesSampleRate; - // cast the rate to a number first in case it's a boolean - transaction.tags = tslib_1.__assign(tslib_1.__assign({}, transaction.tags), { __sentry_samplingMethod: types_1.TransactionSamplingMethod.Rate, - // TODO kmclb - once tag types are loosened, don't need to cast to string here - __sentry_sampleRate: String(Number(sampleRate)) }); - } - // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The - // only valid values are booleans or numbers between 0 and 1.) - if (!isValidSampleRate(sampleRate)) { - utils_1.logger.warn("[Tracing] Discarding transaction because of invalid sample rate."); - transaction.sampled = false; - return transaction; - } - // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped - if (!sampleRate) { - utils_1.logger.log("[Tracing] Discarding transaction because " + (typeof options.tracesSampler === 'function' - ? 'tracesSampler returned 0 or false' - : 'a negative sampling decision was inherited or tracesSampleRate is set to 0')); - transaction.sampled = false; - return transaction; - } - // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is - // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false. - transaction.sampled = Math.random() < sampleRate; - // if we're not going to keep it, we're done - if (!transaction.sampled) { - utils_1.logger.log("[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = " + Number(sampleRate) + ")"); - return transaction; - } - // at this point we know we're keeping the transaction, whether because of an inherited decision or because it got - // lucky with the dice roll - transaction.initSpanRecorder((_a = options._experiments) === null || _a === void 0 ? void 0 : _a.maxSpans); - utils_1.logger.log("[Tracing] starting " + transaction.op + " transaction - " + transaction.name); - return transaction; -} -/** - * Gets the correct context to pass to the tracesSampler, based on the environment (i.e., which SDK is being used) + * Before sending an event via the backend, it is passed through + * {@link BaseClient._prepareEvent} to add SDK information and scope data + * (breadcrumbs and context). To add more custom information, override this + * method and extend the resulting prepared event. + * + * To issue automatically created events (e.g. via instrumentation), use + * {@link Client.captureEvent}. It will prepare the event and pass it through + * the callback lifecycle. To issue auto-breadcrumbs, use + * {@link Client.addBreadcrumb}. + * + * @example + * class NodeClient extends BaseClient { + * public constructor(options: NodeOptions) { + * super(NodeBackend, options); + * } * - * @returns The default sample context + * // ... + * } */ -function getDefaultSamplingContext(transactionContext) { - // promote parent sampling decision (if any) for easy access - var parentSampled = transactionContext.parentSampled; - var defaultSamplingContext = { transactionContext: transactionContext, parentSampled: parentSampled }; - if (utils_1.isNodeEnv()) { - var domain = hub_1.getActiveDomain(); - if (domain) { - // for all node servers that we currently support, we store the incoming request object (which is an instance of - // http.IncomingMessage) on the domain - // the domain members are stored as an array, so our only way to find the request is to iterate through the array - // and compare types - var nodeHttpModule = utils_1.dynamicRequire(module, 'http'); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - var requestType_1 = nodeHttpModule.IncomingMessage; - var request = domain.members.find(function (member) { return utils_1.isInstanceOf(member, requestType_1); }); - if (request) { - defaultSamplingContext.request = utils_1.extractNodeRequestData(request); - } +var BaseClient = /** @class */ (function () { + /** + * Initializes this client instance. + * + * @param backendClass A constructor function to create the backend. + * @param options Options for the client. + */ + function BaseClient(backendClass, options) { + /** Array of used integrations. */ + this._integrations = {}; + /** Number of calls being processed */ + this._numProcessing = 0; + this._backend = new backendClass(options); + this._options = options; + if (options.dsn) { + this._dsn = new utils_1.Dsn(options.dsn); } } - // we must be in browser-js (or some derivative thereof) - else { - // we use `getGlobalObject()` rather than `window` since service workers also have a `location` property on `self` - var globalObject = utils_1.getGlobalObject(); - if ('location' in globalObject) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any - defaultSamplingContext.location = tslib_1.__assign({}, globalObject.location); + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + BaseClient.prototype.captureException = function (exception, hint, scope) { + var _this = this; + var eventId = hint && hint.event_id; + this._process(this._getBackend() + .eventFromException(exception, hint) + .then(function (event) { return _this._captureEvent(event, hint, scope); }) + .then(function (result) { + eventId = result; + })); + return eventId; + }; + /** + * @inheritDoc + */ + BaseClient.prototype.captureMessage = function (message, level, hint, scope) { + var _this = this; + var eventId = hint && hint.event_id; + var promisedEvent = utils_1.isPrimitive(message) + ? this._getBackend().eventFromMessage(String(message), level, hint) + : this._getBackend().eventFromException(message, hint); + this._process(promisedEvent + .then(function (event) { return _this._captureEvent(event, hint, scope); }) + .then(function (result) { + eventId = result; + })); + return eventId; + }; + /** + * @inheritDoc + */ + BaseClient.prototype.captureEvent = function (event, hint, scope) { + var eventId = hint && hint.event_id; + this._process(this._captureEvent(event, hint, scope).then(function (result) { + eventId = result; + })); + return eventId; + }; + /** + * @inheritDoc + */ + BaseClient.prototype.captureSession = function (session) { + if (!this._isEnabled()) { + utils_1.logger.warn('SDK not enabled, will not capture session.'); + return; } - } - return defaultSamplingContext; -} -/** - * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1). - */ -function isValidSampleRate(rate) { - // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) { - utils_1.logger.warn("[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got " + JSON.stringify(rate) + " of type " + JSON.stringify(typeof rate) + "."); - return false; - } - // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false - if (rate < 0 || rate > 1) { - utils_1.logger.warn("[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got " + rate + "."); - return false; - } - return true; -} -/** - * Creates a new transaction and adds a sampling decision if it doesn't yet have one. - * - * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if - * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an - * "extension method." - * - * @param this: The Hub starting the transaction - * @param transactionContext: Data used to configure the transaction - * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any) - * - * @returns The new transaction - * - * @see {@link Hub.startTransaction} - */ -function _startTransaction(transactionContext, customSamplingContext) { - var transaction = new transaction_1.Transaction(transactionContext, this); - return sample(this, transaction, tslib_1.__assign(tslib_1.__assign({}, getDefaultSamplingContext(transactionContext)), customSamplingContext)); -} -/** - * Create new idle transaction. - */ -function startIdleTransaction(hub, transactionContext, idleTimeout, onScope) { - var transaction = new idletransaction_1.IdleTransaction(transactionContext, hub, idleTimeout, onScope); - return sample(hub, transaction, getDefaultSamplingContext(transactionContext)); -} -exports.startIdleTransaction = startIdleTransaction; -/** - * @private - */ -function _addTracingExtensions() { - var carrier = hub_1.getMainCarrier(); - if (carrier.__SENTRY__) { - carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; - if (!carrier.__SENTRY__.extensions.startTransaction) { - carrier.__SENTRY__.extensions.startTransaction = _startTransaction; + if (!(typeof session.release === 'string')) { + utils_1.logger.warn('Discarded session because of missing or non-string release'); } - if (!carrier.__SENTRY__.extensions.traceHeaders) { - carrier.__SENTRY__.extensions.traceHeaders = traceHeaders; + else { + this._sendSession(session); + // After sending, we set init false to indicate it's not the first occurrence + session.update({ init: false }); } - } -} -exports._addTracingExtensions = _addTracingExtensions; -/** - * This patches the global object and injects the Tracing extensions methods - */ -function addExtensionMethods() { - _addTracingExtensions(); - // If an error happens globally, we should make sure transaction status is set to error. - errors_1.registerErrorInstrumentation(); -} -exports.addExtensionMethods = addExtensionMethods; -//# sourceMappingURL=hubextensions.js.map - -/***/ }), - -/***/ 2171: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var utils_1 = __nccwpck_require__(1620); -var span_1 = __nccwpck_require__(64655); -var spanstatus_1 = __nccwpck_require__(58522); -var transaction_1 = __nccwpck_require__(8186); -exports.DEFAULT_IDLE_TIMEOUT = 1000; -/** - * @inheritDoc - */ -var IdleTransactionSpanRecorder = /** @class */ (function (_super) { - tslib_1.__extends(IdleTransactionSpanRecorder, _super); - function IdleTransactionSpanRecorder(_pushActivity, _popActivity, transactionSpanId, maxlen) { - if (transactionSpanId === void 0) { transactionSpanId = ''; } - var _this = _super.call(this, maxlen) || this; - _this._pushActivity = _pushActivity; - _this._popActivity = _popActivity; - _this.transactionSpanId = transactionSpanId; - return _this; - } + }; + /** + * @inheritDoc + */ + BaseClient.prototype.getDsn = function () { + return this._dsn; + }; + /** + * @inheritDoc + */ + BaseClient.prototype.getOptions = function () { + return this._options; + }; + /** + * @inheritDoc + */ + BaseClient.prototype.flush = function (timeout) { + var _this = this; + return this._isClientDoneProcessing(timeout).then(function (clientFinished) { + return _this._getBackend() + .getTransport() + .close(timeout) + .then(function (transportFlushed) { return clientFinished && transportFlushed; }); + }); + }; /** * @inheritDoc */ - IdleTransactionSpanRecorder.prototype.add = function (span) { + BaseClient.prototype.close = function (timeout) { var _this = this; - // We should make sure we do not push and pop activities for - // the transaction that this span recorder belongs to. - if (span.spanId !== this.transactionSpanId) { - // We patch span.finish() to pop an activity after setting an endTimestamp. - span.finish = function (endTimestamp) { - span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : utils_1.timestampWithMs(); - _this._popActivity(span.spanId); - }; - // We should only push new activities if the span does not have an end timestamp. - if (span.endTimestamp === undefined) { - this._pushActivity(span.spanId); - } + return this.flush(timeout).then(function (result) { + _this.getOptions().enabled = false; + return result; + }); + }; + /** + * Sets up the integrations + */ + BaseClient.prototype.setupIntegrations = function () { + if (this._isEnabled() && !this._integrations.initialized) { + this._integrations = integration_1.setupIntegrations(this._options); } - _super.prototype.add.call(this, span); }; - return IdleTransactionSpanRecorder; -}(span_1.SpanRecorder)); -exports.IdleTransactionSpanRecorder = IdleTransactionSpanRecorder; -/** - * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities. - * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will - * put itself on the scope on creation. - */ -var IdleTransaction = /** @class */ (function (_super) { - tslib_1.__extends(IdleTransaction, _super); - function IdleTransaction(transactionContext, _idleHub, - // The time to wait in ms until the idle transaction will be finished. Default: 1000 - _idleTimeout, - // If an idle transaction should be put itself on and off the scope automatically. - _onScope) { - if (_idleTimeout === void 0) { _idleTimeout = exports.DEFAULT_IDLE_TIMEOUT; } - if (_onScope === void 0) { _onScope = false; } - var _this = _super.call(this, transactionContext, _idleHub) || this; - _this._idleHub = _idleHub; - _this._idleTimeout = _idleTimeout; - _this._onScope = _onScope; - // Activities store a list of active spans - _this.activities = {}; - // Stores reference to the timeout that calls _beat(). - _this._heartbeatTimer = 0; - // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats. - _this._heartbeatCounter = 0; - // We should not use heartbeat if we finished a transaction - _this._finished = false; - _this._beforeFinishCallbacks = []; - if (_idleHub && _onScope) { - // There should only be one active transaction on the scope - clearActiveTransaction(_idleHub); - // We set the transaction here on the scope so error events pick up the trace - // context and attach it to the error. - utils_1.logger.log("Setting idle transaction on scope. Span ID: " + _this.spanId); - _idleHub.configureScope(function (scope) { return scope.setSpan(_this); }); + /** + * @inheritDoc + */ + BaseClient.prototype.getIntegration = function (integration) { + try { + return this._integrations[integration.id] || null; } - return _this; - } - /** {@inheritDoc} */ - IdleTransaction.prototype.finish = function (endTimestamp) { + catch (_oO) { + utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Client"); + return null; + } + }; + /** Updates existing session based on the provided event */ + BaseClient.prototype._updateSessionFromEvent = function (session, event) { var e_1, _a; - var _this = this; - if (endTimestamp === void 0) { endTimestamp = utils_1.timestampWithMs(); } - this._finished = true; - this.activities = {}; - if (this.spanRecorder) { - utils_1.logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op); + var crashed = false; + var errored = false; + var exceptions = event.exception && event.exception.values; + if (exceptions) { + errored = true; try { - for (var _b = tslib_1.__values(this._beforeFinishCallbacks), _c = _b.next(); !_c.done; _c = _b.next()) { - var callback = _c.value; - callback(this, endTimestamp); + for (var exceptions_1 = tslib_1.__values(exceptions), exceptions_1_1 = exceptions_1.next(); !exceptions_1_1.done; exceptions_1_1 = exceptions_1.next()) { + var ex = exceptions_1_1.value; + var mechanism = ex.mechanism; + if (mechanism && mechanism.handled === false) { + crashed = true; + break; + } } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + if (exceptions_1_1 && !exceptions_1_1.done && (_a = exceptions_1.return)) _a.call(exceptions_1); } finally { if (e_1) throw e_1.error; } } - this.spanRecorder.spans = this.spanRecorder.spans.filter(function (span) { - // If we are dealing with the transaction itself, we just return it - if (span.spanId === _this.spanId) { - return true; - } - // We cancel all pending spans with status "cancelled" to indicate the idle transaction was finished early - if (!span.endTimestamp) { - span.endTimestamp = endTimestamp; - span.setStatus(spanstatus_1.SpanStatus.Cancelled); - utils_1.logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2)); - } - var keepSpan = span.startTimestamp < endTimestamp; - if (!keepSpan) { - utils_1.logger.log('[Tracing] discarding Span since it happened after Transaction was finished', JSON.stringify(span, undefined, 2)); - } - return keepSpan; - }); - // this._onScope is true if the transaction was previously on the scope. - if (this._onScope) { - clearActiveTransaction(this._idleHub); - } - utils_1.logger.log('[Tracing] flushing IdleTransaction'); } - else { - utils_1.logger.log('[Tracing] No active IdleTransaction'); + // A session is updated and that session update is sent in only one of the two following scenarios: + // 1. Session with non terminal status and 0 errors + an error occurred -> Will set error count to 1 and send update + // 2. Session with non terminal status and 1 error + a crash occurred -> Will set status crashed and send update + var sessionNonTerminal = session.status === types_1.SessionStatus.Ok; + var shouldUpdateAndSend = (sessionNonTerminal && session.errors === 0) || (sessionNonTerminal && crashed); + if (shouldUpdateAndSend) { + session.update(tslib_1.__assign(tslib_1.__assign({}, (crashed && { status: types_1.SessionStatus.Crashed })), { errors: session.errors || Number(errored || crashed) })); + this.captureSession(session); } - return _super.prototype.finish.call(this, endTimestamp); }; - /** - * Register a callback function that gets excecuted before the transaction finishes. - * Useful for cleanup or if you want to add any additional spans based on current context. - * - * This is exposed because users have no other way of running something before an idle transaction - * finishes. - */ - IdleTransaction.prototype.registerBeforeFinishCallback = function (callback) { - this._beforeFinishCallbacks.push(callback); + /** Deliver captured session to Sentry */ + BaseClient.prototype._sendSession = function (session) { + this._getBackend().sendSession(session); }; /** - * @inheritDoc + * Determine if the client is finished processing. Returns a promise because it will wait `timeout` ms before saying + * "no" (resolving to `false`) in order to give the client a chance to potentially finish first. + * + * @param timeout The time, in ms, after which to resolve to `false` if the client is still busy. Passing `0` (or not + * passing anything) will make the promise wait as long as it takes for processing to finish before resolving to + * `true`. + * @returns A promise which will resolve to `true` if processing is already done or finishes before the timeout, and + * `false` otherwise */ - IdleTransaction.prototype.initSpanRecorder = function (maxlen) { + BaseClient.prototype._isClientDoneProcessing = function (timeout) { var _this = this; - if (!this.spanRecorder) { - this._initTimeout = setTimeout(function () { - if (!_this._finished) { - _this.finish(); - } - }, this._idleTimeout); - var pushActivity = function (id) { - if (_this._finished) { - return; + return new utils_1.SyncPromise(function (resolve) { + var ticked = 0; + var tick = 1; + var interval = setInterval(function () { + if (_this._numProcessing == 0) { + clearInterval(interval); + resolve(true); } - _this._pushActivity(id); - }; - var popActivity = function (id) { - if (_this._finished) { - return; + else { + ticked += tick; + if (timeout && ticked >= timeout) { + clearInterval(interval); + resolve(false); + } } - _this._popActivity(id); - }; - this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen); - // Start heartbeat so that transactions do not run forever. - utils_1.logger.log('Starting heartbeat'); - this._pingHeartbeat(); - } - this.spanRecorder.add(this); + }, tick); + }); + }; + /** Returns the current backend. */ + BaseClient.prototype._getBackend = function () { + return this._backend; + }; + /** Determines whether this SDK is enabled and a valid Dsn is present. */ + BaseClient.prototype._isEnabled = function () { + return this.getOptions().enabled !== false && this._dsn !== undefined; }; /** - * Start tracking a specific activity. - * @param spanId The span id that represents the activity + * Adds common information to events. + * + * The information includes release and environment from `options`, + * breadcrumbs and context (extra, tags and user) from the scope. + * + * Information that is already present in the event is never overwritten. For + * nested objects, such as the context, keys are merged. + * + * @param event The original event. + * @param hint May contain additional information about the original exception. + * @param scope A scope containing event metadata. + * @returns A new event with more information. */ - IdleTransaction.prototype._pushActivity = function (spanId) { - if (this._initTimeout) { - clearTimeout(this._initTimeout); - this._initTimeout = undefined; + BaseClient.prototype._prepareEvent = function (event, scope, hint) { + var _this = this; + var _a = this.getOptions().normalizeDepth, normalizeDepth = _a === void 0 ? 3 : _a; + var prepared = tslib_1.__assign(tslib_1.__assign({}, event), { event_id: event.event_id || (hint && hint.event_id ? hint.event_id : utils_1.uuid4()), timestamp: event.timestamp || utils_1.dateTimestampInSeconds() }); + this._applyClientOptions(prepared); + this._applyIntegrationsMetadata(prepared); + // If we have scope given to us, use it as the base for further modifications. + // This allows us to prevent unnecessary copying of data if `captureContext` is not provided. + var finalScope = scope; + if (hint && hint.captureContext) { + finalScope = hub_1.Scope.clone(finalScope).update(hint.captureContext); } - utils_1.logger.log("[Tracing] pushActivity: " + spanId); - this.activities[spanId] = true; - utils_1.logger.log('[Tracing] new activities count', Object.keys(this.activities).length); + // We prepare the result here with a resolved Event. + var result = utils_1.SyncPromise.resolve(prepared); + // This should be the last thing called, since we want that + // {@link Hub.addEventProcessor} gets the finished prepared event. + if (finalScope) { + // In case we have a hub we reassign it. + result = finalScope.applyToEvent(prepared, hint); + } + return result.then(function (evt) { + if (typeof normalizeDepth === 'number' && normalizeDepth > 0) { + return _this._normalizeEvent(evt, normalizeDepth); + } + return evt; + }); }; /** - * Remove an activity from usage - * @param spanId The span id that represents the activity + * Applies `normalize` function on necessary `Event` attributes to make them safe for serialization. + * Normalized keys: + * - `breadcrumbs.data` + * - `user` + * - `contexts` + * - `extra` + * @param event Event + * @returns Normalized event */ - IdleTransaction.prototype._popActivity = function (spanId) { - var _this = this; - if (this.activities[spanId]) { - utils_1.logger.log("[Tracing] popActivity " + spanId); - // eslint-disable-next-line @typescript-eslint/no-dynamic-delete - delete this.activities[spanId]; - utils_1.logger.log('[Tracing] new activities count', Object.keys(this.activities).length); + BaseClient.prototype._normalizeEvent = function (event, depth) { + if (!event) { + return null; } - if (Object.keys(this.activities).length === 0) { - var timeout = this._idleTimeout; - // We need to add the timeout here to have the real endtimestamp of the transaction - // Remember timestampWithMs is in seconds, timeout is in ms - var end_1 = utils_1.timestampWithMs() + timeout / 1000; - setTimeout(function () { - if (!_this._finished) { - _this.finish(end_1); - } - }, timeout); + var normalized = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, event), (event.breadcrumbs && { + breadcrumbs: event.breadcrumbs.map(function (b) { return (tslib_1.__assign(tslib_1.__assign({}, b), (b.data && { + data: utils_1.normalize(b.data, depth), + }))); }), + })), (event.user && { + user: utils_1.normalize(event.user, depth), + })), (event.contexts && { + contexts: utils_1.normalize(event.contexts, depth), + })), (event.extra && { + extra: utils_1.normalize(event.extra, depth), + })); + // event.contexts.trace stores information about a Transaction. Similarly, + // event.spans[] stores information about child Spans. Given that a + // Transaction is conceptually a Span, normalization should apply to both + // Transactions and Spans consistently. + // For now the decision is to skip normalization of Transactions and Spans, + // so this block overwrites the normalized event to add back the original + // Transaction information prior to normalization. + if (event.contexts && event.contexts.trace) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + normalized.contexts.trace = event.contexts.trace; } + var _a = this.getOptions()._experiments, _experiments = _a === void 0 ? {} : _a; + if (_experiments.ensureNoCircularStructures) { + return utils_1.normalize(normalized); + } + return normalized; }; /** - * Checks when entries of this.activities are not changing for 3 beats. - * If this occurs we finish the transaction. + * Enhances event using the client configuration. + * It takes care of all "static" values like environment, release and `dist`, + * as well as truncating overly long values. + * @param event event instance to be enhanced */ - IdleTransaction.prototype._beat = function () { - clearTimeout(this._heartbeatTimer); - // We should not be running heartbeat if the idle transaction is finished. - if (this._finished) { - return; + BaseClient.prototype._applyClientOptions = function (event) { + var options = this.getOptions(); + var environment = options.environment, release = options.release, dist = options.dist, _a = options.maxValueLength, maxValueLength = _a === void 0 ? 250 : _a; + if (!('environment' in event)) { + event.environment = 'environment' in options ? environment : 'production'; } - var keys = Object.keys(this.activities); - var heartbeatString = keys.length ? keys.reduce(function (prev, current) { return prev + current; }) : ''; - if (heartbeatString === this._prevHeartbeatString) { - this._heartbeatCounter += 1; + if (event.release === undefined && release !== undefined) { + event.release = release; } - else { - this._heartbeatCounter = 1; + if (event.dist === undefined && dist !== undefined) { + event.dist = dist; } - this._prevHeartbeatString = heartbeatString; - if (this._heartbeatCounter >= 3) { - utils_1.logger.log("[Tracing] Transaction finished because of no change for 3 heart beats"); - this.setStatus(spanstatus_1.SpanStatus.DeadlineExceeded); - this.setTag('heartbeat', 'failed'); - this.finish(); + if (event.message) { + event.message = utils_1.truncate(event.message, maxValueLength); } - else { - this._pingHeartbeat(); + var exception = event.exception && event.exception.values && event.exception.values[0]; + if (exception && exception.value) { + exception.value = utils_1.truncate(exception.value, maxValueLength); + } + var request = event.request; + if (request && request.url) { + request.url = utils_1.truncate(request.url, maxValueLength); } }; /** - * Pings the heartbeat + * This function adds all used integrations to the SDK info in the event. + * @param event The event that will be filled with all integrations. */ - IdleTransaction.prototype._pingHeartbeat = function () { - var _this = this; - utils_1.logger.log("pinging Heartbeat -> current counter: " + this._heartbeatCounter); - this._heartbeatTimer = setTimeout(function () { - _this._beat(); - }, 5000); + BaseClient.prototype._applyIntegrationsMetadata = function (event) { + var integrationsArray = Object.keys(this._integrations); + if (integrationsArray.length > 0) { + event.sdk = event.sdk || {}; + event.sdk.integrations = tslib_1.__spread((event.sdk.integrations || []), integrationsArray); + } }; - return IdleTransaction; -}(transaction_1.Transaction)); -exports.IdleTransaction = IdleTransaction; -/** - * Reset active transaction on scope - */ -function clearActiveTransaction(hub) { - if (hub) { - var scope = hub.getScope(); - if (scope) { - var transaction = scope.getTransaction(); - if (transaction) { - scope.setSpan(undefined); + /** + * Tells the backend to send this event + * @param event The Sentry event to send + */ + BaseClient.prototype._sendEvent = function (event) { + this._getBackend().sendEvent(event); + }; + /** + * Processes the event and logs an error in case of rejection + * @param event + * @param hint + * @param scope + */ + BaseClient.prototype._captureEvent = function (event, hint, scope) { + return this._processEvent(event, hint, scope).then(function (finalEvent) { + return finalEvent.event_id; + }, function (reason) { + utils_1.logger.error(reason); + return undefined; + }); + }; + /** + * Processes an event (either error or message) and sends it to Sentry. + * + * This also adds breadcrumbs and context information to the event. However, + * platform specific meta data (such as the User's IP address) must be added + * by the SDK implementor. + * + * + * @param event The event to send to Sentry. + * @param hint May contain additional information about the original exception. + * @param scope A scope containing event metadata. + * @returns A SyncPromise that resolves with the event or rejects in case event was/will not be send. + */ + BaseClient.prototype._processEvent = function (event, hint, scope) { + var _this = this; + // eslint-disable-next-line @typescript-eslint/unbound-method + var _a = this.getOptions(), beforeSend = _a.beforeSend, sampleRate = _a.sampleRate; + if (!this._isEnabled()) { + return utils_1.SyncPromise.reject(new utils_1.SentryError('SDK not enabled, will not capture event.')); + } + var isTransaction = event.type === 'transaction'; + // 1.0 === 100% events are sent + // 0.0 === 0% events are sent + // Sampling for transaction happens somewhere else + if (!isTransaction && typeof sampleRate === 'number' && Math.random() > sampleRate) { + return utils_1.SyncPromise.reject(new utils_1.SentryError("Discarding event because it's not included in the random sample (sampling rate = " + sampleRate + ")")); + } + return this._prepareEvent(event, scope, hint) + .then(function (prepared) { + if (prepared === null) { + throw new utils_1.SentryError('An event processor returned null, will not send event.'); + } + var isInternalException = hint && hint.data && hint.data.__sentry__ === true; + if (isInternalException || isTransaction || !beforeSend) { + return prepared; + } + var beforeSendResult = beforeSend(prepared, hint); + return _this._ensureBeforeSendRv(beforeSendResult); + }) + .then(function (processedEvent) { + if (processedEvent === null) { + throw new utils_1.SentryError('`beforeSend` returned `null`, will not send event.'); + } + var session = scope && scope.getSession && scope.getSession(); + if (!isTransaction && session) { + _this._updateSessionFromEvent(session, processedEvent); + } + _this._sendEvent(processedEvent); + return processedEvent; + }) + .then(null, function (reason) { + if (reason instanceof utils_1.SentryError) { + throw reason; } + _this.captureException(reason, { + data: { + __sentry__: true, + }, + originalException: reason, + }); + throw new utils_1.SentryError("Event processing pipeline threw an error, original event will not be sent. Details have been sent as a new event.\nReason: " + reason); + }); + }; + /** + * Occupies the client with processing and event + */ + BaseClient.prototype._process = function (promise) { + var _this = this; + this._numProcessing += 1; + void promise.then(function (value) { + _this._numProcessing -= 1; + return value; + }, function (reason) { + _this._numProcessing -= 1; + return reason; + }); + }; + /** + * Verifies that return value of configured `beforeSend` is of expected type. + */ + BaseClient.prototype._ensureBeforeSendRv = function (rv) { + var nullErr = '`beforeSend` method has to return `null` or a valid event.'; + if (utils_1.isThenable(rv)) { + return rv.then(function (event) { + if (!(utils_1.isPlainObject(event) || event === null)) { + throw new utils_1.SentryError(nullErr); + } + return event; + }, function (e) { + throw new utils_1.SentryError("beforeSend rejected with " + e); + }); } - } -} -//# sourceMappingURL=idletransaction.js.map + else if (!(utils_1.isPlainObject(rv) || rv === null)) { + throw new utils_1.SentryError(nullErr); + } + return rv; + }; + return BaseClient; +}()); +exports.BaseClient = BaseClient; +//# sourceMappingURL=baseclient.js.map /***/ }), -/***/ 64358: +/***/ 79212: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var browser_1 = __nccwpck_require__(71425); -var hubextensions_1 = __nccwpck_require__(31409); -exports.addExtensionMethods = hubextensions_1.addExtensionMethods; -var TracingIntegrations = __nccwpck_require__(28502); -var Integrations = tslib_1.__assign(tslib_1.__assign({}, TracingIntegrations), { BrowserTracing: browser_1.BrowserTracing }); -exports.Integrations = Integrations; -var span_1 = __nccwpck_require__(64655); -exports.Span = span_1.Span; -var transaction_1 = __nccwpck_require__(8186); -exports.Transaction = transaction_1.Transaction; -var spanstatus_1 = __nccwpck_require__(58522); -exports.SpanStatus = spanstatus_1.SpanStatus; -// We are patching the global object with our hub extension methods -hubextensions_1.addExtensionMethods(); -var utils_1 = __nccwpck_require__(31386); -exports.extractTraceparentData = utils_1.extractTraceparentData; -exports.getActiveTransaction = utils_1.getActiveTransaction; -exports.hasTracingEnabled = utils_1.hasTracingEnabled; -exports.stripUrlQueryAndFragment = utils_1.stripUrlQueryAndFragment; -exports.TRACEPARENT_REGEXP = utils_1.TRACEPARENT_REGEXP; +var minimal_1 = __nccwpck_require__(88455); +exports.addBreadcrumb = minimal_1.addBreadcrumb; +exports.captureException = minimal_1.captureException; +exports.captureEvent = minimal_1.captureEvent; +exports.captureMessage = minimal_1.captureMessage; +exports.configureScope = minimal_1.configureScope; +exports.startTransaction = minimal_1.startTransaction; +exports.setContext = minimal_1.setContext; +exports.setExtra = minimal_1.setExtra; +exports.setExtras = minimal_1.setExtras; +exports.setTag = minimal_1.setTag; +exports.setTags = minimal_1.setTags; +exports.setUser = minimal_1.setUser; +exports.withScope = minimal_1.withScope; +var hub_1 = __nccwpck_require__(6393); +exports.addGlobalEventProcessor = hub_1.addGlobalEventProcessor; +exports.getCurrentHub = hub_1.getCurrentHub; +exports.getHubFromCarrier = hub_1.getHubFromCarrier; +exports.Hub = hub_1.Hub; +exports.makeMain = hub_1.makeMain; +exports.Scope = hub_1.Scope; +var api_1 = __nccwpck_require__(90785); +exports.API = api_1.API; +var baseclient_1 = __nccwpck_require__(25684); +exports.BaseClient = baseclient_1.BaseClient; +var basebackend_1 = __nccwpck_require__(25886); +exports.BaseBackend = basebackend_1.BaseBackend; +var request_1 = __nccwpck_require__(1553); +exports.eventToSentryRequest = request_1.eventToSentryRequest; +exports.sessionToSentryRequest = request_1.sessionToSentryRequest; +var sdk_1 = __nccwpck_require__(46406); +exports.initAndBind = sdk_1.initAndBind; +var noop_1 = __nccwpck_require__(68641); +exports.NoopTransport = noop_1.NoopTransport; +var version_1 = __nccwpck_require__(33493); +exports.SDK_VERSION = version_1.SDK_VERSION; +var Integrations = __nccwpck_require__(96727); +exports.Integrations = Integrations; //# sourceMappingURL=index.js.map /***/ }), -/***/ 96221: +/***/ 58500: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); var tslib_1 = __nccwpck_require__(4351); +var hub_1 = __nccwpck_require__(6393); var utils_1 = __nccwpck_require__(1620); +exports.installedIntegrations = []; /** - * Express integration - * - * Provides an request and error handler for Express framework as well as tracing capabilities + * @private */ -var Express = /** @class */ (function () { - /** - * @inheritDoc - */ - function Express(options) { - if (options === void 0) { options = {}; } +function filterDuplicates(integrations) { + return integrations.reduce(function (acc, integrations) { + if (acc.every(function (accIntegration) { return integrations.name !== accIntegration.name; })) { + acc.push(integrations); + } + return acc; + }, []); +} +/** Gets integration to install */ +function getIntegrationsToSetup(options) { + var defaultIntegrations = (options.defaultIntegrations && tslib_1.__spread(options.defaultIntegrations)) || []; + var userIntegrations = options.integrations; + var integrations = tslib_1.__spread(filterDuplicates(defaultIntegrations)); + if (Array.isArray(userIntegrations)) { + // Filter out integrations that are also included in user options + integrations = tslib_1.__spread(integrations.filter(function (integrations) { + return userIntegrations.every(function (userIntegration) { return userIntegration.name !== integrations.name; }); + }), filterDuplicates(userIntegrations)); + } + else if (typeof userIntegrations === 'function') { + integrations = userIntegrations(integrations); + integrations = Array.isArray(integrations) ? integrations : [integrations]; + } + // Make sure that if present, `Debug` integration will always run last + var integrationsNames = integrations.map(function (i) { return i.name; }); + var alwaysLastToRun = 'Debug'; + if (integrationsNames.indexOf(alwaysLastToRun) !== -1) { + integrations.push.apply(integrations, tslib_1.__spread(integrations.splice(integrationsNames.indexOf(alwaysLastToRun), 1))); + } + return integrations; +} +exports.getIntegrationsToSetup = getIntegrationsToSetup; +/** Setup given integration */ +function setupIntegration(integration) { + if (exports.installedIntegrations.indexOf(integration.name) !== -1) { + return; + } + integration.setupOnce(hub_1.addGlobalEventProcessor, hub_1.getCurrentHub); + exports.installedIntegrations.push(integration.name); + utils_1.logger.log("Integration installed: " + integration.name); +} +exports.setupIntegration = setupIntegration; +/** + * Given a list of integration instances this installs them all. When `withDefaults` is set to `true` then all default + * integrations are added unless they were already provided before. + * @param integrations array of integration instances + * @param withDefault should enable default integrations + */ +function setupIntegrations(options) { + var integrations = {}; + getIntegrationsToSetup(options).forEach(function (integration) { + integrations[integration.name] = integration; + setupIntegration(integration); + }); + // set the `initialized` flag so we don't run through the process again unecessarily; use `Object.defineProperty` + // because by default it creates a property which is nonenumerable, which we want since `initialized` shouldn't be + // considered a member of the index the way the actual integrations are + Object.defineProperty(integrations, 'initialized', { value: true }); + return integrations; +} +exports.setupIntegrations = setupIntegrations; +//# sourceMappingURL=integration.js.map + +/***/ }), + +/***/ 87349: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var originalFunctionToString; +/** Patch toString calls to return proper name for wrapped functions */ +var FunctionToString = /** @class */ (function () { + function FunctionToString() { /** * @inheritDoc */ - this.name = Express.id; - this._router = options.router || options.app; - this._methods = (Array.isArray(options.methods) ? options.methods : []).concat('use'); + this.name = FunctionToString.id; } /** * @inheritDoc */ - Express.prototype.setupOnce = function () { - if (!this._router) { - utils_1.logger.error('ExpressIntegration is missing an Express instance'); - return; - } - instrumentMiddlewares(this._router, this._methods); + FunctionToString.prototype.setupOnce = function () { + // eslint-disable-next-line @typescript-eslint/unbound-method + originalFunctionToString = Function.prototype.toString; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Function.prototype.toString = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var context = this.__sentry_original__ || this; + return originalFunctionToString.apply(context, args); + }; }; /** * @inheritDoc */ - Express.id = 'Express'; - return Express; + FunctionToString.id = 'FunctionToString'; + return FunctionToString; }()); -exports.Express = Express; -/** - * Wraps original middleware function in a tracing call, which stores the info about the call as a span, - * and finishes it once the middleware is done invoking. - * - * Express middlewares have 3 various forms, thus we have to take care of all of them: - * // sync - * app.use(function (req, res) { ... }) - * // async - * app.use(function (req, res, next) { ... }) - * // error handler - * app.use(function (err, req, res, next) { ... }) - * - * They all internally delegate to the `router[method]` of the given application instance. - */ -// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any -function wrap(fn, method) { - var arity = fn.length; - switch (arity) { - case 2: { - return function (req, res) { - var transaction = res.__sentry_transaction; - if (transaction) { - var span_1 = transaction.startChild({ - description: fn.name, - op: "middleware." + method, - }); - res.once('finish', function () { - span_1.finish(); - }); - } - return fn.call(this, req, res); - }; - } - case 3: { - return function (req, res, next) { - var _a; - var transaction = res.__sentry_transaction; - var span = (_a = transaction) === null || _a === void 0 ? void 0 : _a.startChild({ - description: fn.name, - op: "middleware." + method, - }); - fn.call(this, req, res, function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - next.call.apply(next, tslib_1.__spread([this], args)); - }); - }; - } - case 4: { - return function (err, req, res, next) { - var _a; - var transaction = res.__sentry_transaction; - var span = (_a = transaction) === null || _a === void 0 ? void 0 : _a.startChild({ - description: fn.name, - op: "middleware." + method, - }); - fn.call(this, err, req, res, function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - next.call.apply(next, tslib_1.__spread([this], args)); - }); - }; - } - default: { - throw new Error("Express middleware takes 2-4 arguments. Got: " + arity); - } - } -} -/** - * Takes all the function arguments passed to the original `app` or `router` method, eg. `app.use` or `router.use` - * and wraps every function, as well as array of functions with a call to our `wrap` method. - * We have to take care of the arrays as well as iterate over all of the arguments, - * as `app.use` can accept middlewares in few various forms. - * - * app.use([], ) - * app.use([], , ...) - * app.use([], ...[]) - */ -function wrapMiddlewareArgs(args, method) { - return args.map(function (arg) { - if (typeof arg === 'function') { - return wrap(arg, method); - } - if (Array.isArray(arg)) { - return arg.map(function (a) { - if (typeof a === 'function') { - return wrap(a, method); - } - return a; - }); - } - return arg; - }); -} -/** - * Patches original router to utilize our tracing functionality - */ -function patchMiddleware(router, method) { - var originalCallback = router[method]; - router[method] = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return originalCallback.call.apply(originalCallback, tslib_1.__spread([this], wrapMiddlewareArgs(args, method))); - }; - return router; -} -/** - * Patches original router methods - */ -function instrumentMiddlewares(router, methods) { - if (methods === void 0) { methods = []; } - methods.forEach(function (method) { return patchMiddleware(router, method); }); -} -//# sourceMappingURL=express.js.map +exports.FunctionToString = FunctionToString; +//# sourceMappingURL=functiontostring.js.map /***/ }), -/***/ 28502: +/***/ 54838: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Object.defineProperty(exports, "__esModule", ({ value: true })); -var express_1 = __nccwpck_require__(96221); -exports.Express = express_1.Express; -var postgres_1 = __nccwpck_require__(31931); -exports.Postgres = postgres_1.Postgres; -var mysql_1 = __nccwpck_require__(67082); -exports.Mysql = mysql_1.Mysql; -var mongo_1 = __nccwpck_require__(22606); -exports.Mongo = mongo_1.Mongo; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 22606: -/***/ ((module, exports, __nccwpck_require__) => { - -/* module decorator */ module = __nccwpck_require__.nmd(module); Object.defineProperty(exports, "__esModule", ({ value: true })); var tslib_1 = __nccwpck_require__(4351); +var hub_1 = __nccwpck_require__(6393); var utils_1 = __nccwpck_require__(1620); -var OPERATIONS = [ - 'aggregate', - 'bulkWrite', - 'countDocuments', - 'createIndex', - 'createIndexes', - 'deleteMany', - 'deleteOne', - 'distinct', - 'drop', - 'dropIndex', - 'dropIndexes', - 'estimatedDocumentCount', - 'findOne', - 'findOneAndDelete', - 'findOneAndReplace', - 'findOneAndUpdate', - 'indexes', - 'indexExists', - 'indexInformation', - 'initializeOrderedBulkOp', - 'insertMany', - 'insertOne', - 'isCapped', - 'mapReduce', - 'options', - 'parallelCollectionScan', - 'rename', - 'replaceOne', - 'stats', - 'updateMany', - 'updateOne', -]; -// All of the operations above take `options` and `callback` as their final parameters, but some of them -// take additional parameters as well. For those operations, this is a map of -// { : [] }, as a way to know what to call the operation's -// positional arguments when we add them to the span's `data` object later -var OPERATION_SIGNATURES = { - // aggregate intentionally not included because `pipeline` arguments are too complex to serialize well - // see https://github.com/getsentry/sentry-javascript/pull/3102 - bulkWrite: ['operations'], - countDocuments: ['query'], - createIndex: ['fieldOrSpec'], - createIndexes: ['indexSpecs'], - deleteMany: ['filter'], - deleteOne: ['filter'], - distinct: ['key', 'query'], - dropIndex: ['indexName'], - findOne: ['query'], - findOneAndDelete: ['filter'], - findOneAndReplace: ['filter', 'replacement'], - findOneAndUpdate: ['filter', 'update'], - indexExists: ['indexes'], - insertMany: ['docs'], - insertOne: ['doc'], - mapReduce: ['map', 'reduce'], - rename: ['newName'], - replaceOne: ['filter', 'doc'], - updateMany: ['filter', 'update'], - updateOne: ['filter', 'update'], -}; -/** Tracing integration for mongo package */ -var Mongo = /** @class */ (function () { - /** - * @inheritDoc - */ - function Mongo(options) { - if (options === void 0) { options = {}; } +// "Script error." is hard coded into browsers for errors that it can't read. +// this is the result of a script being pulled in from an external domain and CORS. +var DEFAULT_IGNORE_ERRORS = [/^Script error\.?$/, /^Javascript error: Script error\.? on line 0$/]; +/** Inbound filters configurable by the user */ +var InboundFilters = /** @class */ (function () { + function InboundFilters(_options) { + if (_options === void 0) { _options = {}; } + this._options = _options; /** * @inheritDoc */ - this.name = Mongo.id; - this._operations = Array.isArray(options.operations) - ? options.operations - : OPERATIONS; - this._describeOperations = 'describeOperations' in options ? options.describeOperations : true; + this.name = InboundFilters.id; } /** * @inheritDoc */ - Mongo.prototype.setupOnce = function (_, getCurrentHub) { - var collection; - try { - var mongodbModule = utils_1.dynamicRequire(module, 'mongodb'); - collection = mongodbModule.Collection; + InboundFilters.prototype.setupOnce = function () { + hub_1.addGlobalEventProcessor(function (event) { + var hub = hub_1.getCurrentHub(); + if (!hub) { + return event; + } + var self = hub.getIntegration(InboundFilters); + if (self) { + var client = hub.getClient(); + var clientOptions = client ? client.getOptions() : {}; + // This checks prevents most of the occurrences of the bug linked below: + // https://github.com/getsentry/sentry-javascript/issues/2622 + // The bug is caused by multiple SDK instances, where one is minified and one is using non-mangled code. + // Unfortunatelly we cannot fix it reliably (thus reserved property in rollup's terser config), + // as we cannot force people using multiple instances in their apps to sync SDK versions. + var options = typeof self._mergeOptions === 'function' ? self._mergeOptions(clientOptions) : {}; + if (typeof self._shouldDropEvent !== 'function') { + return event; + } + return self._shouldDropEvent(event, options) ? null : event; + } + return event; + }); + }; + /** JSDoc */ + InboundFilters.prototype._shouldDropEvent = function (event, options) { + if (this._isSentryError(event, options)) { + utils_1.logger.warn("Event dropped due to being internal Sentry Error.\nEvent: " + utils_1.getEventDescription(event)); + return true; } - catch (e) { - utils_1.logger.error('Mongo Integration was unable to require `mongodb` package.'); - return; + if (this._isIgnoredError(event, options)) { + utils_1.logger.warn("Event dropped due to being matched by `ignoreErrors` option.\nEvent: " + utils_1.getEventDescription(event)); + return true; + } + if (this._isDeniedUrl(event, options)) { + utils_1.logger.warn("Event dropped due to being matched by `denyUrls` option.\nEvent: " + utils_1.getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event)); + return true; + } + if (!this._isAllowedUrl(event, options)) { + utils_1.logger.warn("Event dropped due to not being matched by `allowUrls` option.\nEvent: " + utils_1.getEventDescription(event) + ".\nUrl: " + this._getEventFilterUrl(event)); + return true; } - this._instrumentOperations(collection, this._operations, getCurrentHub); + return false; }; - /** - * Patches original collection methods - */ - Mongo.prototype._instrumentOperations = function (collection, operations, getCurrentHub) { - var _this = this; - operations.forEach(function (operation) { return _this._patchOperation(collection, operation, getCurrentHub); }); + /** JSDoc */ + InboundFilters.prototype._isSentryError = function (event, options) { + if (!options.ignoreInternal) { + return false; + } + try { + return ((event && + event.exception && + event.exception.values && + event.exception.values[0] && + event.exception.values[0].type === 'SentryError') || + false); + } + catch (_oO) { + return false; + } }; - /** - * Patches original collection to utilize our tracing functionality - */ - Mongo.prototype._patchOperation = function (collection, operation, getCurrentHub) { - if (!(operation in collection.prototype)) - return; - var getSpanContext = this._getSpanContextFromOperationArguments.bind(this); - utils_1.fill(collection.prototype, operation, function (orig) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var _a, _b, _c; - var lastArg = args[args.length - 1]; - var scope = getCurrentHub().getScope(); - var parentSpan = (_a = scope) === null || _a === void 0 ? void 0 : _a.getSpan(); - // Check if the operation was passed a callback. (mapReduce requires a different check, as - // its (non-callback) arguments can also be functions.) - if (typeof lastArg !== 'function' || (operation === 'mapReduce' && args.length === 2)) { - var span_1 = (_b = parentSpan) === null || _b === void 0 ? void 0 : _b.startChild(getSpanContext(this, operation, args)); - return orig.call.apply(orig, tslib_1.__spread([this], args)).then(function (res) { - var _a; - (_a = span_1) === null || _a === void 0 ? void 0 : _a.finish(); - return res; - }); - } - var span = (_c = parentSpan) === null || _c === void 0 ? void 0 : _c.startChild(getSpanContext(this, operation, args.slice(0, -1))); - return orig.call.apply(orig, tslib_1.__spread([this], args.slice(0, -1), [function (err, result) { - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - lastArg(err, result); - }])); - }; + /** JSDoc */ + InboundFilters.prototype._isIgnoredError = function (event, options) { + if (!options.ignoreErrors || !options.ignoreErrors.length) { + return false; + } + return this._getPossibleEventMessages(event).some(function (message) { + // Not sure why TypeScript complains here... + return options.ignoreErrors.some(function (pattern) { return utils_1.isMatchingPattern(message, pattern); }); }); }; - /** - * Form a SpanContext based on the user input to a given operation. - */ - Mongo.prototype._getSpanContextFromOperationArguments = function (collection, operation, args) { - var data = { - collectionName: collection.collectionName, - dbName: collection.dbName, - namespace: collection.namespace, - }; - var spanContext = { - op: "db", - description: operation, - data: data, + /** JSDoc */ + InboundFilters.prototype._isDeniedUrl = function (event, options) { + // TODO: Use Glob instead? + if (!options.denyUrls || !options.denyUrls.length) { + return false; + } + var url = this._getEventFilterUrl(event); + return !url ? false : options.denyUrls.some(function (pattern) { return utils_1.isMatchingPattern(url, pattern); }); + }; + /** JSDoc */ + InboundFilters.prototype._isAllowedUrl = function (event, options) { + // TODO: Use Glob instead? + if (!options.allowUrls || !options.allowUrls.length) { + return true; + } + var url = this._getEventFilterUrl(event); + return !url ? true : options.allowUrls.some(function (pattern) { return utils_1.isMatchingPattern(url, pattern); }); + }; + /** JSDoc */ + InboundFilters.prototype._mergeOptions = function (clientOptions) { + if (clientOptions === void 0) { clientOptions = {}; } + return { + allowUrls: tslib_1.__spread((this._options.whitelistUrls || []), (this._options.allowUrls || []), (clientOptions.whitelistUrls || []), (clientOptions.allowUrls || [])), + denyUrls: tslib_1.__spread((this._options.blacklistUrls || []), (this._options.denyUrls || []), (clientOptions.blacklistUrls || []), (clientOptions.denyUrls || [])), + ignoreErrors: tslib_1.__spread((this._options.ignoreErrors || []), (clientOptions.ignoreErrors || []), DEFAULT_IGNORE_ERRORS), + ignoreInternal: typeof this._options.ignoreInternal !== 'undefined' ? this._options.ignoreInternal : true, }; - // If the operation takes no arguments besides `options` and `callback`, or if argument - // collection is disabled for this operation, just return early. - var signature = OPERATION_SIGNATURES[operation]; - var shouldDescribe = Array.isArray(this._describeOperations) - ? this._describeOperations.includes(operation) - : this._describeOperations; - if (!signature || !shouldDescribe) { - return spanContext; + }; + /** JSDoc */ + InboundFilters.prototype._getPossibleEventMessages = function (event) { + if (event.message) { + return [event.message]; } - try { - // Special case for `mapReduce`, as the only one accepting functions as arguments. - if (operation === 'mapReduce') { - var _a = tslib_1.__read(args, 2), map = _a[0], reduce = _a[1]; - data[signature[0]] = typeof map === 'string' ? map : map.name || ''; - data[signature[1]] = typeof reduce === 'string' ? reduce : reduce.name || ''; + if (event.exception) { + try { + var _a = (event.exception.values && event.exception.values[0]) || {}, _b = _a.type, type = _b === void 0 ? '' : _b, _c = _a.value, value = _c === void 0 ? '' : _c; + return ["" + value, type + ": " + value]; } - else { - for (var i = 0; i < signature.length; i++) { - data[signature[i]] = JSON.stringify(args[i]); - } + catch (oO) { + utils_1.logger.error("Cannot extract message for event " + utils_1.getEventDescription(event)); + return []; + } + } + return []; + }; + /** JSDoc */ + InboundFilters.prototype._getLastValidUrl = function (frames) { + if (frames === void 0) { frames = []; } + var _a; + for (var i = frames.length - 1; i >= 0; i--) { + var frame = frames[i]; + if (((_a = frame) === null || _a === void 0 ? void 0 : _a.filename) !== '') { + return frame.filename || null; + } + } + return null; + }; + /** JSDoc */ + InboundFilters.prototype._getEventFilterUrl = function (event) { + try { + if (event.stacktrace) { + var frames_1 = event.stacktrace.frames; + return this._getLastValidUrl(frames_1); + } + if (event.exception) { + var frames_2 = event.exception.values && event.exception.values[0].stacktrace && event.exception.values[0].stacktrace.frames; + return this._getLastValidUrl(frames_2); } + return null; } - catch (_oO) { - // no-empty + catch (oO) { + utils_1.logger.error("Cannot extract url for event " + utils_1.getEventDescription(event)); + return null; } - return spanContext; }; /** * @inheritDoc */ - Mongo.id = 'Mongo'; - return Mongo; + InboundFilters.id = 'InboundFilters'; + return InboundFilters; }()); -exports.Mongo = Mongo; -//# sourceMappingURL=mongo.js.map +exports.InboundFilters = InboundFilters; +//# sourceMappingURL=inboundfilters.js.map /***/ }), -/***/ 67082: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 96727: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* module decorator */ module = __nccwpck_require__.nmd(module); Object.defineProperty(exports, "__esModule", ({ value: true })); -var utils_1 = __nccwpck_require__(1620); -/** Tracing integration for node-mysql package */ -var Mysql = /** @class */ (function () { - function Mysql() { - /** - * @inheritDoc - */ - this.name = Mysql.id; +var functiontostring_1 = __nccwpck_require__(87349); +exports.FunctionToString = functiontostring_1.FunctionToString; +var inboundfilters_1 = __nccwpck_require__(54838); +exports.InboundFilters = inboundfilters_1.InboundFilters; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 1553: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +/** Extract sdk info from from the API metadata */ +function getSdkMetadataForEnvelopeHeader(api) { + if (!api.metadata || !api.metadata.sdk) { + return; } - /** - * @inheritDoc - */ - Mysql.prototype.setupOnce = function (_, getCurrentHub) { - var connection; - try { - // Unfortunatelly mysql is using some custom loading system and `Connection` is not exported directly. - connection = utils_1.dynamicRequire(module, 'mysql/lib/Connection.js'); - } - catch (e) { - utils_1.logger.error('Mysql Integration was unable to require `mysql` package.'); - return; - } - // The original function will have one of these signatures: - // function (callback) => void - // function (options, callback) => void - // function (options, values, callback) => void - utils_1.fill(connection.prototype, 'query', function (orig) { - return function (options, values, callback) { - var _a, _b; - var scope = getCurrentHub().getScope(); - var parentSpan = (_a = scope) === null || _a === void 0 ? void 0 : _a.getSpan(); - var span = (_b = parentSpan) === null || _b === void 0 ? void 0 : _b.startChild({ - description: typeof options === 'string' ? options : options.sql, - op: "db", - }); - if (typeof callback === 'function') { - return orig.call(this, options, values, function (err, result, fields) { - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - callback(err, result, fields); - }); - } - if (typeof values === 'function') { - return orig.call(this, options, function (err, result, fields) { - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - values(err, result, fields); - }); - } - return orig.call(this, options, values, callback); - }; - }); + var _a = api.metadata.sdk, name = _a.name, version = _a.version; + return { name: name, version: version }; +} +/** + * Apply SdkInfo (name, version, packages, integrations) to the corresponding event key. + * Merge with existing data if any. + **/ +function enhanceEventWithSdkInfo(event, sdkInfo) { + if (!sdkInfo) { + return event; + } + event.sdk = event.sdk || {}; + event.sdk.name = event.sdk.name || sdkInfo.name; + event.sdk.version = event.sdk.version || sdkInfo.version; + event.sdk.integrations = tslib_1.__spread((event.sdk.integrations || []), (sdkInfo.integrations || [])); + event.sdk.packages = tslib_1.__spread((event.sdk.packages || []), (sdkInfo.packages || [])); + return event; +} +/** Creates a SentryRequest from a Session. */ +function sessionToSentryRequest(session, api) { + var sdkInfo = getSdkMetadataForEnvelopeHeader(api); + var envelopeHeaders = JSON.stringify(tslib_1.__assign(tslib_1.__assign({ sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (api.forceEnvelope() && { dsn: api.getDsn().toString() }))); + // I know this is hacky but we don't want to add `session` to request type since it's never rate limited + var type = 'aggregates' in session ? 'sessions' : 'session'; + var itemHeaders = JSON.stringify({ + type: type, + }); + return { + body: envelopeHeaders + "\n" + itemHeaders + "\n" + JSON.stringify(session), + type: type, + url: api.getEnvelopeEndpointWithUrlEncodedAuth(), }; - /** - * @inheritDoc - */ - Mysql.id = 'Mysql'; - return Mysql; -}()); -exports.Mysql = Mysql; -//# sourceMappingURL=mysql.js.map +} +exports.sessionToSentryRequest = sessionToSentryRequest; +/** Creates a SentryRequest from an event. */ +function eventToSentryRequest(event, api) { + var sdkInfo = getSdkMetadataForEnvelopeHeader(api); + var eventType = event.type || 'event'; + var useEnvelope = eventType === 'transaction' || api.forceEnvelope(); + var _a = event.debug_meta || {}, transactionSampling = _a.transactionSampling, metadata = tslib_1.__rest(_a, ["transactionSampling"]); + var _b = transactionSampling || {}, samplingMethod = _b.method, sampleRate = _b.rate; + if (Object.keys(metadata).length === 0) { + delete event.debug_meta; + } + else { + event.debug_meta = metadata; + } + var req = { + body: JSON.stringify(sdkInfo ? enhanceEventWithSdkInfo(event, api.metadata.sdk) : event), + type: eventType, + url: useEnvelope ? api.getEnvelopeEndpointWithUrlEncodedAuth() : api.getStoreEndpointWithUrlEncodedAuth(), + }; + // https://develop.sentry.dev/sdk/envelopes/ + // Since we don't need to manipulate envelopes nor store them, there is no + // exported concept of an Envelope with operations including serialization and + // deserialization. Instead, we only implement a minimal subset of the spec to + // serialize events inline here. + if (useEnvelope) { + var envelopeHeaders = JSON.stringify(tslib_1.__assign(tslib_1.__assign({ event_id: event.event_id, sent_at: new Date().toISOString() }, (sdkInfo && { sdk: sdkInfo })), (api.forceEnvelope() && { dsn: api.getDsn().toString() }))); + var itemHeaders = JSON.stringify({ + type: eventType, + // TODO: Right now, sampleRate may or may not be defined (it won't be in the cases of inheritance and + // explicitly-set sampling decisions). Are we good with that? + sample_rates: [{ id: samplingMethod, rate: sampleRate }], + }); + // The trailing newline is optional. We intentionally don't send it to avoid + // sending unnecessary bytes. + // + // const envelope = `${envelopeHeaders}\n${itemHeaders}\n${req.body}\n`; + var envelope = envelopeHeaders + "\n" + itemHeaders + "\n" + req.body; + req.body = envelope; + } + return req; +} +exports.eventToSentryRequest = eventToSentryRequest; +//# sourceMappingURL=request.js.map /***/ }), -/***/ 31931: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 46406: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* module decorator */ module = __nccwpck_require__.nmd(module); Object.defineProperty(exports, "__esModule", ({ value: true })); +var hub_1 = __nccwpck_require__(6393); var utils_1 = __nccwpck_require__(1620); -/** Tracing integration for node-postgres package */ -var Postgres = /** @class */ (function () { - function Postgres() { - /** - * @inheritDoc - */ - this.name = Postgres.id; +/** + * Internal function to create a new SDK client instance. The client is + * installed and then bound to the current scope. + * + * @param clientClass The client class to instantiate. + * @param options Options to pass to the client. + */ +function initAndBind(clientClass, options) { + var _a; + if (options.debug === true) { + utils_1.logger.enable(); + } + var hub = hub_1.getCurrentHub(); + (_a = hub.getScope()) === null || _a === void 0 ? void 0 : _a.update(options.initialScope); + var client = new clientClass(options); + hub.bindClient(client); +} +exports.initAndBind = initAndBind; +//# sourceMappingURL=sdk.js.map + +/***/ }), + +/***/ 68641: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +/** Noop transport */ +var NoopTransport = /** @class */ (function () { + function NoopTransport() { } /** * @inheritDoc */ - Postgres.prototype.setupOnce = function (_, getCurrentHub) { - var client; - try { - var pgModule = utils_1.dynamicRequire(module, 'pg'); - client = pgModule.Client; - } - catch (e) { - utils_1.logger.error('Postgres Integration was unable to require `pg` package.'); - return; - } - /** - * function (query, callback) => void - * function (query, params, callback) => void - * function (query) => Promise - * function (query, params) => Promise - */ - utils_1.fill(client.prototype, 'query', function (orig) { - return function (config, values, callback) { - var _a, _b; - var scope = getCurrentHub().getScope(); - var parentSpan = (_a = scope) === null || _a === void 0 ? void 0 : _a.getSpan(); - var span = (_b = parentSpan) === null || _b === void 0 ? void 0 : _b.startChild({ - description: typeof config === 'string' ? config : config.text, - op: "db", - }); - if (typeof callback === 'function') { - return orig.call(this, config, values, function (err, result) { - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - callback(err, result); - }); - } - if (typeof values === 'function') { - return orig.call(this, config, function (err, result) { - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - values(err, result); - }); - } - return orig.call(this, config, values).then(function (res) { - var _a; - (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); - return res; - }); - }; + NoopTransport.prototype.sendEvent = function (_) { + return utils_1.SyncPromise.resolve({ + reason: "NoopTransport: Event has been skipped because no Dsn is configured.", + status: types_1.Status.Skipped, }); }; /** * @inheritDoc */ - Postgres.id = 'Postgres'; - return Postgres; + NoopTransport.prototype.close = function (_) { + return utils_1.SyncPromise.resolve(true); + }; + return NoopTransport; }()); -exports.Postgres = Postgres; -//# sourceMappingURL=postgres.js.map +exports.NoopTransport = NoopTransport; +//# sourceMappingURL=noop.js.map /***/ }), -/***/ 64655: +/***/ 33493: +/***/ ((__unused_webpack_module, exports) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SDK_VERSION = '6.11.0'; +//# sourceMappingURL=version.js.map + +/***/ }), + +/***/ 53536: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); var tslib_1 = __nccwpck_require__(4351); +/* eslint-disable max-lines */ +var types_1 = __nccwpck_require__(83789); var utils_1 = __nccwpck_require__(1620); -var spanstatus_1 = __nccwpck_require__(58522); +var scope_1 = __nccwpck_require__(4213); +var session_1 = __nccwpck_require__(12474); /** - * Keeps track of finished spans for a given transaction - * @internal - * @hideconstructor + * API compatibility version of this hub. + * + * WARNING: This number should only be increased when the global interface + * changes and new methods are introduced. + * * @hidden */ -var SpanRecorder = /** @class */ (function () { - function SpanRecorder(maxlen) { - if (maxlen === void 0) { maxlen = 1000; } - this.spans = []; - this._maxlen = maxlen; - } +exports.API_VERSION = 4; +/** + * Default maximum number of breadcrumbs added to an event. Can be overwritten + * with {@link Options.maxBreadcrumbs}. + */ +var DEFAULT_BREADCRUMBS = 100; +/** + * @inheritDoc + */ +var Hub = /** @class */ (function () { /** - * This is just so that we don't run out of memory while recording a lot - * of spans. At some point we just stop and flush out the start of the - * trace tree (i.e.the first n spans with the smallest - * start_timestamp). + * Creates a new instance of the hub, will push one {@link Layer} into the + * internal stack on creation. + * + * @param client bound to the hub. + * @param scope bound to the hub. + * @param version number, higher number means higher priority. */ - SpanRecorder.prototype.add = function (span) { - if (this.spans.length > this._maxlen) { - span.spanRecorder = undefined; - } - else { - this.spans.push(span); + function Hub(client, scope, _version) { + if (scope === void 0) { scope = new scope_1.Scope(); } + if (_version === void 0) { _version = exports.API_VERSION; } + this._version = _version; + /** Is a {@link Layer}[] containing the client and scope */ + this._stack = [{}]; + this.getStackTop().scope = scope; + if (client) { + this.bindClient(client); } + } + /** + * @inheritDoc + */ + Hub.prototype.isOlderThan = function (version) { + return this._version < version; }; - return SpanRecorder; -}()); -exports.SpanRecorder = SpanRecorder; -/** - * Span contains all data about a span - */ -var Span = /** @class */ (function () { /** - * You should never call the constructor manually, always use `Sentry.startTransaction()` - * or call `startChild()` on an existing span. - * @internal - * @hideconstructor - * @hidden + * @inheritDoc */ - function Span(spanContext) { - /** - * @inheritDoc - */ - this.traceId = utils_1.uuid4(); - /** - * @inheritDoc - */ - this.spanId = utils_1.uuid4().substring(16); - /** - * Timestamp in seconds when the span was created. - */ - this.startTimestamp = utils_1.timestampWithMs(); - /** - * @inheritDoc - */ - this.tags = {}; - /** - * @inheritDoc - */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.data = {}; - if (!spanContext) { - return this; - } - if (spanContext.traceId) { - this.traceId = spanContext.traceId; - } - if (spanContext.spanId) { - this.spanId = spanContext.spanId; - } - if (spanContext.parentSpanId) { - this.parentSpanId = spanContext.parentSpanId; - } - // We want to include booleans as well here - if ('sampled' in spanContext) { - this.sampled = spanContext.sampled; - } - if (spanContext.op) { - this.op = spanContext.op; - } - if (spanContext.description) { - this.description = spanContext.description; - } - if (spanContext.data) { - this.data = spanContext.data; + Hub.prototype.bindClient = function (client) { + var top = this.getStackTop(); + top.client = client; + if (client && client.setupIntegrations) { + client.setupIntegrations(); } - if (spanContext.tags) { - this.tags = spanContext.tags; + }; + /** + * @inheritDoc + */ + Hub.prototype.pushScope = function () { + // We want to clone the content of prev scope + var scope = scope_1.Scope.clone(this.getScope()); + this.getStack().push({ + client: this.getClient(), + scope: scope, + }); + return scope; + }; + /** + * @inheritDoc + */ + Hub.prototype.popScope = function () { + if (this.getStack().length <= 1) + return false; + return !!this.getStack().pop(); + }; + /** + * @inheritDoc + */ + Hub.prototype.withScope = function (callback) { + var scope = this.pushScope(); + try { + callback(scope); } - if (spanContext.status) { - this.status = spanContext.status; + finally { + this.popScope(); } - if (spanContext.startTimestamp) { - this.startTimestamp = spanContext.startTimestamp; + }; + /** + * @inheritDoc + */ + Hub.prototype.getClient = function () { + return this.getStackTop().client; + }; + /** Returns the scope of the top stack. */ + Hub.prototype.getScope = function () { + return this.getStackTop().scope; + }; + /** Returns the scope stack for domains or the process. */ + Hub.prototype.getStack = function () { + return this._stack; + }; + /** Returns the topmost scope layer in the order domain > local > process. */ + Hub.prototype.getStackTop = function () { + return this._stack[this._stack.length - 1]; + }; + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + Hub.prototype.captureException = function (exception, hint) { + var eventId = (this._lastEventId = utils_1.uuid4()); + var finalHint = hint; + // If there's no explicit hint provided, mimic the same thing that would happen + // in the minimal itself to create a consistent behavior. + // We don't do this in the client, as it's the lowest level API, and doing this, + // would prevent user from having full control over direct calls. + if (!hint) { + var syntheticException = void 0; + try { + throw new Error('Sentry syntheticException'); + } + catch (exception) { + syntheticException = exception; + } + finalHint = { + originalException: exception, + syntheticException: syntheticException, + }; } - if (spanContext.endTimestamp) { - this.endTimestamp = spanContext.endTimestamp; + this._invokeClient('captureException', exception, tslib_1.__assign(tslib_1.__assign({}, finalHint), { event_id: eventId })); + return eventId; + }; + /** + * @inheritDoc + */ + Hub.prototype.captureMessage = function (message, level, hint) { + var eventId = (this._lastEventId = utils_1.uuid4()); + var finalHint = hint; + // If there's no explicit hint provided, mimic the same thing that would happen + // in the minimal itself to create a consistent behavior. + // We don't do this in the client, as it's the lowest level API, and doing this, + // would prevent user from having full control over direct calls. + if (!hint) { + var syntheticException = void 0; + try { + throw new Error(message); + } + catch (exception) { + syntheticException = exception; + } + finalHint = { + originalException: message, + syntheticException: syntheticException, + }; } - } + this._invokeClient('captureMessage', message, level, tslib_1.__assign(tslib_1.__assign({}, finalHint), { event_id: eventId })); + return eventId; + }; /** * @inheritDoc - * @deprecated */ - Span.prototype.child = function (spanContext) { - return this.startChild(spanContext); + Hub.prototype.captureEvent = function (event, hint) { + var eventId = (this._lastEventId = utils_1.uuid4()); + this._invokeClient('captureEvent', event, tslib_1.__assign(tslib_1.__assign({}, hint), { event_id: eventId })); + return eventId; }; /** * @inheritDoc */ - Span.prototype.startChild = function (spanContext) { - var childSpan = new Span(tslib_1.__assign(tslib_1.__assign({}, spanContext), { parentSpanId: this.spanId, sampled: this.sampled, traceId: this.traceId })); - childSpan.spanRecorder = this.spanRecorder; - if (childSpan.spanRecorder) { - childSpan.spanRecorder.add(childSpan); - } - childSpan.transaction = this.transaction; - return childSpan; + Hub.prototype.lastEventId = function () { + return this._lastEventId; }; /** * @inheritDoc */ - Span.prototype.setTag = function (key, value) { - var _a; - this.tags = tslib_1.__assign(tslib_1.__assign({}, this.tags), (_a = {}, _a[key] = value, _a)); - return this; + Hub.prototype.addBreadcrumb = function (breadcrumb, hint) { + var _a = this.getStackTop(), scope = _a.scope, client = _a.client; + if (!scope || !client) + return; + // eslint-disable-next-line @typescript-eslint/unbound-method + var _b = (client.getOptions && client.getOptions()) || {}, _c = _b.beforeBreadcrumb, beforeBreadcrumb = _c === void 0 ? null : _c, _d = _b.maxBreadcrumbs, maxBreadcrumbs = _d === void 0 ? DEFAULT_BREADCRUMBS : _d; + if (maxBreadcrumbs <= 0) + return; + var timestamp = utils_1.dateTimestampInSeconds(); + var mergedBreadcrumb = tslib_1.__assign({ timestamp: timestamp }, breadcrumb); + var finalBreadcrumb = beforeBreadcrumb + ? utils_1.consoleSandbox(function () { return beforeBreadcrumb(mergedBreadcrumb, hint); }) + : mergedBreadcrumb; + if (finalBreadcrumb === null) + return; + scope.addBreadcrumb(finalBreadcrumb, maxBreadcrumbs); }; /** * @inheritDoc */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types - Span.prototype.setData = function (key, value) { - var _a; - this.data = tslib_1.__assign(tslib_1.__assign({}, this.data), (_a = {}, _a[key] = value, _a)); - return this; + Hub.prototype.setUser = function (user) { + var scope = this.getScope(); + if (scope) + scope.setUser(user); }; /** * @inheritDoc */ - Span.prototype.setStatus = function (value) { - this.status = value; - return this; + Hub.prototype.setTags = function (tags) { + var scope = this.getScope(); + if (scope) + scope.setTags(tags); }; /** * @inheritDoc */ - Span.prototype.setHttpStatus = function (httpStatus) { - this.setTag('http.status_code', String(httpStatus)); - var spanStatus = spanstatus_1.SpanStatus.fromHttpCode(httpStatus); - if (spanStatus !== spanstatus_1.SpanStatus.UnknownError) { - this.setStatus(spanStatus); - } - return this; + Hub.prototype.setExtras = function (extras) { + var scope = this.getScope(); + if (scope) + scope.setExtras(extras); }; /** * @inheritDoc */ - Span.prototype.isSuccess = function () { - return this.status === spanstatus_1.SpanStatus.Ok; + Hub.prototype.setTag = function (key, value) { + var scope = this.getScope(); + if (scope) + scope.setTag(key, value); }; /** * @inheritDoc */ - Span.prototype.finish = function (endTimestamp) { - this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : utils_1.timestampWithMs(); + Hub.prototype.setExtra = function (key, extra) { + var scope = this.getScope(); + if (scope) + scope.setExtra(key, extra); }; /** * @inheritDoc */ - Span.prototype.toTraceparent = function () { - var sampledString = ''; - if (this.sampled !== undefined) { - sampledString = this.sampled ? '-1' : '-0'; - } - return this.traceId + "-" + this.spanId + sampledString; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Hub.prototype.setContext = function (name, context) { + var scope = this.getScope(); + if (scope) + scope.setContext(name, context); }; /** * @inheritDoc */ - Span.prototype.getTraceContext = function () { - return utils_1.dropUndefinedKeys({ - data: Object.keys(this.data).length > 0 ? this.data : undefined, - description: this.description, - op: this.op, - parent_span_id: this.parentSpanId, - span_id: this.spanId, - status: this.status, - tags: Object.keys(this.tags).length > 0 ? this.tags : undefined, - trace_id: this.traceId, - }); + Hub.prototype.configureScope = function (callback) { + var _a = this.getStackTop(), scope = _a.scope, client = _a.client; + if (scope && client) { + callback(scope); + } }; /** * @inheritDoc */ - Span.prototype.toJSON = function () { - return utils_1.dropUndefinedKeys({ - data: Object.keys(this.data).length > 0 ? this.data : undefined, - description: this.description, - op: this.op, - parent_span_id: this.parentSpanId, - span_id: this.spanId, - start_timestamp: this.startTimestamp, - status: this.status, - tags: Object.keys(this.tags).length > 0 ? this.tags : undefined, - timestamp: this.endTimestamp, - trace_id: this.traceId, - }); + Hub.prototype.run = function (callback) { + var oldHub = makeMain(this); + try { + callback(this); + } + finally { + makeMain(oldHub); + } }; - return Span; -}()); -exports.Span = Span; -//# sourceMappingURL=span.js.map - -/***/ }), - -/***/ 58522: -/***/ ((__unused_webpack_module, exports) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** The status of an Span. */ -// eslint-disable-next-line import/export -var SpanStatus; -(function (SpanStatus) { - /** The operation completed successfully. */ - SpanStatus["Ok"] = "ok"; - /** Deadline expired before operation could complete. */ - SpanStatus["DeadlineExceeded"] = "deadline_exceeded"; - /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */ - SpanStatus["Unauthenticated"] = "unauthenticated"; - /** 403 Forbidden */ - SpanStatus["PermissionDenied"] = "permission_denied"; - /** 404 Not Found. Some requested entity (file or directory) was not found. */ - SpanStatus["NotFound"] = "not_found"; - /** 429 Too Many Requests */ - SpanStatus["ResourceExhausted"] = "resource_exhausted"; - /** Client specified an invalid argument. 4xx. */ - SpanStatus["InvalidArgument"] = "invalid_argument"; - /** 501 Not Implemented */ - SpanStatus["Unimplemented"] = "unimplemented"; - /** 503 Service Unavailable */ - SpanStatus["Unavailable"] = "unavailable"; - /** Other/generic 5xx. */ - SpanStatus["InternalError"] = "internal_error"; - /** Unknown. Any non-standard HTTP status code. */ - SpanStatus["UnknownError"] = "unknown_error"; - /** The operation was cancelled (typically by the user). */ - SpanStatus["Cancelled"] = "cancelled"; - /** Already exists (409) */ - SpanStatus["AlreadyExists"] = "already_exists"; - /** Operation was rejected because the system is not in a state required for the operation's */ - SpanStatus["FailedPrecondition"] = "failed_precondition"; - /** The operation was aborted, typically due to a concurrency issue. */ - SpanStatus["Aborted"] = "aborted"; - /** Operation was attempted past the valid range. */ - SpanStatus["OutOfRange"] = "out_of_range"; - /** Unrecoverable data loss or corruption */ - SpanStatus["DataLoss"] = "data_loss"; -})(SpanStatus = exports.SpanStatus || (exports.SpanStatus = {})); -// eslint-disable-next-line @typescript-eslint/no-namespace, import/export -(function (SpanStatus) { /** - * Converts a HTTP status code into a {@link SpanStatus}. - * - * @param httpStatus The HTTP response status code. - * @returns The span status or {@link SpanStatus.UnknownError}. + * @inheritDoc */ - function fromHttpCode(httpStatus) { - if (httpStatus < 400) { - return SpanStatus.Ok; - } - if (httpStatus >= 400 && httpStatus < 500) { - switch (httpStatus) { - case 401: - return SpanStatus.Unauthenticated; - case 403: - return SpanStatus.PermissionDenied; - case 404: - return SpanStatus.NotFound; - case 409: - return SpanStatus.AlreadyExists; - case 413: - return SpanStatus.FailedPrecondition; - case 429: - return SpanStatus.ResourceExhausted; - default: - return SpanStatus.InvalidArgument; - } + Hub.prototype.getIntegration = function (integration) { + var client = this.getClient(); + if (!client) + return null; + try { + return client.getIntegration(integration); } - if (httpStatus >= 500 && httpStatus < 600) { - switch (httpStatus) { - case 501: - return SpanStatus.Unimplemented; - case 503: - return SpanStatus.Unavailable; - case 504: - return SpanStatus.DeadlineExceeded; - default: - return SpanStatus.InternalError; - } + catch (_oO) { + utils_1.logger.warn("Cannot retrieve integration " + integration.id + " from the current Hub"); + return null; } - return SpanStatus.UnknownError; - } - SpanStatus.fromHttpCode = fromHttpCode; -})(SpanStatus = exports.SpanStatus || (exports.SpanStatus = {})); -//# sourceMappingURL=spanstatus.js.map - -/***/ }), - -/***/ 8186: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var hub_1 = __nccwpck_require__(6393); -var utils_1 = __nccwpck_require__(1620); -var span_1 = __nccwpck_require__(64655); -/** JSDoc */ -var Transaction = /** @class */ (function (_super) { - tslib_1.__extends(Transaction, _super); + }; /** - * This constructor should never be called manually. Those instrumenting tracing should use - * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`. - * @internal - * @hideconstructor - * @hidden + * @inheritDoc */ - function Transaction(transactionContext, hub) { - var _this = _super.call(this, transactionContext) || this; - _this._measurements = {}; - /** - * The reference to the current hub. - */ - _this._hub = hub_1.getCurrentHub(); - if (utils_1.isInstanceOf(hub, hub_1.Hub)) { - _this._hub = hub; - } - _this.name = transactionContext.name ? transactionContext.name : ''; - _this._trimEnd = transactionContext.trimEnd; - // this is because transactions are also spans, and spans have a transaction pointer - _this.transaction = _this; - return _this; - } + Hub.prototype.startSpan = function (context) { + return this._callExtensionMethod('startSpan', context); + }; /** - * JSDoc + * @inheritDoc */ - Transaction.prototype.setName = function (name) { - this.name = name; + Hub.prototype.startTransaction = function (context, customSamplingContext) { + return this._callExtensionMethod('startTransaction', context, customSamplingContext); }; /** - * Attaches SpanRecorder to the span itself - * @param maxlen maximum number of spans that can be recorded + * @inheritDoc */ - Transaction.prototype.initSpanRecorder = function (maxlen) { - if (maxlen === void 0) { maxlen = 1000; } - if (!this.spanRecorder) { - this.spanRecorder = new span_1.SpanRecorder(maxlen); - } - this.spanRecorder.add(this); + Hub.prototype.traceHeaders = function () { + return this._callExtensionMethod('traceHeaders'); }; /** - * Set observed measurements for this transaction. - * @hidden + * @inheritDoc */ - Transaction.prototype.setMeasurements = function (measurements) { - this._measurements = tslib_1.__assign({}, measurements); + Hub.prototype.captureSession = function (endSession) { + if (endSession === void 0) { endSession = false; } + // both send the update and pull the session from the scope + if (endSession) { + return this.endSession(); + } + // only send the update + this._sendSessionUpdate(); }; /** * @inheritDoc */ - Transaction.prototype.finish = function (endTimestamp) { - var _this = this; - // This transaction is already finished, so we should not flush it again. - if (this.endTimestamp !== undefined) { - return undefined; - } - if (!this.name) { - utils_1.logger.warn('Transaction has no name, falling back to ``.'); - this.name = ''; - } - // just sets the end timestamp - _super.prototype.finish.call(this, endTimestamp); - if (this.sampled !== true) { - // At this point if `sampled !== true` we want to discard the transaction. - utils_1.logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.'); - return undefined; - } - var finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(function (s) { return s !== _this && s.endTimestamp; }) : []; - if (this._trimEnd && finishedSpans.length > 0) { - this.endTimestamp = finishedSpans.reduce(function (prev, current) { - if (prev.endTimestamp && current.endTimestamp) { - return prev.endTimestamp > current.endTimestamp ? prev : current; - } - return prev; - }).endTimestamp; - } - var transaction = { - contexts: { - trace: this.getTraceContext(), - }, - spans: finishedSpans, - start_timestamp: this.startTimestamp, - tags: this.tags, - timestamp: this.endTimestamp, - transaction: this.name, - type: 'transaction', - }; - var hasMeasurements = Object.keys(this._measurements).length > 0; - if (hasMeasurements) { - utils_1.logger.log('[Measurements] Adding measurements to transaction', JSON.stringify(this._measurements, undefined, 2)); - transaction.measurements = this._measurements; - } - return this._hub.captureEvent(transaction); + Hub.prototype.endSession = function () { + var _a, _b, _c, _d, _e; + (_c = (_b = (_a = this.getStackTop()) === null || _a === void 0 ? void 0 : _a.scope) === null || _b === void 0 ? void 0 : _b.getSession()) === null || _c === void 0 ? void 0 : _c.close(); + this._sendSessionUpdate(); + // the session is over; take it off of the scope + (_e = (_d = this.getStackTop()) === null || _d === void 0 ? void 0 : _d.scope) === null || _e === void 0 ? void 0 : _e.setSession(); }; - return Transaction; -}(span_1.Span)); -exports.Transaction = Transaction; -//# sourceMappingURL=transaction.js.map - -/***/ }), - -/***/ 31386: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var hub_1 = __nccwpck_require__(6393); -exports.TRACEPARENT_REGEXP = new RegExp('^[ \\t]*' + // whitespace - '([0-9a-f]{32})?' + // trace_id - '-?([0-9a-f]{16})?' + // span_id - '-?([01])?' + // sampled - '[ \\t]*$'); -/** - * Determines if tracing is currently enabled. - * - * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config. - */ -function hasTracingEnabled(options) { - return 'tracesSampleRate' in options || 'tracesSampler' in options; -} -exports.hasTracingEnabled = hasTracingEnabled; -/** - * Extract transaction context data from a `sentry-trace` header. - * - * @param traceparent Traceparent string - * - * @returns Object containing data from the header, or undefined if traceparent string is malformed - */ -function extractTraceparentData(traceparent) { - var matches = traceparent.match(exports.TRACEPARENT_REGEXP); - if (matches) { - var parentSampled = void 0; - if (matches[3] === '1') { - parentSampled = true; - } - else if (matches[3] === '0') { - parentSampled = false; - } - return { - traceId: matches[1], - parentSampled: parentSampled, - parentSpanId: matches[2], - }; - } - return undefined; -} -exports.extractTraceparentData = extractTraceparentData; -/** Grabs active transaction off scope, if any */ -function getActiveTransaction(hub) { - if (hub === void 0) { hub = hub_1.getCurrentHub(); } - var _a, _b; - return (_b = (_a = hub) === null || _a === void 0 ? void 0 : _a.getScope()) === null || _b === void 0 ? void 0 : _b.getTransaction(); -} -exports.getActiveTransaction = getActiveTransaction; -/** - * Converts from milliseconds to seconds - * @param time time in ms - */ -function msToSec(time) { - return time / 1000; -} -exports.msToSec = msToSec; -/** - * Converts from seconds to milliseconds - * @param time time in seconds - */ -function secToMs(time) { - return time * 1000; -} -exports.secToMs = secToMs; -// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils -var utils_1 = __nccwpck_require__(1620); -exports.stripUrlQueryAndFragment = utils_1.stripUrlQueryAndFragment; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 83789: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var loglevel_1 = __nccwpck_require__(6853); -exports.LogLevel = loglevel_1.LogLevel; -var session_1 = __nccwpck_require__(84954); -exports.SessionStatus = session_1.SessionStatus; -var severity_1 = __nccwpck_require__(94124); -exports.Severity = severity_1.Severity; -var status_1 = __nccwpck_require__(61277); -exports.Status = status_1.Status; -var transaction_1 = __nccwpck_require__(47540); -exports.TransactionSamplingMethod = transaction_1.TransactionSamplingMethod; -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 6853: -/***/ ((__unused_webpack_module, exports) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** Console logging verbosity for the SDK. */ -var LogLevel; -(function (LogLevel) { - /** No logs will be generated. */ - LogLevel[LogLevel["None"] = 0] = "None"; - /** Only SDK internal errors will be logged. */ - LogLevel[LogLevel["Error"] = 1] = "Error"; - /** Information useful for debugging the SDK will be logged. */ - LogLevel[LogLevel["Debug"] = 2] = "Debug"; - /** All SDK actions will be logged. */ - LogLevel[LogLevel["Verbose"] = 3] = "Verbose"; -})(LogLevel = exports.LogLevel || (exports.LogLevel = {})); -//# sourceMappingURL=loglevel.js.map - -/***/ }), - -/***/ 84954: -/***/ ((__unused_webpack_module, exports) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Session Status - */ -var SessionStatus; -(function (SessionStatus) { - /** JSDoc */ - SessionStatus["Ok"] = "ok"; - /** JSDoc */ - SessionStatus["Exited"] = "exited"; - /** JSDoc */ - SessionStatus["Crashed"] = "crashed"; - /** JSDoc */ - SessionStatus["Abnormal"] = "abnormal"; -})(SessionStatus = exports.SessionStatus || (exports.SessionStatus = {})); -//# sourceMappingURL=session.js.map - -/***/ }), - -/***/ 94124: -/***/ ((__unused_webpack_module, exports) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** JSDoc */ -// eslint-disable-next-line import/export -var Severity; -(function (Severity) { - /** JSDoc */ - Severity["Fatal"] = "fatal"; - /** JSDoc */ - Severity["Error"] = "error"; - /** JSDoc */ - Severity["Warning"] = "warning"; - /** JSDoc */ - Severity["Log"] = "log"; - /** JSDoc */ - Severity["Info"] = "info"; - /** JSDoc */ - Severity["Debug"] = "debug"; - /** JSDoc */ - Severity["Critical"] = "critical"; -})(Severity = exports.Severity || (exports.Severity = {})); -// eslint-disable-next-line @typescript-eslint/no-namespace, import/export -(function (Severity) { /** - * Converts a string-based level into a {@link Severity}. - * - * @param level string representation of Severity - * @returns Severity + * @inheritDoc */ - function fromString(level) { - switch (level) { - case 'debug': - return Severity.Debug; - case 'info': - return Severity.Info; - case 'warn': - case 'warning': - return Severity.Warning; - case 'error': - return Severity.Error; - case 'fatal': - return Severity.Fatal; - case 'critical': - return Severity.Critical; - case 'log': - default: - return Severity.Log; - } - } - Severity.fromString = fromString; -})(Severity = exports.Severity || (exports.Severity = {})); -//# sourceMappingURL=severity.js.map - -/***/ }), - -/***/ 61277: -/***/ ((__unused_webpack_module, exports) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** The status of an event. */ -// eslint-disable-next-line import/export -var Status; -(function (Status) { - /** The status could not be determined. */ - Status["Unknown"] = "unknown"; - /** The event was skipped due to configuration or callbacks. */ - Status["Skipped"] = "skipped"; - /** The event was sent to Sentry successfully. */ - Status["Success"] = "success"; - /** The client is currently rate limited and will try again later. */ - Status["RateLimit"] = "rate_limit"; - /** The event could not be processed. */ - Status["Invalid"] = "invalid"; - /** A server-side error ocurred during submission. */ - Status["Failed"] = "failed"; -})(Status = exports.Status || (exports.Status = {})); -// eslint-disable-next-line @typescript-eslint/no-namespace, import/export -(function (Status) { + Hub.prototype.startSession = function (context) { + var _a = this.getStackTop(), scope = _a.scope, client = _a.client; + var _b = (client && client.getOptions()) || {}, release = _b.release, environment = _b.environment; + // Will fetch userAgent if called from browser sdk + var global = utils_1.getGlobalObject(); + var userAgent = (global.navigator || {}).userAgent; + var session = new session_1.Session(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({ release: release, + environment: environment }, (scope && { user: scope.getUser() })), (userAgent && { userAgent: userAgent })), context)); + if (scope) { + // End existing session if there's one + var currentSession = scope.getSession && scope.getSession(); + if (currentSession && currentSession.status === types_1.SessionStatus.Ok) { + currentSession.update({ status: types_1.SessionStatus.Exited }); + } + this.endSession(); + // Afterwards we set the new session on the scope + scope.setSession(session); + } + return session; + }; /** - * Converts a HTTP status code into a {@link Status}. + * Sends the current Session on the scope + */ + Hub.prototype._sendSessionUpdate = function () { + var _a = this.getStackTop(), scope = _a.scope, client = _a.client; + if (!scope) + return; + var session = scope.getSession && scope.getSession(); + if (session) { + if (client && client.captureSession) { + client.captureSession(session); + } + } + }; + /** + * Internal helper function to call a method on the top client if it exists. * - * @param code The HTTP response status code. - * @returns The send status or {@link Status.Unknown}. + * @param method The method to call on the client. + * @param args Arguments to pass to the client function. */ - function fromHttpCode(code) { - if (code >= 200 && code < 300) { - return Status.Success; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Hub.prototype._invokeClient = function (method) { + var _a; + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - if (code === 429) { - return Status.RateLimit; + var _b = this.getStackTop(), scope = _b.scope, client = _b.client; + if (client && client[method]) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + (_a = client)[method].apply(_a, tslib_1.__spread(args, [scope])); } - if (code >= 400 && code < 500) { - return Status.Invalid; + }; + /** + * Calls global extension method and binding current instance to the function call + */ + // @ts-ignore Function lacks ending return statement and return type does not include 'undefined'. ts(2366) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Hub.prototype._callExtensionMethod = function (method) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - if (code >= 500) { - return Status.Failed; + var carrier = getMainCarrier(); + var sentry = carrier.__SENTRY__; + if (sentry && sentry.extensions && typeof sentry.extensions[method] === 'function') { + return sentry.extensions[method].apply(this, args); } - return Status.Unknown; - } - Status.fromHttpCode = fromHttpCode; -})(Status = exports.Status || (exports.Status = {})); -//# sourceMappingURL=status.js.map - -/***/ }), - -/***/ 47540: -/***/ ((__unused_webpack_module, exports) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var TransactionSamplingMethod; -(function (TransactionSamplingMethod) { - TransactionSamplingMethod["Explicit"] = "explicitly_set"; - TransactionSamplingMethod["Sampler"] = "client_sampler"; - TransactionSamplingMethod["Rate"] = "client_rate"; - TransactionSamplingMethod["Inheritance"] = "inheritance"; -})(TransactionSamplingMethod = exports.TransactionSamplingMethod || (exports.TransactionSamplingMethod = {})); -//# sourceMappingURL=transaction.js.map - -/***/ }), - -/***/ 58343: -/***/ ((__unused_webpack_module, exports) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); + utils_1.logger.warn("Extension method " + method + " couldn't be found, doing nothing."); + }; + return Hub; +}()); +exports.Hub = Hub; /** - * Consumes the promise and logs the error when it rejects. - * @param promise A promise to forget. + * Returns the global shim registry. + * + * FIXME: This function is problematic, because despite always returning a valid Carrier, + * it has an optional `__SENTRY__` property, which then in turn requires us to always perform an unnecessary check + * at the call-site. We always access the carrier through this function, so we can guarantee that `__SENTRY__` is there. + **/ +function getMainCarrier() { + var carrier = utils_1.getGlobalObject(); + carrier.__SENTRY__ = carrier.__SENTRY__ || { + extensions: {}, + hub: undefined, + }; + return carrier; +} +exports.getMainCarrier = getMainCarrier; +/** + * Replaces the current main hub with the passed one on the global object + * + * @returns The old replaced hub */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function forget(promise) { - promise.then(null, function (e) { - // TODO: Use a better logging mechanism - // eslint-disable-next-line no-console - console.error(e); - }); +function makeMain(hub) { + var registry = getMainCarrier(); + var oldHub = getHubFromCarrier(registry); + setHubOnCarrier(registry, hub); + return oldHub; } -exports.forget = forget; -//# sourceMappingURL=async.js.map - -/***/ }), - -/***/ 30597: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var is_1 = __nccwpck_require__(92757); +exports.makeMain = makeMain; /** - * Given a child DOM element, returns a query-selector statement describing that - * and its ancestors - * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] - * @returns generated DOM path + * Returns the default hub instance. + * + * If a hub is already registered in the global carrier but this module + * contains a more recent version, it replaces the registered version. + * Otherwise, the currently registered hub will be returned. */ -function htmlTreeAsString(elem) { - // try/catch both: - // - accessing event.target (see getsentry/raven-js#838, #768) - // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly - // - can throw an exception in some circumstances. - try { - var currentElem = elem; - var MAX_TRAVERSE_HEIGHT = 5; - var MAX_OUTPUT_LEN = 80; - var out = []; - var height = 0; - var len = 0; - var separator = ' > '; - var sepLength = separator.length; - var nextStr = void 0; - // eslint-disable-next-line no-plusplus - while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { - nextStr = _htmlElementAsString(currentElem); - // bail out if - // - nextStr is the 'html' element - // - the length of the string that would be created exceeds MAX_OUTPUT_LEN - // (ignore this limit if we are on the first iteration) - if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) { - break; - } - out.push(nextStr); - len += nextStr.length; - currentElem = currentElem.parentNode; - } - return out.reverse().join(separator); +function getCurrentHub() { + // Get main carrier (global for every environment) + var registry = getMainCarrier(); + // If there's no hub, or its an old API, assign a new one + if (!hasHubOnCarrier(registry) || getHubFromCarrier(registry).isOlderThan(exports.API_VERSION)) { + setHubOnCarrier(registry, new Hub()); } - catch (_oO) { - return ''; + // Prefer domains over global if they are there (applicable only to Node environment) + if (utils_1.isNodeEnv()) { + return getHubFromActiveDomain(registry); } + // Return hub that lives on a global object + return getHubFromCarrier(registry); } -exports.htmlTreeAsString = htmlTreeAsString; +exports.getCurrentHub = getCurrentHub; /** - * Returns a simple, query-selector representation of a DOM element - * e.g. [HTMLElement] => input#foo.btn[name=baz] - * @returns generated DOM path + * Returns the active domain, if one exists + * @deprecated No longer used; remove in v7 + * @returns The domain, or undefined if there is no active domain */ -function _htmlElementAsString(el) { - var elem = el; - var out = []; - var className; - var classes; - var key; - var attr; - var i; - if (!elem || !elem.tagName) { - return ''; - } - out.push(elem.tagName.toLowerCase()); - if (elem.id) { - out.push("#" + elem.id); - } - // eslint-disable-next-line prefer-const - className = elem.className; - if (className && is_1.isString(className)) { - classes = className.split(/\s+/); - for (i = 0; i < classes.length; i++) { - out.push("." + classes[i]); +// eslint-disable-next-line deprecation/deprecation +function getActiveDomain() { + utils_1.logger.warn('Function `getActiveDomain` is deprecated and will be removed in a future version.'); + var sentry = getMainCarrier().__SENTRY__; + return sentry && sentry.extensions && sentry.extensions.domain && sentry.extensions.domain.active; +} +exports.getActiveDomain = getActiveDomain; +/** + * Try to read the hub from an active domain, and fallback to the registry if one doesn't exist + * @returns discovered hub + */ +function getHubFromActiveDomain(registry) { + var _a, _b, _c; + try { + var activeDomain = (_c = (_b = (_a = getMainCarrier().__SENTRY__) === null || _a === void 0 ? void 0 : _a.extensions) === null || _b === void 0 ? void 0 : _b.domain) === null || _c === void 0 ? void 0 : _c.active; + // If there's no active domain, just return global hub + if (!activeDomain) { + return getHubFromCarrier(registry); } - } - var allowedAttrs = ['type', 'name', 'title', 'alt']; - for (i = 0; i < allowedAttrs.length; i++) { - key = allowedAttrs[i]; - attr = elem.getAttribute(key); - if (attr) { - out.push("[" + key + "=\"" + attr + "\"]"); + // If there's no hub on current domain, or it's an old API, assign a new one + if (!hasHubOnCarrier(activeDomain) || getHubFromCarrier(activeDomain).isOlderThan(exports.API_VERSION)) { + var registryHubTopStack = getHubFromCarrier(registry).getStackTop(); + setHubOnCarrier(activeDomain, new Hub(registryHubTopStack.client, scope_1.Scope.clone(registryHubTopStack.scope))); } + // Return hub that lives on a domain + return getHubFromCarrier(activeDomain); + } + catch (_Oo) { + // Return hub that lives on a global object + return getHubFromCarrier(registry); } - return out.join(''); } -//# sourceMappingURL=browser.js.map +/** + * This will tell whether a carrier has a hub on it or not + * @param carrier object + */ +function hasHubOnCarrier(carrier) { + return !!(carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub); +} +/** + * This will create a new {@link Hub} and add to the passed object on + * __SENTRY__.hub. + * @param carrier object + * @hidden + */ +function getHubFromCarrier(carrier) { + if (carrier && carrier.__SENTRY__ && carrier.__SENTRY__.hub) + return carrier.__SENTRY__.hub; + carrier.__SENTRY__ = carrier.__SENTRY__ || {}; + carrier.__SENTRY__.hub = new Hub(); + return carrier.__SENTRY__.hub; +} +exports.getHubFromCarrier = getHubFromCarrier; +/** + * This will set passed {@link Hub} on the passed object's __SENTRY__.hub attribute + * @param carrier object + * @param hub Hub + * @returns A boolean indicating success or failure + */ +function setHubOnCarrier(carrier, hub) { + if (!carrier) + return false; + carrier.__SENTRY__ = carrier.__SENTRY__ || {}; + carrier.__SENTRY__.hub = hub; + return true; +} +exports.setHubOnCarrier = setHubOnCarrier; +//# sourceMappingURL=hub.js.map /***/ }), -/***/ 3275: +/***/ 6393: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var scope_1 = __nccwpck_require__(4213); +exports.addGlobalEventProcessor = scope_1.addGlobalEventProcessor; +exports.Scope = scope_1.Scope; +var session_1 = __nccwpck_require__(12474); +exports.Session = session_1.Session; +var sessionflusher_1 = __nccwpck_require__(99695); +exports.SessionFlusher = sessionflusher_1.SessionFlusher; +var hub_1 = __nccwpck_require__(53536); +// eslint-disable-next-line deprecation/deprecation +exports.getActiveDomain = hub_1.getActiveDomain; +exports.getCurrentHub = hub_1.getCurrentHub; +exports.getHubFromCarrier = hub_1.getHubFromCarrier; +exports.getMainCarrier = hub_1.getMainCarrier; +exports.Hub = hub_1.Hub; +exports.makeMain = hub_1.makeMain; +exports.setHubOnCarrier = hub_1.setHubOnCarrier; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 4213: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); var tslib_1 = __nccwpck_require__(4351); -var error_1 = __nccwpck_require__(66238); -/** Regular expression used to parse a Dsn. */ -var DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/; -/** Error message */ -var ERROR_MESSAGE = 'Invalid Dsn'; -/** The Sentry Dsn, identifying a Sentry instance and project. */ -var Dsn = /** @class */ (function () { - /** Creates a new Dsn component */ - function Dsn(from) { - if (typeof from === 'string') { - this._fromString(from); - } - else { - this._fromComponents(from); - } - this._validate(); +var utils_1 = __nccwpck_require__(1620); +/** + * Absolute maximum number of breadcrumbs added to an event. + * The `maxBreadcrumbs` option cannot be higher than this value. + */ +var MAX_BREADCRUMBS = 100; +/** + * Holds additional event information. {@link Scope.applyToEvent} will be + * called by the client before an event will be sent. + */ +var Scope = /** @class */ (function () { + function Scope() { + /** Flag if notifying is happening. */ + this._notifyingListeners = false; + /** Callback for client to receive scope changes. */ + this._scopeListeners = []; + /** Callback list that will be called after {@link applyToEvent}. */ + this._eventProcessors = []; + /** Array of breadcrumbs. */ + this._breadcrumbs = []; + /** User */ + this._user = {}; + /** Tags */ + this._tags = {}; + /** Extra */ + this._extra = {}; + /** Contexts */ + this._contexts = {}; } /** - * Renders the string representation of this Dsn. - * - * By default, this will render the public representation without the password - * component. To get the deprecated private representation, set `withPassword` - * to true. - * - * @param withPassword When set to true, the password will be included. + * Inherit values from the parent scope. + * @param scope to clone. */ - Dsn.prototype.toString = function (withPassword) { - if (withPassword === void 0) { withPassword = false; } - var _a = this, host = _a.host, path = _a.path, pass = _a.pass, port = _a.port, projectId = _a.projectId, protocol = _a.protocol, user = _a.user; - return (protocol + "://" + user + (withPassword && pass ? ":" + pass : '') + - ("@" + host + (port ? ":" + port : '') + "/" + (path ? path + "/" : path) + projectId)); + Scope.clone = function (scope) { + var newScope = new Scope(); + if (scope) { + newScope._breadcrumbs = tslib_1.__spread(scope._breadcrumbs); + newScope._tags = tslib_1.__assign({}, scope._tags); + newScope._extra = tslib_1.__assign({}, scope._extra); + newScope._contexts = tslib_1.__assign({}, scope._contexts); + newScope._user = scope._user; + newScope._level = scope._level; + newScope._span = scope._span; + newScope._session = scope._session; + newScope._transactionName = scope._transactionName; + newScope._fingerprint = scope._fingerprint; + newScope._eventProcessors = tslib_1.__spread(scope._eventProcessors); + newScope._requestSession = scope._requestSession; + } + return newScope; }; - /** Parses a string into this Dsn. */ - Dsn.prototype._fromString = function (str) { - var match = DSN_REGEX.exec(str); - if (!match) { - throw new error_1.SentryError(ERROR_MESSAGE); + /** + * Add internal on change listener. Used for sub SDKs that need to store the scope. + * @hidden + */ + Scope.prototype.addScopeListener = function (callback) { + this._scopeListeners.push(callback); + }; + /** + * @inheritDoc + */ + Scope.prototype.addEventProcessor = function (callback) { + this._eventProcessors.push(callback); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setUser = function (user) { + this._user = user || {}; + if (this._session) { + this._session.update({ user: user }); } - var _a = tslib_1.__read(match.slice(1), 6), protocol = _a[0], user = _a[1], _b = _a[2], pass = _b === void 0 ? '' : _b, host = _a[3], _c = _a[4], port = _c === void 0 ? '' : _c, lastPath = _a[5]; - var path = ''; - var projectId = lastPath; - var split = projectId.split('/'); - if (split.length > 1) { - path = split.slice(0, -1).join('/'); - projectId = split.pop(); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.getUser = function () { + return this._user; + }; + /** + * @inheritDoc + */ + Scope.prototype.getRequestSession = function () { + return this._requestSession; + }; + /** + * @inheritDoc + */ + Scope.prototype.setRequestSession = function (requestSession) { + this._requestSession = requestSession; + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setTags = function (tags) { + this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), tags); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setTag = function (key, value) { + var _a; + this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), (_a = {}, _a[key] = value, _a)); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setExtras = function (extras) { + this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), extras); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setExtra = function (key, extra) { + var _a; + this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), (_a = {}, _a[key] = extra, _a)); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setFingerprint = function (fingerprint) { + this._fingerprint = fingerprint; + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setLevel = function (level) { + this._level = level; + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.setTransactionName = function (name) { + this._transactionName = name; + this._notifyScopeListeners(); + return this; + }; + /** + * Can be removed in major version. + * @deprecated in favor of {@link this.setTransactionName} + */ + Scope.prototype.setTransaction = function (name) { + return this.setTransactionName(name); + }; + /** + * @inheritDoc + */ + Scope.prototype.setContext = function (key, context) { + var _a; + if (context === null) { + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this._contexts[key]; } - if (projectId) { - var projectMatch = projectId.match(/^\d+/); - if (projectMatch) { - projectId = projectMatch[0]; - } + else { + this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), (_a = {}, _a[key] = context, _a)); } - this._fromComponents({ host: host, pass: pass, path: path, projectId: projectId, port: port, protocol: protocol, user: user }); + this._notifyScopeListeners(); + return this; }; - /** Maps Dsn components into this instance. */ - Dsn.prototype._fromComponents = function (components) { - this.protocol = components.protocol; - this.user = components.user; - this.pass = components.pass || ''; - this.host = components.host; - this.port = components.port || ''; - this.path = components.path || ''; - this.projectId = components.projectId; + /** + * @inheritDoc + */ + Scope.prototype.setSpan = function (span) { + this._span = span; + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.getSpan = function () { + return this._span; }; - /** Validates this Dsn and throws on error. */ - Dsn.prototype._validate = function () { - var _this = this; - ['protocol', 'user', 'host', 'projectId'].forEach(function (component) { - if (!_this[component]) { - throw new error_1.SentryError(ERROR_MESSAGE + ": " + component + " missing"); - } - }); - if (!this.projectId.match(/^\d+$/)) { - throw new error_1.SentryError(ERROR_MESSAGE + ": Invalid projectId " + this.projectId); - } - if (this.protocol !== 'http' && this.protocol !== 'https') { - throw new error_1.SentryError(ERROR_MESSAGE + ": Invalid protocol " + this.protocol); + /** + * @inheritDoc + */ + Scope.prototype.getTransaction = function () { + var _a, _b, _c, _d; + // often, this span will be a transaction, but it's not guaranteed to be + var span = this.getSpan(); + // try it the new way first + if ((_a = span) === null || _a === void 0 ? void 0 : _a.transaction) { + return (_b = span) === null || _b === void 0 ? void 0 : _b.transaction; } - if (this.port && isNaN(parseInt(this.port, 10))) { - throw new error_1.SentryError(ERROR_MESSAGE + ": Invalid port " + this.port); + // fallback to the old way (known bug: this only finds transactions with sampled = true) + if ((_d = (_c = span) === null || _c === void 0 ? void 0 : _c.spanRecorder) === null || _d === void 0 ? void 0 : _d.spans[0]) { + return span.spanRecorder.spans[0]; } + // neither way found a transaction + return undefined; }; - return Dsn; -}()); -exports.Dsn = Dsn; -//# sourceMappingURL=dsn.js.map - -/***/ }), - -/***/ 66238: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var polyfill_1 = __nccwpck_require__(1243); -/** An error emitted by Sentry SDKs and related utilities. */ -var SentryError = /** @class */ (function (_super) { - tslib_1.__extends(SentryError, _super); - function SentryError(message) { - var _newTarget = this.constructor; - var _this = _super.call(this, message) || this; - _this.message = message; - _this.name = _newTarget.prototype.constructor.name; - polyfill_1.setPrototypeOf(_this, _newTarget.prototype); - return _this; - } - return SentryError; -}(Error)); -exports.SentryError = SentryError; -//# sourceMappingURL=error.js.map - -/***/ }), - -/***/ 1620: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -tslib_1.__exportStar(__nccwpck_require__(58343), exports); -tslib_1.__exportStar(__nccwpck_require__(30597), exports); -tslib_1.__exportStar(__nccwpck_require__(3275), exports); -tslib_1.__exportStar(__nccwpck_require__(66238), exports); -tslib_1.__exportStar(__nccwpck_require__(65474), exports); -tslib_1.__exportStar(__nccwpck_require__(92757), exports); -tslib_1.__exportStar(__nccwpck_require__(15577), exports); -tslib_1.__exportStar(__nccwpck_require__(49515), exports); -tslib_1.__exportStar(__nccwpck_require__(32154), exports); -tslib_1.__exportStar(__nccwpck_require__(16411), exports); -tslib_1.__exportStar(__nccwpck_require__(69249), exports); -tslib_1.__exportStar(__nccwpck_require__(39188), exports); -tslib_1.__exportStar(__nccwpck_require__(31811), exports); -tslib_1.__exportStar(__nccwpck_require__(5986), exports); -tslib_1.__exportStar(__nccwpck_require__(66538), exports); -tslib_1.__exportStar(__nccwpck_require__(88714), exports); -tslib_1.__exportStar(__nccwpck_require__(87833), exports); -tslib_1.__exportStar(__nccwpck_require__(1735), exports); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 65474: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var is_1 = __nccwpck_require__(92757); -var logger_1 = __nccwpck_require__(15577); -var misc_1 = __nccwpck_require__(32154); -var object_1 = __nccwpck_require__(69249); -var stacktrace_1 = __nccwpck_require__(5986); -var supports_1 = __nccwpck_require__(88714); -var global = misc_1.getGlobalObject(); -/** - * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc. - * - Console API - * - Fetch API - * - XHR API - * - History API - * - DOM API (click/typing) - * - Error API - * - UnhandledRejection API - */ -var handlers = {}; -var instrumented = {}; -/** Instruments given API */ -function instrument(type) { - if (instrumented[type]) { - return; - } - instrumented[type] = true; - switch (type) { - case 'console': - instrumentConsole(); - break; - case 'dom': - instrumentDOM(); - break; - case 'xhr': - instrumentXHR(); - break; - case 'fetch': - instrumentFetch(); - break; - case 'history': - instrumentHistory(); - break; - case 'error': - instrumentError(); - break; - case 'unhandledrejection': - instrumentUnhandledRejection(); - break; - default: - logger_1.logger.warn('unknown instrumentation type:', type); - } -} -/** - * Add handler that will be called when given type of instrumentation triggers. - * Use at your own risk, this might break without changelog notice, only used internally. - * @hidden - */ -function addInstrumentationHandler(handler) { - if (!handler || typeof handler.type !== 'string' || typeof handler.callback !== 'function') { - return; - } - handlers[handler.type] = handlers[handler.type] || []; - handlers[handler.type].push(handler.callback); - instrument(handler.type); -} -exports.addInstrumentationHandler = addInstrumentationHandler; -/** JSDoc */ -function triggerHandlers(type, data) { - var e_1, _a; - if (!type || !handlers[type]) { - return; - } - try { - for (var _b = tslib_1.__values(handlers[type] || []), _c = _b.next(); !_c.done; _c = _b.next()) { - var handler = _c.value; - try { - handler(data); - } - catch (e) { - logger_1.logger.error("Error while triggering instrumentation handler.\nType: " + type + "\nName: " + stacktrace_1.getFunctionName(handler) + "\nError: " + e); - } + /** + * @inheritDoc + */ + Scope.prototype.setSession = function (session) { + if (!session) { + delete this._session; } - } - catch (e_1_1) { e_1 = { error: e_1_1 }; } - finally { - try { - if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + else { + this._session = session; } - finally { if (e_1) throw e_1.error; } - } -} -/** JSDoc */ -function instrumentConsole() { - if (!('console' in global)) { - return; - } - ['debug', 'info', 'warn', 'error', 'log', 'assert'].forEach(function (level) { - if (!(level in global.console)) { - return; + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.getSession = function () { + return this._session; + }; + /** + * @inheritDoc + */ + Scope.prototype.update = function (captureContext) { + if (!captureContext) { + return this; } - object_1.fill(global.console, level, function (originalConsoleLevel) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - triggerHandlers('console', { args: args, level: level }); - // this fails for some browsers. :( - if (originalConsoleLevel) { - Function.prototype.apply.call(originalConsoleLevel, global.console, args); - } - }; - }); - }); -} -/** JSDoc */ -function instrumentFetch() { - if (!supports_1.supportsNativeFetch()) { - return; - } - object_1.fill(global, 'fetch', function (originalFetch) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; + if (typeof captureContext === 'function') { + var updatedScope = captureContext(this); + return updatedScope instanceof Scope ? updatedScope : this; + } + if (captureContext instanceof Scope) { + this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), captureContext._tags); + this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), captureContext._extra); + this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), captureContext._contexts); + if (captureContext._user && Object.keys(captureContext._user).length) { + this._user = captureContext._user; } - var handlerData = { - args: args, - fetchData: { - method: getFetchMethod(args), - url: getFetchUrl(args), - }, - startTimestamp: Date.now(), - }; - triggerHandlers('fetch', tslib_1.__assign({}, handlerData)); - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return originalFetch.apply(global, args).then(function (response) { - triggerHandlers('fetch', tslib_1.__assign(tslib_1.__assign({}, handlerData), { endTimestamp: Date.now(), response: response })); - return response; - }, function (error) { - triggerHandlers('fetch', tslib_1.__assign(tslib_1.__assign({}, handlerData), { endTimestamp: Date.now(), error: error })); - // NOTE: If you are a Sentry user, and you are seeing this stack frame, - // it means the sentry.javascript SDK caught an error invoking your application code. - // This is expected behavior and NOT indicative of a bug with sentry.javascript. - throw error; - }); - }; - }); -} -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ -/** Extract `method` from fetch call arguments */ -function getFetchMethod(fetchArgs) { - if (fetchArgs === void 0) { fetchArgs = []; } - if ('Request' in global && is_1.isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) { - return String(fetchArgs[0].method).toUpperCase(); - } - if (fetchArgs[1] && fetchArgs[1].method) { - return String(fetchArgs[1].method).toUpperCase(); - } - return 'GET'; -} -/** Extract `url` from fetch call arguments */ -function getFetchUrl(fetchArgs) { - if (fetchArgs === void 0) { fetchArgs = []; } - if (typeof fetchArgs[0] === 'string') { - return fetchArgs[0]; - } - if ('Request' in global && is_1.isInstanceOf(fetchArgs[0], Request)) { - return fetchArgs[0].url; - } - return String(fetchArgs[0]); -} -/* eslint-enable @typescript-eslint/no-unsafe-member-access */ -/** JSDoc */ -function instrumentXHR() { - if (!('XMLHttpRequest' in global)) { - return; - } - // Poor man's implementation of ES6 `Map`, tracking and keeping in sync key and value separately. - var requestKeys = []; - var requestValues = []; - var xhrproto = XMLHttpRequest.prototype; - object_1.fill(xhrproto, 'open', function (originalOpen) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; + if (captureContext._level) { + this._level = captureContext._level; } - // eslint-disable-next-line @typescript-eslint/no-this-alias - var xhr = this; - var url = args[1]; - xhr.__sentry_xhr__ = { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - method: is_1.isString(args[0]) ? args[0].toUpperCase() : args[0], - url: args[1], - }; - // if Sentry key appears in URL, don't capture it as a request - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (is_1.isString(url) && xhr.__sentry_xhr__.method === 'POST' && url.match(/sentry_key/)) { - xhr.__sentry_own_request__ = true; + if (captureContext._fingerprint) { + this._fingerprint = captureContext._fingerprint; } - var onreadystatechangeHandler = function () { - if (xhr.readyState === 4) { - try { - // touching statusCode in some platforms throws - // an exception - if (xhr.__sentry_xhr__) { - xhr.__sentry_xhr__.status_code = xhr.status; - } - } - catch (e) { - /* do nothing */ - } - try { - var requestPos = requestKeys.indexOf(xhr); - if (requestPos !== -1) { - // Make sure to pop both key and value to keep it in sync. - requestKeys.splice(requestPos); - var args_1 = requestValues.splice(requestPos)[0]; - if (xhr.__sentry_xhr__ && args_1[0] !== undefined) { - xhr.__sentry_xhr__.body = args_1[0]; - } - } - } - catch (e) { - /* do nothing */ - } - triggerHandlers('xhr', { - args: args, - endTimestamp: Date.now(), - startTimestamp: Date.now(), - xhr: xhr, - }); - } - }; - if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') { - object_1.fill(xhr, 'onreadystatechange', function (original) { - return function () { - var readyStateArgs = []; - for (var _i = 0; _i < arguments.length; _i++) { - readyStateArgs[_i] = arguments[_i]; - } - onreadystatechangeHandler(); - return original.apply(xhr, readyStateArgs); - }; - }); + if (captureContext._requestSession) { + this._requestSession = captureContext._requestSession; } - else { - xhr.addEventListener('readystatechange', onreadystatechangeHandler); + } + else if (utils_1.isPlainObject(captureContext)) { + // eslint-disable-next-line no-param-reassign + captureContext = captureContext; + this._tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), captureContext.tags); + this._extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), captureContext.extra); + this._contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), captureContext.contexts); + if (captureContext.user) { + this._user = captureContext.user; } - return originalOpen.apply(xhr, args); - }; - }); - object_1.fill(xhrproto, 'send', function (originalSend) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; + if (captureContext.level) { + this._level = captureContext.level; } - requestKeys.push(this); - requestValues.push(args); - triggerHandlers('xhr', { - args: args, - startTimestamp: Date.now(), - xhr: this, - }); - return originalSend.apply(this, args); - }; - }); -} -var lastHref; -/** JSDoc */ -function instrumentHistory() { - if (!supports_1.supportsHistory()) { - return; - } - var oldOnPopState = global.onpopstate; - global.onpopstate = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var to = global.location.href; - // keep track of the current URL state, as we always receive only the updated state - var from = lastHref; - lastHref = to; - triggerHandlers('history', { - from: from, - to: to, - }); - if (oldOnPopState) { - return oldOnPopState.apply(this, args); - } - }; - /** @hidden */ - function historyReplacementFunction(originalHistoryFunction) { - return function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; + if (captureContext.fingerprint) { + this._fingerprint = captureContext.fingerprint; } - var url = args.length > 2 ? args[2] : undefined; - if (url) { - // coerce to string (this is what pushState does) - var from = lastHref; - var to = String(url); - // keep track of the current URL state, as we always receive only the updated state - lastHref = to; - triggerHandlers('history', { - from: from, - to: to, - }); + if (captureContext.requestSession) { + this._requestSession = captureContext.requestSession; } - return originalHistoryFunction.apply(this, args); - }; - } - object_1.fill(global.history, 'pushState', historyReplacementFunction); - object_1.fill(global.history, 'replaceState', historyReplacementFunction); -} -/** JSDoc */ -function instrumentDOM() { - if (!('document' in global)) { - return; - } - // Capture breadcrumbs from any click that is unhandled / bubbled up all the way - // to the document. Do this before we instrument addEventListener. - global.document.addEventListener('click', domEventHandler('click', triggerHandlers.bind(null, 'dom')), false); - global.document.addEventListener('keypress', keypressEventHandler(triggerHandlers.bind(null, 'dom')), false); - // After hooking into document bubbled up click and keypresses events, we also hook into user handled click & keypresses. - ['EventTarget', 'Node'].forEach(function (target) { - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - var proto = global[target] && global[target].prototype; - // eslint-disable-next-line no-prototype-builtins - if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) { - return; } - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ - object_1.fill(proto, 'addEventListener', function (original) { - return function (eventName, fn, options) { - if (fn && fn.handleEvent) { - if (eventName === 'click') { - object_1.fill(fn, 'handleEvent', function (innerOriginal) { - return function (event) { - domEventHandler('click', triggerHandlers.bind(null, 'dom'))(event); - return innerOriginal.call(this, event); - }; - }); - } - if (eventName === 'keypress') { - object_1.fill(fn, 'handleEvent', function (innerOriginal) { - return function (event) { - keypressEventHandler(triggerHandlers.bind(null, 'dom'))(event); - return innerOriginal.call(this, event); - }; - }); - } - } - else { - if (eventName === 'click') { - domEventHandler('click', triggerHandlers.bind(null, 'dom'), true)(this); - } - if (eventName === 'keypress') { - keypressEventHandler(triggerHandlers.bind(null, 'dom'))(this); - } - } - return original.call(this, eventName, fn, options); - }; - }); - object_1.fill(proto, 'removeEventListener', function (original) { - return function (eventName, fn, options) { - try { - original.call(this, eventName, fn.__sentry_wrapped__, options); - } - catch (e) { - // ignore, accessing __sentry_wrapped__ will throw in some Selenium environments - } - return original.call(this, eventName, fn, options); - }; - }); - }); -} -var debounceDuration = 1000; -var debounceTimer = 0; -var keypressTimeout; -var lastCapturedEvent; -/** - * Wraps addEventListener to capture UI breadcrumbs - * @param name the event name (e.g. "click") - * @param handler function that will be triggered - * @param debounce decides whether it should wait till another event loop - * @returns wrapped breadcrumb events handler - * @hidden - */ -function domEventHandler(name, handler, debounce) { - if (debounce === void 0) { debounce = false; } - return function (event) { - // reset keypress timeout; e.g. triggering a 'click' after - // a 'keypress' will reset the keypress debounce so that a new - // set of keypresses can be recorded - keypressTimeout = undefined; - // It's possible this handler might trigger multiple times for the same - // event (e.g. event propagation through node ancestors). Ignore if we've - // already captured the event. - if (!event || lastCapturedEvent === event) { - return; + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.clear = function () { + this._breadcrumbs = []; + this._tags = {}; + this._extra = {}; + this._user = {}; + this._contexts = {}; + this._level = undefined; + this._transactionName = undefined; + this._fingerprint = undefined; + this._requestSession = undefined; + this._span = undefined; + this._session = undefined; + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.addBreadcrumb = function (breadcrumb, maxBreadcrumbs) { + var maxCrumbs = typeof maxBreadcrumbs === 'number' ? Math.min(maxBreadcrumbs, MAX_BREADCRUMBS) : MAX_BREADCRUMBS; + // No data has been changed, so don't notify scope listeners + if (maxCrumbs <= 0) { + return this; } - lastCapturedEvent = event; - if (debounceTimer) { - clearTimeout(debounceTimer); + var mergedBreadcrumb = tslib_1.__assign({ timestamp: utils_1.dateTimestampInSeconds() }, breadcrumb); + this._breadcrumbs = tslib_1.__spread(this._breadcrumbs, [mergedBreadcrumb]).slice(-maxCrumbs); + this._notifyScopeListeners(); + return this; + }; + /** + * @inheritDoc + */ + Scope.prototype.clearBreadcrumbs = function () { + this._breadcrumbs = []; + this._notifyScopeListeners(); + return this; + }; + /** + * Applies the current context and fingerprint to the event. + * Note that breadcrumbs will be added by the client. + * Also if the event has already breadcrumbs on it, we do not merge them. + * @param event Event + * @param hint May contain additional information about the original exception. + * @hidden + */ + Scope.prototype.applyToEvent = function (event, hint) { + var _a; + if (this._extra && Object.keys(this._extra).length) { + event.extra = tslib_1.__assign(tslib_1.__assign({}, this._extra), event.extra); } - if (debounce) { - debounceTimer = setTimeout(function () { - handler({ event: event, name: name }); - }); + if (this._tags && Object.keys(this._tags).length) { + event.tags = tslib_1.__assign(tslib_1.__assign({}, this._tags), event.tags); } - else { - handler({ event: event, name: name }); + if (this._user && Object.keys(this._user).length) { + event.user = tslib_1.__assign(tslib_1.__assign({}, this._user), event.user); } - }; -} -/** - * Wraps addEventListener to capture keypress UI events - * @param handler function that will be triggered - * @returns wrapped keypress events handler - * @hidden - */ -function keypressEventHandler(handler) { - // TODO: if somehow user switches keypress target before - // debounce timeout is triggered, we will only capture - // a single breadcrumb from the FIRST target (acceptable?) - return function (event) { - var target; - try { - target = event.target; + if (this._contexts && Object.keys(this._contexts).length) { + event.contexts = tslib_1.__assign(tslib_1.__assign({}, this._contexts), event.contexts); } - catch (e) { - // just accessing event properties can throw an exception in some rare circumstances - // see: https://github.com/getsentry/raven-js/issues/838 - return; + if (this._level) { + event.level = this._level; } - var tagName = target && target.tagName; - // only consider keypress events on actual input elements - // this will disregard keypresses targeting body (e.g. tabbing - // through elements, hotkeys, etc) - if (!tagName || (tagName !== 'INPUT' && tagName !== 'TEXTAREA' && !target.isContentEditable)) { - return; + if (this._transactionName) { + event.transaction = this._transactionName; } - // record first keypress in a series, but ignore subsequent - // keypresses until debounce clears - if (!keypressTimeout) { - domEventHandler('input', handler)(event); + // We want to set the trace context for normal events only if there isn't already + // a trace context on the event. There is a product feature in place where we link + // errors with transaction and it relies on that. + if (this._span) { + event.contexts = tslib_1.__assign({ trace: this._span.getTraceContext() }, event.contexts); + var transactionName = (_a = this._span.transaction) === null || _a === void 0 ? void 0 : _a.name; + if (transactionName) { + event.tags = tslib_1.__assign({ transaction: transactionName }, event.tags); + } } - clearTimeout(keypressTimeout); - keypressTimeout = setTimeout(function () { - keypressTimeout = undefined; - }, debounceDuration); + this._applyFingerprint(event); + event.breadcrumbs = tslib_1.__spread((event.breadcrumbs || []), this._breadcrumbs); + event.breadcrumbs = event.breadcrumbs.length > 0 ? event.breadcrumbs : undefined; + return this._notifyEventProcessors(tslib_1.__spread(getGlobalEventProcessors(), this._eventProcessors), event, hint); }; -} -var _oldOnErrorHandler = null; -/** JSDoc */ -function instrumentError() { - _oldOnErrorHandler = global.onerror; - global.onerror = function (msg, url, line, column, error) { - triggerHandlers('error', { - column: column, - error: error, - line: line, - msg: msg, - url: url, + /** + * This will be called after {@link applyToEvent} is finished. + */ + Scope.prototype._notifyEventProcessors = function (processors, event, hint, index) { + var _this = this; + if (index === void 0) { index = 0; } + return new utils_1.SyncPromise(function (resolve, reject) { + var processor = processors[index]; + if (event === null || typeof processor !== 'function') { + resolve(event); + } + else { + var result = processor(tslib_1.__assign({}, event), hint); + if (utils_1.isThenable(result)) { + void result + .then(function (final) { return _this._notifyEventProcessors(processors, final, hint, index + 1).then(resolve); }) + .then(null, reject); + } + else { + void _this._notifyEventProcessors(processors, result, hint, index + 1) + .then(resolve) + .then(null, reject); + } + } }); - if (_oldOnErrorHandler) { - // eslint-disable-next-line prefer-rest-params - return _oldOnErrorHandler.apply(this, arguments); + }; + /** + * This will be called on every set call. + */ + Scope.prototype._notifyScopeListeners = function () { + var _this = this; + // We need this check for this._notifyingListeners to be able to work on scope during updates + // If this check is not here we'll produce endless recursion when something is done with the scope + // during the callback. + if (!this._notifyingListeners) { + this._notifyingListeners = true; + this._scopeListeners.forEach(function (callback) { + callback(_this); + }); + this._notifyingListeners = false; } - return false; }; -} -var _oldOnUnhandledRejectionHandler = null; -/** JSDoc */ -function instrumentUnhandledRejection() { - _oldOnUnhandledRejectionHandler = global.onunhandledrejection; - global.onunhandledrejection = function (e) { - triggerHandlers('unhandledrejection', e); - if (_oldOnUnhandledRejectionHandler) { - // eslint-disable-next-line prefer-rest-params - return _oldOnUnhandledRejectionHandler.apply(this, arguments); + /** + * Applies fingerprint from the scope to the event if there's one, + * uses message if there's one instead or get rid of empty fingerprint + */ + Scope.prototype._applyFingerprint = function (event) { + // Make sure it's an array first and we actually have something in place + event.fingerprint = event.fingerprint + ? Array.isArray(event.fingerprint) + ? event.fingerprint + : [event.fingerprint] + : []; + // If we have something on the scope, then merge it with event + if (this._fingerprint) { + event.fingerprint = event.fingerprint.concat(this._fingerprint); + } + // If we have no data at all, remove empty array default + if (event.fingerprint && !event.fingerprint.length) { + delete event.fingerprint; } - return true; }; -} -//# sourceMappingURL=instrument.js.map - -/***/ }), - -/***/ 92757: -/***/ ((__unused_webpack_module, exports) => { - -/* eslint-disable @typescript-eslint/no-explicit-any */ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Checks whether given value's type is one of a few Error or Error-like - * {@link isError}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isError(wat) { - switch (Object.prototype.toString.call(wat)) { - case '[object Error]': - return true; - case '[object Exception]': - return true; - case '[object DOMException]': - return true; - default: - return isInstanceOf(wat, Error); - } -} -exports.isError = isError; -/** - * Checks whether given value's type is ErrorEvent - * {@link isErrorEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isErrorEvent(wat) { - return Object.prototype.toString.call(wat) === '[object ErrorEvent]'; -} -exports.isErrorEvent = isErrorEvent; -/** - * Checks whether given value's type is DOMError - * {@link isDOMError}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isDOMError(wat) { - return Object.prototype.toString.call(wat) === '[object DOMError]'; -} -exports.isDOMError = isDOMError; -/** - * Checks whether given value's type is DOMException - * {@link isDOMException}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isDOMException(wat) { - return Object.prototype.toString.call(wat) === '[object DOMException]'; -} -exports.isDOMException = isDOMException; -/** - * Checks whether given value's type is a string - * {@link isString}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isString(wat) { - return Object.prototype.toString.call(wat) === '[object String]'; -} -exports.isString = isString; -/** - * Checks whether given value's is a primitive (undefined, null, number, boolean, string, bigint, symbol) - * {@link isPrimitive}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isPrimitive(wat) { - return wat === null || (typeof wat !== 'object' && typeof wat !== 'function'); -} -exports.isPrimitive = isPrimitive; -/** - * Checks whether given value's type is an object literal - * {@link isPlainObject}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isPlainObject(wat) { - return Object.prototype.toString.call(wat) === '[object Object]'; -} -exports.isPlainObject = isPlainObject; -/** - * Checks whether given value's type is an Event instance - * {@link isEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isEvent(wat) { - return typeof Event !== 'undefined' && isInstanceOf(wat, Event); -} -exports.isEvent = isEvent; -/** - * Checks whether given value's type is an Element instance - * {@link isElement}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isElement(wat) { - return typeof Element !== 'undefined' && isInstanceOf(wat, Element); -} -exports.isElement = isElement; -/** - * Checks whether given value's type is an regexp - * {@link isRegExp}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. - */ -function isRegExp(wat) { - return Object.prototype.toString.call(wat) === '[object RegExp]'; -} -exports.isRegExp = isRegExp; -/** - * Checks whether given value has a then function. - * @param wat A value to be checked. - */ -function isThenable(wat) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return Boolean(wat && wat.then && typeof wat.then === 'function'); -} -exports.isThenable = isThenable; + return Scope; +}()); +exports.Scope = Scope; /** - * Checks whether given value's type is a SyntheticEvent - * {@link isSyntheticEvent}. - * - * @param wat A value to be checked. - * @returns A boolean representing the result. + * Returns the global event processors. */ -function isSyntheticEvent(wat) { - return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; +function getGlobalEventProcessors() { + /* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */ + var global = utils_1.getGlobalObject(); + global.__SENTRY__ = global.__SENTRY__ || {}; + global.__SENTRY__.globalEventProcessors = global.__SENTRY__.globalEventProcessors || []; + return global.__SENTRY__.globalEventProcessors; + /* eslint-enable @typescript-eslint/no-explicit-any, @typescript-eslint/no-unsafe-member-access */ } -exports.isSyntheticEvent = isSyntheticEvent; /** - * Checks whether given value's type is an instance of provided constructor. - * {@link isInstanceOf}. - * - * @param wat A value to be checked. - * @param base A constructor to be used in a check. - * @returns A boolean representing the result. + * Add a EventProcessor to be kept globally. + * @param callback EventProcessor to add */ -function isInstanceOf(wat, base) { - try { - return wat instanceof base; - } - catch (_e) { - return false; - } +function addGlobalEventProcessor(callback) { + getGlobalEventProcessors().push(callback); } -exports.isInstanceOf = isInstanceOf; -//# sourceMappingURL=is.js.map +exports.addGlobalEventProcessor = addGlobalEventProcessor; +//# sourceMappingURL=scope.js.map /***/ }), -/***/ 15577: +/***/ 12474: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -/* eslint-disable @typescript-eslint/no-explicit-any */ -var misc_1 = __nccwpck_require__(32154); -// TODO: Implement different loggers for different environments -var global = misc_1.getGlobalObject(); -/** Prefix for logging strings */ -var PREFIX = 'Sentry Logger '; -/** JSDoc */ -var Logger = /** @class */ (function () { - /** JSDoc */ - function Logger() { - this._enabled = false; +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +/** + * @inheritdoc + */ +var Session = /** @class */ (function () { + function Session(context) { + this.errors = 0; + this.sid = utils_1.uuid4(); + this.duration = 0; + this.status = types_1.SessionStatus.Ok; + this.init = true; + this.ignoreDuration = false; + // Both timestamp and started are in seconds since the UNIX epoch. + var startingTime = utils_1.timestampInSeconds(); + this.timestamp = startingTime; + this.started = startingTime; + if (context) { + this.update(context); + } } /** JSDoc */ - Logger.prototype.disable = function () { - this._enabled = false; - }; - /** JSDoc */ - Logger.prototype.enable = function () { - this._enabled = true; - }; - /** JSDoc */ - Logger.prototype.log = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; + // eslint-disable-next-line complexity + Session.prototype.update = function (context) { + if (context === void 0) { context = {}; } + if (context.user) { + if (!this.ipAddress && context.user.ip_address) { + this.ipAddress = context.user.ip_address; + } + if (!this.did && !context.did) { + this.did = context.user.id || context.user.email || context.user.username; + } } - if (!this._enabled) { - return; + this.timestamp = context.timestamp || utils_1.timestampInSeconds(); + if (context.ignoreDuration) { + this.ignoreDuration = context.ignoreDuration; } - misc_1.consoleSandbox(function () { - global.console.log(PREFIX + "[Log]: " + args.join(' ')); - }); - }; - /** JSDoc */ - Logger.prototype.warn = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; + if (context.sid) { + // Good enough uuid validation. — Kamil + this.sid = context.sid.length === 32 ? context.sid : utils_1.uuid4(); } - if (!this._enabled) { - return; + if (context.init !== undefined) { + this.init = context.init; + } + if (!this.did && context.did) { + this.did = "" + context.did; + } + if (typeof context.started === 'number') { + this.started = context.started; + } + if (this.ignoreDuration) { + this.duration = undefined; + } + else if (typeof context.duration === 'number') { + this.duration = context.duration; + } + else { + var duration = this.timestamp - this.started; + this.duration = duration >= 0 ? duration : 0; + } + if (context.release) { + this.release = context.release; + } + if (context.environment) { + this.environment = context.environment; + } + if (!this.ipAddress && context.ipAddress) { + this.ipAddress = context.ipAddress; + } + if (!this.userAgent && context.userAgent) { + this.userAgent = context.userAgent; + } + if (typeof context.errors === 'number') { + this.errors = context.errors; + } + if (context.status) { + this.status = context.status; } - misc_1.consoleSandbox(function () { - global.console.warn(PREFIX + "[Warn]: " + args.join(' ')); - }); }; /** JSDoc */ - Logger.prototype.error = function () { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; + Session.prototype.close = function (status) { + if (status) { + this.update({ status: status }); } - if (!this._enabled) { - return; + else if (this.status === types_1.SessionStatus.Ok) { + this.update({ status: types_1.SessionStatus.Exited }); } - misc_1.consoleSandbox(function () { - global.console.error(PREFIX + "[Error]: " + args.join(' ')); + else { + this.update(); + } + }; + /** JSDoc */ + Session.prototype.toJSON = function () { + return utils_1.dropUndefinedKeys({ + sid: "" + this.sid, + init: this.init, + // Make sure that sec is converted to ms for date constructor + started: new Date(this.started * 1000).toISOString(), + timestamp: new Date(this.timestamp * 1000).toISOString(), + status: this.status, + errors: this.errors, + did: typeof this.did === 'number' || typeof this.did === 'string' ? "" + this.did : undefined, + duration: this.duration, + attrs: utils_1.dropUndefinedKeys({ + release: this.release, + environment: this.environment, + ip_address: this.ipAddress, + user_agent: this.userAgent, + }), }); }; - return Logger; + return Session; }()); -// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used -global.__SENTRY__ = global.__SENTRY__ || {}; -var logger = global.__SENTRY__.logger || (global.__SENTRY__.logger = new Logger()); -exports.logger = logger; -//# sourceMappingURL=logger.js.map +exports.Session = Session; +//# sourceMappingURL=session.js.map /***/ }), -/***/ 49515: -/***/ ((__unused_webpack_module, exports) => { +/***/ 99695: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -/* eslint-disable @typescript-eslint/no-unsafe-member-access */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var hub_1 = __nccwpck_require__(53536); /** - * Memo class used for decycle json objects. Uses WeakSet if available otherwise array. + * @inheritdoc */ -var Memo = /** @class */ (function () { - function Memo() { - this._hasWeakSet = typeof WeakSet === 'function'; - this._inner = this._hasWeakSet ? new WeakSet() : []; - } - /** - * Sets obj to remember. - * @param obj Object to remember - */ - Memo.prototype.memoize = function (obj) { - if (this._hasWeakSet) { - if (this._inner.has(obj)) { - return true; - } - this._inner.add(obj); - return false; +var SessionFlusher = /** @class */ (function () { + function SessionFlusher(transport, attrs) { + var _this = this; + this.flushTimeout = 60; + this._pendingAggregates = {}; + this._isEnabled = true; + this._transport = transport; + // Call to setInterval, so that flush is called every 60 seconds + this._intervalId = setInterval(function () { return _this.flush(); }, this.flushTimeout * 1000); + this._sessionAttrs = attrs; + } + /** Sends session aggregates to Transport */ + SessionFlusher.prototype.sendSessionAggregates = function (sessionAggregates) { + if (!this._transport.sendSession) { + utils_1.logger.warn("Dropping session because custom transport doesn't implement sendSession"); + return; } - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (var i = 0; i < this._inner.length; i++) { - var value = this._inner[i]; - if (value === obj) { - return true; - } + void this._transport.sendSession(sessionAggregates).then(null, function (reason) { + utils_1.logger.error("Error while sending session: " + reason); + }); + }; + /** Checks if `pendingAggregates` has entries, and if it does flushes them by calling `sendSessions` */ + SessionFlusher.prototype.flush = function () { + var sessionAggregates = this.getSessionAggregates(); + if (sessionAggregates.aggregates.length === 0) { + return; } - this._inner.push(obj); - return false; + this._pendingAggregates = {}; + this.sendSessionAggregates(sessionAggregates); + }; + /** Massages the entries in `pendingAggregates` and returns aggregated sessions */ + SessionFlusher.prototype.getSessionAggregates = function () { + var _this = this; + var aggregates = Object.keys(this._pendingAggregates).map(function (key) { + return _this._pendingAggregates[parseInt(key)]; + }); + var sessionAggregates = { + attrs: this._sessionAttrs, + aggregates: aggregates, + }; + return utils_1.dropUndefinedKeys(sessionAggregates); + }; + /** JSDoc */ + SessionFlusher.prototype.close = function () { + clearInterval(this._intervalId); + this._isEnabled = false; + this.flush(); }; /** - * Removes object from internal storage. - * @param obj Object to forget + * Wrapper function for _incrementSessionStatusCount that checks if the instance of SessionFlusher is enabled then + * fetches the session status of the request from `Scope.getRequestSession().status` on the scope and passes them to + * `_incrementSessionStatusCount` along with the start date */ - Memo.prototype.unmemoize = function (obj) { - if (this._hasWeakSet) { - this._inner.delete(obj); + SessionFlusher.prototype.incrementSessionStatusCount = function () { + var _a, _b; + if (!this._isEnabled) { + return; } - else { - for (var i = 0; i < this._inner.length; i++) { - if (this._inner[i] === obj) { - this._inner.splice(i, 1); - break; - } - } + var scope = hub_1.getCurrentHub().getScope(); + var requestSession = (_a = scope) === null || _a === void 0 ? void 0 : _a.getRequestSession(); + if (requestSession && requestSession.status) { + this._incrementSessionStatusCount(requestSession.status, new Date()); + // This is not entirely necessarily but is added as a safe guard to indicate the bounds of a request and so in + // case captureRequestSession is called more than once to prevent double count + (_b = scope) === null || _b === void 0 ? void 0 : _b.setRequestSession(undefined); + /* eslint-enable @typescript-eslint/no-unsafe-member-access */ } }; - return Memo; + /** + * Increments status bucket in pendingAggregates buffer (internal state) corresponding to status of + * the session received + */ + SessionFlusher.prototype._incrementSessionStatusCount = function (status, date) { + // Truncate minutes and seconds on Session Started attribute to have one minute bucket keys + var sessionStartedTrunc = new Date(date).setSeconds(0, 0); + this._pendingAggregates[sessionStartedTrunc] = this._pendingAggregates[sessionStartedTrunc] || {}; + // corresponds to aggregated sessions in one specific minute bucket + // for example, {"started":"2021-03-16T08:00:00.000Z","exited":4, "errored": 1} + var aggregationCounts = this._pendingAggregates[sessionStartedTrunc]; + if (!aggregationCounts.started) { + aggregationCounts.started = new Date(sessionStartedTrunc).toISOString(); + } + switch (status) { + case types_1.RequestSessionStatus.Errored: + aggregationCounts.errored = (aggregationCounts.errored || 0) + 1; + return aggregationCounts.errored; + case types_1.RequestSessionStatus.Ok: + aggregationCounts.exited = (aggregationCounts.exited || 0) + 1; + return aggregationCounts.exited; + case types_1.RequestSessionStatus.Crashed: + aggregationCounts.crashed = (aggregationCounts.crashed || 0) + 1; + return aggregationCounts.crashed; + } + }; + return SessionFlusher; }()); -exports.Memo = Memo; -//# sourceMappingURL=memo.js.map +exports.SessionFlusher = SessionFlusher; +//# sourceMappingURL=sessionflusher.js.map /***/ }), -/***/ 32154: +/***/ 88455: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var node_1 = __nccwpck_require__(16411); -var string_1 = __nccwpck_require__(66538); -var fallbackGlobalObject = {}; +var tslib_1 = __nccwpck_require__(4351); +var hub_1 = __nccwpck_require__(6393); /** - * Safely get global scope object - * - * @returns Global scope object + * This calls a function on the current hub. + * @param method function to call on hub. + * @param args to pass to function. */ -function getGlobalObject() { - return (node_1.isNodeEnv() - ? global - : typeof window !== 'undefined' - ? window - : typeof self !== 'undefined' - ? self - : fallbackGlobalObject); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function callOnHub(method) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; + } + var hub = hub_1.getCurrentHub(); + if (hub && hub[method]) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return hub[method].apply(hub, tslib_1.__spread(args)); + } + throw new Error("No hub defined or " + method + " was not found on the hub, please open a bug report."); } -exports.getGlobalObject = getGlobalObject; /** - * UUID4 generator + * Captures an exception event and sends it to Sentry. * - * @returns string Generated UUID4. + * @param exception An exception-like object. + * @returns The generated eventId. */ -function uuid4() { - var global = getGlobalObject(); - var crypto = global.crypto || global.msCrypto; - if (!(crypto === void 0) && crypto.getRandomValues) { - // Use window.crypto API if available - var arr = new Uint16Array(8); - crypto.getRandomValues(arr); - // set 4 in byte 7 - // eslint-disable-next-line no-bitwise - arr[3] = (arr[3] & 0xfff) | 0x4000; - // set 2 most significant bits of byte 9 to '10' - // eslint-disable-next-line no-bitwise - arr[4] = (arr[4] & 0x3fff) | 0x8000; - var pad = function (num) { - var v = num.toString(16); - while (v.length < 4) { - v = "0" + v; - } - return v; - }; - return (pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7])); +// eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types +function captureException(exception, captureContext) { + var syntheticException; + try { + throw new Error('Sentry syntheticException'); } - // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 - return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) { - // eslint-disable-next-line no-bitwise - var r = (Math.random() * 16) | 0; - // eslint-disable-next-line no-bitwise - var v = c === 'x' ? r : (r & 0x3) | 0x8; - return v.toString(16); + catch (exception) { + syntheticException = exception; + } + return callOnHub('captureException', exception, { + captureContext: captureContext, + originalException: exception, + syntheticException: syntheticException, }); } -exports.uuid4 = uuid4; +exports.captureException = captureException; /** - * Parses string form of URL into an object - * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B - * // intentionally using regex and not href parsing trick because React Native and other - * // environments where DOM might not be available - * @returns parsed URL object + * Captures a message event and sends it to Sentry. + * + * @param message The message to send to Sentry. + * @param level Define the level of the message. + * @returns The generated eventId. */ -function parseUrl(url) { - if (!url) { - return {}; +function captureMessage(message, captureContext) { + var syntheticException; + try { + throw new Error(message); } - var match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); - if (!match) { - return {}; + catch (exception) { + syntheticException = exception; } - // coerce to undefined values to empty string so we don't get 'undefined' - var query = match[6] || ''; - var fragment = match[8] || ''; - return { - host: match[4], - path: match[5], - protocol: match[2], - relative: match[5] + query + fragment, - }; + // This is necessary to provide explicit scopes upgrade, without changing the original + // arity of the `captureMessage(message, level)` method. + var level = typeof captureContext === 'string' ? captureContext : undefined; + var context = typeof captureContext !== 'string' ? { captureContext: captureContext } : undefined; + return callOnHub('captureMessage', message, level, tslib_1.__assign({ originalException: message, syntheticException: syntheticException }, context)); } -exports.parseUrl = parseUrl; +exports.captureMessage = captureMessage; /** - * Extracts either message or type+value from an event that can be used for user-facing logs - * @returns event's description + * Captures a manually created event and sends it to Sentry. + * + * @param event The event to send to Sentry. + * @returns The generated eventId. */ -function getEventDescription(event) { - if (event.message) { - return event.message; - } - if (event.exception && event.exception.values && event.exception.values[0]) { - var exception = event.exception.values[0]; - if (exception.type && exception.value) { - return exception.type + ": " + exception.value; - } - return exception.type || exception.value || event.event_id || ''; - } - return event.event_id || ''; +function captureEvent(event) { + return callOnHub('captureEvent', event); } -exports.getEventDescription = getEventDescription; -/** JSDoc */ -function consoleSandbox(callback) { - var global = getGlobalObject(); - var levels = ['debug', 'info', 'warn', 'error', 'log', 'assert']; - if (!('console' in global)) { - return callback(); - } - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - var originalConsole = global.console; - var wrappedLevels = {}; - // Restore all wrapped console methods - levels.forEach(function (level) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - if (level in global.console && originalConsole[level].__sentry_original__) { - wrappedLevels[level] = originalConsole[level]; - originalConsole[level] = originalConsole[level].__sentry_original__; - } - }); - // Perform callback manipulations - var result = callback(); - // Revert restoration to wrapped state - Object.keys(wrappedLevels).forEach(function (level) { - originalConsole[level] = wrappedLevels[level]; - }); - return result; +exports.captureEvent = captureEvent; +/** + * Callback to set context information onto the scope. + * @param callback Callback function that receives Scope. + */ +function configureScope(callback) { + callOnHub('configureScope', callback); } -exports.consoleSandbox = consoleSandbox; +exports.configureScope = configureScope; /** - * Adds exception values, type and value to an synthetic Exception. - * @param event The event to modify. - * @param value Value of the exception. - * @param type Type of the exception. - * @hidden + * Records a new breadcrumb which will be attached to future events. + * + * Breadcrumbs will be added to subsequent events to provide more context on + * user's actions prior to an error or crash. + * + * @param breadcrumb The breadcrumb to record. */ -function addExceptionTypeValue(event, value, type) { - event.exception = event.exception || {}; - event.exception.values = event.exception.values || []; - event.exception.values[0] = event.exception.values[0] || {}; - event.exception.values[0].value = event.exception.values[0].value || value || ''; - event.exception.values[0].type = event.exception.values[0].type || type || 'Error'; +function addBreadcrumb(breadcrumb) { + callOnHub('addBreadcrumb', breadcrumb); } -exports.addExceptionTypeValue = addExceptionTypeValue; +exports.addBreadcrumb = addBreadcrumb; /** - * Adds exception mechanism to a given event. - * @param event The event to modify. - * @param mechanism Mechanism of the mechanism. - * @hidden + * Sets context data with the given name. + * @param name of the context + * @param context Any kind of data. This data will be normalized. */ -function addExceptionMechanism(event, mechanism) { - if (mechanism === void 0) { mechanism = {}; } - // TODO: Use real type with `keyof Mechanism` thingy and maybe make it better? - try { - // @ts-ignore Type 'Mechanism | {}' is not assignable to type 'Mechanism | undefined' - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - event.exception.values[0].mechanism = event.exception.values[0].mechanism || {}; - Object.keys(mechanism).forEach(function (key) { - // @ts-ignore Mechanism has no index signature - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - event.exception.values[0].mechanism[key] = mechanism[key]; - }); - } - catch (_oO) { - // no-empty - } +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setContext(name, context) { + callOnHub('setContext', name, context); } -exports.addExceptionMechanism = addExceptionMechanism; +exports.setContext = setContext; /** - * A safe form of location.href + * Set an object that will be merged sent as extra data with the event. + * @param extras Extras object to merge into current context. */ -function getLocationHref() { - try { - return document.location.href; - } - catch (oO) { - return ''; - } +function setExtras(extras) { + callOnHub('setExtras', extras); } -exports.getLocationHref = getLocationHref; -// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string -var SEMVER_REGEXP = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; +exports.setExtras = setExtras; /** - * Parses input into a SemVer interface - * @param input string representation of a semver version + * Set an object that will be merged sent as tags data with the event. + * @param tags Tags context object to merge into current context. */ -function parseSemver(input) { - var match = input.match(SEMVER_REGEXP) || []; - var major = parseInt(match[1], 10); - var minor = parseInt(match[2], 10); - var patch = parseInt(match[3], 10); - return { - buildmetadata: match[5], - major: isNaN(major) ? undefined : major, - minor: isNaN(minor) ? undefined : minor, - patch: isNaN(patch) ? undefined : patch, - prerelease: match[4], - }; +function setTags(tags) { + callOnHub('setTags', tags); } -exports.parseSemver = parseSemver; -var defaultRetryAfter = 60 * 1000; // 60 seconds +exports.setTags = setTags; /** - * Extracts Retry-After value from the request header or returns default value - * @param now current unix timestamp - * @param header string representation of 'Retry-After' header + * Set key:value that will be sent as extra data with the event. + * @param key String of extra + * @param extra Any kind of data. This data will be normalized. */ -function parseRetryAfterHeader(now, header) { - if (!header) { - return defaultRetryAfter; - } - var headerDelay = parseInt("" + header, 10); - if (!isNaN(headerDelay)) { - return headerDelay * 1000; - } - var headerDate = Date.parse("" + header); - if (!isNaN(headerDate)) { - return headerDate - now; +function setExtra(key, extra) { + callOnHub('setExtra', key, extra); +} +exports.setExtra = setExtra; +/** + * Set key:value that will be sent as tags data with the event. + * + * Can also be used to unset a tag, by passing `undefined`. + * + * @param key String key of tag + * @param value Value of tag + */ +function setTag(key, value) { + callOnHub('setTag', key, value); +} +exports.setTag = setTag; +/** + * Updates user context information for future events. + * + * @param user User context object to be set in the current context. Pass `null` to unset the user. + */ +function setUser(user) { + callOnHub('setUser', user); +} +exports.setUser = setUser; +/** + * Creates a new scope with and executes the given operation within. + * The scope is automatically removed once the operation + * finishes or throws. + * + * This is essentially a convenience function for: + * + * pushScope(); + * callback(); + * popScope(); + * + * @param callback that will be enclosed into push/popScope. + */ +function withScope(callback) { + callOnHub('withScope', callback); +} +exports.withScope = withScope; +/** + * Calls a function on the latest client. Use this with caution, it's meant as + * in "internal" helper so we don't need to expose every possible function in + * the shim. It is not guaranteed that the client actually implements the + * function. + * + * @param method The method to call on the client/client. + * @param args Arguments to pass to the client/fontend. + * @hidden + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function _callOnClient(method) { + var args = []; + for (var _i = 1; _i < arguments.length; _i++) { + args[_i - 1] = arguments[_i]; } - return defaultRetryAfter; + callOnHub.apply(void 0, tslib_1.__spread(['_invokeClient', method], args)); } -exports.parseRetryAfterHeader = parseRetryAfterHeader; +exports._callOnClient = _callOnClient; /** - * This function adds context (pre/post/line) lines to the provided frame + * Starts a new `Transaction` and returns it. This is the entry point to manual tracing instrumentation. * - * @param lines string[] containing all lines - * @param frame StackFrame that will be mutated - * @param linesOfContext number of context lines we want to add pre/post + * A tree structure can be built by adding child spans to the transaction, and child spans to other spans. To start a + * new child span within the transaction or any span, call the respective `.startChild()` method. + * + * Every child span must be finished before the transaction is finished, otherwise the unfinished spans are discarded. + * + * The transaction must be finished with a call to its `.finish()` method, at which point the transaction with all its + * finished child spans will be sent to Sentry. + * + * @param context Properties of the new `Transaction`. + * @param customSamplingContext Information given to the transaction sampling function (along with context-dependent + * default values). See {@link Options.tracesSampler}. + * + * @returns The transaction which was just started */ -function addContextToFrame(lines, frame, linesOfContext) { - if (linesOfContext === void 0) { linesOfContext = 5; } - var lineno = frame.lineno || 0; - var maxLines = lines.length; - var sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0); - frame.pre_context = lines - .slice(Math.max(0, sourceLine - linesOfContext), sourceLine) - .map(function (line) { return string_1.snipLine(line, 0); }); - frame.context_line = string_1.snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0); - frame.post_context = lines - .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext) - .map(function (line) { return string_1.snipLine(line, 0); }); +function startTransaction(context, customSamplingContext) { + return callOnHub('startTransaction', tslib_1.__assign({}, context), customSamplingContext); } -exports.addContextToFrame = addContextToFrame; +exports.startTransaction = startTransaction; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 40508: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var parsers_1 = __nccwpck_require__(19090); +var transports_1 = __nccwpck_require__(21437); /** - * Strip the query string and fragment off of a given URL or path (if present) + * The Sentry Node SDK Backend. + * @hidden + */ +var NodeBackend = /** @class */ (function (_super) { + tslib_1.__extends(NodeBackend, _super); + function NodeBackend() { + return _super !== null && _super.apply(this, arguments) || this; + } + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + NodeBackend.prototype.eventFromException = function (exception, hint) { + var _this = this; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var ex = exception; + var providedMechanism = hint && hint.data && hint.data.mechanism; + var mechanism = providedMechanism || { + handled: true, + type: 'generic', + }; + if (!utils_1.isError(exception)) { + if (utils_1.isPlainObject(exception)) { + // This will allow us to group events based on top-level keys + // which is much better than creating new group when any key/value change + var message = "Non-Error exception captured with keys: " + utils_1.extractExceptionKeysForMessage(exception); + core_1.getCurrentHub().configureScope(function (scope) { + scope.setExtra('__serialized__', utils_1.normalizeToSize(exception)); + }); + ex = (hint && hint.syntheticException) || new Error(message); + ex.message = message; + } + else { + // This handles when someone does: `throw "something awesome";` + // We use synthesized Error here so we can extract a (rough) stack trace. + ex = (hint && hint.syntheticException) || new Error(exception); + ex.message = exception; + } + mechanism.synthetic = true; + } + return new utils_1.SyncPromise(function (resolve, reject) { + return parsers_1.parseError(ex, _this._options) + .then(function (event) { + utils_1.addExceptionTypeValue(event, undefined, undefined); + utils_1.addExceptionMechanism(event, mechanism); + resolve(tslib_1.__assign(tslib_1.__assign({}, event), { event_id: hint && hint.event_id })); + }) + .then(null, reject); + }); + }; + /** + * @inheritDoc + */ + NodeBackend.prototype.eventFromMessage = function (message, level, hint) { + var _this = this; + if (level === void 0) { level = types_1.Severity.Info; } + var event = { + event_id: hint && hint.event_id, + level: level, + message: message, + }; + return new utils_1.SyncPromise(function (resolve) { + if (_this._options.attachStacktrace && hint && hint.syntheticException) { + var stack = hint.syntheticException ? parsers_1.extractStackFromError(hint.syntheticException) : []; + void parsers_1.parseStack(stack, _this._options) + .then(function (frames) { + event.stacktrace = { + frames: parsers_1.prepareFramesForEvent(frames), + }; + resolve(event); + }) + .then(null, function () { + resolve(event); + }); + } + else { + resolve(event); + } + }); + }; + /** + * @inheritDoc + */ + NodeBackend.prototype._setupTransport = function () { + if (!this._options.dsn) { + // We return the noop transport here in case there is no Dsn. + return _super.prototype._setupTransport.call(this); + } + var dsn = new utils_1.Dsn(this._options.dsn); + var transportOptions = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, this._options.transportOptions), (this._options.httpProxy && { httpProxy: this._options.httpProxy })), (this._options.httpsProxy && { httpsProxy: this._options.httpsProxy })), (this._options.caCerts && { caCerts: this._options.caCerts })), { dsn: this._options.dsn, tunnel: this._options.tunnel, _metadata: this._options._metadata }); + if (this._options.transport) { + return new this._options.transport(transportOptions); + } + if (dsn.protocol === 'http') { + return new transports_1.HTTPTransport(transportOptions); + } + return new transports_1.HTTPSTransport(transportOptions); + }; + return NodeBackend; +}(core_1.BaseBackend)); +exports.NodeBackend = NodeBackend; +//# sourceMappingURL=backend.js.map + +/***/ }), + +/***/ 86147: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var hub_1 = __nccwpck_require__(6393); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var backend_1 = __nccwpck_require__(40508); +/** + * The Sentry Node SDK Client. * - * @param urlPath Full URL or path, including possible query string and/or fragment - * @returns URL or path without query string or fragment + * @see NodeOptions for documentation on configuration options. + * @see SentryClient for usage documentation. */ -function stripUrlQueryAndFragment(urlPath) { - // eslint-disable-next-line no-useless-escape - return urlPath.split(/[\?#]/, 1)[0]; -} -exports.stripUrlQueryAndFragment = stripUrlQueryAndFragment; -//# sourceMappingURL=misc.js.map +var NodeClient = /** @class */ (function (_super) { + tslib_1.__extends(NodeClient, _super); + /** + * Creates a new Node SDK instance. + * @param options Configuration options for this SDK. + */ + function NodeClient(options) { + var _this = this; + options._metadata = options._metadata || {}; + options._metadata.sdk = options._metadata.sdk || { + name: 'sentry.javascript.node', + packages: [ + { + name: 'npm:@sentry/node', + version: core_1.SDK_VERSION, + }, + ], + version: core_1.SDK_VERSION, + }; + _this = _super.call(this, backend_1.NodeBackend, options) || this; + return _this; + } + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + NodeClient.prototype.captureException = function (exception, hint, scope) { + // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only + // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload + // sent to the Server only when the `requestHandler` middleware is used + if (this._options.autoSessionTracking && this._sessionFlusher && scope) { + var requestSession = scope.getRequestSession(); + // Necessary checks to ensure this is code block is executed only within a request + // Should override the status only if `requestSession.status` is `Ok`, which is its initial stage + if (requestSession && requestSession.status === types_1.RequestSessionStatus.Ok) { + requestSession.status = types_1.RequestSessionStatus.Errored; + } + } + return _super.prototype.captureException.call(this, exception, hint, scope); + }; + /** + * @inheritDoc + */ + NodeClient.prototype.captureEvent = function (event, hint, scope) { + // Check if the flag `autoSessionTracking` is enabled, and if `_sessionFlusher` exists because it is initialised only + // when the `requestHandler` middleware is used, and hence the expectation is to have SessionAggregates payload + // sent to the Server only when the `requestHandler` middleware is used + if (this._options.autoSessionTracking && this._sessionFlusher && scope) { + var eventType = event.type || 'exception'; + var isException = eventType === 'exception' && event.exception && event.exception.values && event.exception.values.length > 0; + // If the event is of type Exception, then a request session should be captured + if (isException) { + var requestSession = scope.getRequestSession(); + // Ensure that this is happening within the bounds of a request, and make sure not to override + // Session Status if Errored / Crashed + if (requestSession && requestSession.status === types_1.RequestSessionStatus.Ok) { + requestSession.status = types_1.RequestSessionStatus.Errored; + } + } + } + return _super.prototype.captureEvent.call(this, event, hint, scope); + }; + /** + * + * @inheritdoc + */ + NodeClient.prototype.close = function (timeout) { + var _a; + (_a = this._sessionFlusher) === null || _a === void 0 ? void 0 : _a.close(); + return _super.prototype.close.call(this, timeout); + }; + /** Method that initialises an instance of SessionFlusher on Client */ + NodeClient.prototype.initSessionFlusher = function () { + var _a = this._options, release = _a.release, environment = _a.environment; + if (!release) { + utils_1.logger.warn('Cannot initialise an instance of SessionFlusher if no release is provided!'); + } + else { + this._sessionFlusher = new hub_1.SessionFlusher(this._backend.getTransport(), { + release: release, + environment: environment, + }); + } + }; + /** + * @inheritDoc + */ + NodeClient.prototype._prepareEvent = function (event, scope, hint) { + event.platform = event.platform || 'node'; + if (this.getOptions().serverName) { + event.server_name = this.getOptions().serverName; + } + return _super.prototype._prepareEvent.call(this, event, scope, hint); + }; + /** + * Method responsible for capturing/ending a request session by calling `incrementSessionStatusCount` to increment + * appropriate session aggregates bucket + */ + NodeClient.prototype._captureRequestSession = function () { + if (!this._sessionFlusher) { + utils_1.logger.warn('Discarded request mode session because autoSessionTracking option was disabled'); + } + else { + this._sessionFlusher.incrementSessionStatusCount(); + } + }; + return NodeClient; +}(core_1.BaseClient)); +exports.NodeClient = NodeClient; +//# sourceMappingURL=client.js.map /***/ }), -/***/ 16411: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 45400: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* module decorator */ module = __nccwpck_require__.nmd(module); Object.defineProperty(exports, "__esModule", ({ value: true })); -var is_1 = __nccwpck_require__(92757); -var object_1 = __nccwpck_require__(69249); +var tslib_1 = __nccwpck_require__(4351); +/* eslint-disable max-lines */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +var core_1 = __nccwpck_require__(79212); +var tracing_1 = __nccwpck_require__(64358); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var cookie = __nccwpck_require__(93658); +var domain = __nccwpck_require__(85229); +var os = __nccwpck_require__(12087); +var url = __nccwpck_require__(78835); +var sdk_1 = __nccwpck_require__(38836); /** - * Checks whether we're in the Node.js or Browser environment - * - * @returns Answer to given question + * Express-compatible tracing handler. + * @see Exposed as `Handlers.tracingHandler` */ -function isNodeEnv() { - return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; +function tracingHandler() { + return function sentryTracingMiddleware(req, res, next) { + // If there is a trace header set, we extract the data from it (parentSpanId, traceId, and sampling decision) + var traceparentData; + if (req.headers && utils_1.isString(req.headers['sentry-trace'])) { + traceparentData = tracing_1.extractTraceparentData(req.headers['sentry-trace']); + } + var transaction = core_1.startTransaction(tslib_1.__assign({ name: extractExpressTransactionName(req, { path: true, method: true }), op: 'http.server' }, traceparentData), + // extra context passed to the tracesSampler + { request: extractRequestData(req) }); + // We put the transaction on the scope so users can attach children to it + core_1.getCurrentHub().configureScope(function (scope) { + scope.setSpan(transaction); + }); + // We also set __sentry_transaction on the response so people can grab the transaction there to add + // spans to it later. + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + res.__sentry_transaction = transaction; + res.once('finish', function () { + // Push `transaction.finish` to the next event loop so open spans have a chance to finish before the transaction + // closes + setImmediate(function () { + addExpressReqToTransaction(transaction, req); + transaction.setHttpStatus(res.statusCode); + transaction.finish(); + }); + }); + next(); + }; } -exports.isNodeEnv = isNodeEnv; +exports.tracingHandler = tracingHandler; /** - * Requires a module which is protected against bundler minification. + * Set parameterized as transaction name e.g.: `GET /users/:id` + * Also adds more context data on the transaction from the request + */ +function addExpressReqToTransaction(transaction, req) { + if (!transaction) + return; + transaction.name = extractExpressTransactionName(req, { path: true, method: true }); + transaction.setData('url', req.originalUrl); + transaction.setData('baseUrl', req.baseUrl); + transaction.setData('query', req.query); +} +/** + * Extracts complete generalized path from the request object and uses it to construct transaction name. * - * @param request The module path to resolve + * eg. GET /mountpoint/user/:id + * + * @param req The ExpressRequest object + * @param options What to include in the transaction name (method, path, or both) + * + * @returns The fully constructed transaction name */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -function dynamicRequire(mod, request) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - return mod.require(request); +function extractExpressTransactionName(req, options) { + if (options === void 0) { options = {}; } + var _a; + var method = (_a = req.method) === null || _a === void 0 ? void 0 : _a.toUpperCase(); + var path = ''; + if (req.route) { + path = "" + (req.baseUrl || '') + req.route.path; + } + else if (req.originalUrl || req.url) { + path = utils_1.stripUrlQueryAndFragment(req.originalUrl || req.url || ''); + } + var info = ''; + if (options.method && method) { + info += method; + } + if (options.method && options.path) { + info += " "; + } + if (options.path && path) { + info += path; + } + return info; +} +/** JSDoc */ +function extractTransaction(req, type) { + var _a; + switch (type) { + case 'path': { + return extractExpressTransactionName(req, { path: true }); + } + case 'handler': { + return ((_a = req.route) === null || _a === void 0 ? void 0 : _a.stack[0].name) || ''; + } + case 'methodPath': + default: { + return extractExpressTransactionName(req, { path: true, method: true }); + } + } +} +/** Default user keys that'll be used to extract data from the request */ +var DEFAULT_USER_KEYS = ['id', 'username', 'email']; +/** JSDoc */ +function extractUserData(user, keys) { + var extractedUser = {}; + var attributes = Array.isArray(keys) ? keys : DEFAULT_USER_KEYS; + attributes.forEach(function (key) { + if (user && key in user) { + extractedUser[key] = user[key]; + } + }); + return extractedUser; } -exports.dynamicRequire = dynamicRequire; /** Default request keys that'll be used to extract data from the request */ var DEFAULT_REQUEST_KEYS = ['cookies', 'data', 'headers', 'method', 'query_string', 'url']; /** @@ -25205,34 +25104,30 @@ var DEFAULT_REQUEST_KEYS = ['cookies', 'data', 'headers', 'method', 'query_strin * provided. * @returns An object containing normalized request data */ -function extractNodeRequestData(req, keys) { +function extractRequestData(req, keys) { if (keys === void 0) { keys = DEFAULT_REQUEST_KEYS; } - // make sure we can safely use dynamicRequire below - if (!isNodeEnv()) { - throw new Error("Can't get node request data outside of a node environment"); - } var requestData = {}; // headers: - // node, express: req.headers + // node, express, nextjs: req.headers // koa: req.header var headers = (req.headers || req.header || {}); // method: - // node, express, koa: req.method + // node, express, koa, nextjs: req.method var method = req.method; // host: // express: req.hostname in > 4 and req.host in < 4 // koa: req.host - // node: req.headers.host + // node, nextjs: req.headers.host var host = req.hostname || req.host || headers.host || ''; // protocol: - // node: + // node, nextjs: // express, koa: req.protocol var protocol = req.protocol === 'https' || req.secure || (req.socket || {}).encrypted ? 'https' : 'http'; // url (including path and query string): // node, express: req.originalUrl - // koa: req.url + // koa, nextjs: req.url var originalUrl = (req.originalUrl || req.url || ''); // absolute url var absoluteUrl = protocol + "://" + host + originalUrl; @@ -25250,25 +25145,29 @@ function extractNodeRequestData(req, keys) { case 'cookies': // cookies: // node, express, koa: req.headers.cookie - // vercel, sails.js, express (w/ cookie middleware): req.cookies + // vercel, sails.js, express (w/ cookie middleware), nextjs: req.cookies // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.cookies = req.cookies || dynamicRequire(module, 'cookie').parse(headers.cookie || ''); + requestData.cookies = req.cookies || cookie.parse(headers.cookie || ''); break; case 'query_string': // query string: // node: req.url (raw) - // express, koa: req.query + // express, koa, nextjs: req.query // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access - requestData.query_string = dynamicRequire(module, 'url').parse(originalUrl || '', false).query; + requestData.query_string = req.query || url.parse(originalUrl || '', false).query; break; case 'data': if (method === 'GET' || method === 'HEAD') { break; } // body data: - // node, express, koa: req.body + // express, koa, nextjs: req.body + // + // when using node by itself, you have to read the incoming stream(see + // https://nodejs.dev/learn/get-http-request-body-data-using-nodejs); if a user is doing that, we can't know + // where they're going to store the final result, so they'll have to capture this data themselves if (req.body !== undefined) { - requestData.data = is_1.isString(req.body) ? req.body : JSON.stringify(object_1.normalize(req.body)); + requestData.data = utils_1.isString(req.body) ? req.body : JSON.stringify(utils_1.normalize(req.body)); } break; default: @@ -25279,332 +25178,274 @@ function extractNodeRequestData(req, keys) { }); return requestData; } -exports.extractNodeRequestData = extractNodeRequestData; -//# sourceMappingURL=node.js.map - -/***/ }), - -/***/ 69249: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -var tslib_1 = __nccwpck_require__(4351); -var browser_1 = __nccwpck_require__(30597); -var is_1 = __nccwpck_require__(92757); -var memo_1 = __nccwpck_require__(49515); -var stacktrace_1 = __nccwpck_require__(5986); -var string_1 = __nccwpck_require__(66538); +exports.extractRequestData = extractRequestData; /** - * Wrap a given object method with a higher-order function + * Enriches passed event with request data. * - * @param source An object that contains a method to be wrapped. - * @param name A name of method to be wrapped. - * @param replacement A function that should be used to wrap a given method. - * @returns void + * @param event Will be mutated and enriched with req data + * @param req Request object + * @param options object containing flags to enable functionality + * @hidden */ -function fill(source, name, replacement) { - if (!(name in source)) { - return; +function parseRequest(event, req, options) { + // eslint-disable-next-line no-param-reassign + options = tslib_1.__assign({ ip: false, request: true, serverName: true, transaction: true, user: true, version: true }, options); + if (options.version) { + event.contexts = tslib_1.__assign(tslib_1.__assign({}, event.contexts), { runtime: { + name: 'node', + version: global.process.version, + } }); } - var original = source[name]; - var wrapped = replacement(original); - // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work - // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" - if (typeof wrapped === 'function') { - try { - wrapped.prototype = wrapped.prototype || {}; - Object.defineProperties(wrapped, { - __sentry_original__: { - enumerable: false, - value: original, - }, - }); - } - catch (_Oo) { - // This can throw if multiple fill happens on a global object like XMLHttpRequest - // Fixes https://github.com/getsentry/sentry-javascript/issues/2043 - } + if (options.request) { + // if the option value is `true`, use the default set of keys by not passing anything to `extractRequestData()` + var extractedRequestData = Array.isArray(options.request) + ? extractRequestData(req, options.request) + : extractRequestData(req); + event.request = tslib_1.__assign(tslib_1.__assign({}, event.request), extractedRequestData); } - source[name] = wrapped; -} -exports.fill = fill; -/** - * Encodes given object into url-friendly format - * - * @param object An object that contains serializable values - * @returns string Encoded - */ -function urlEncode(object) { - return Object.keys(object) - .map(function (key) { return encodeURIComponent(key) + "=" + encodeURIComponent(object[key]); }) - .join('&'); -} -exports.urlEncode = urlEncode; -/** - * Transforms any object into an object literal with all it's attributes - * attached to it. - * - * @param value Initial source that we have to transform in order to be usable by the serializer - */ -function getWalkSource(value) { - if (is_1.isError(value)) { - var error = value; - var err = { - message: error.message, - name: error.name, - stack: error.stack, - }; - for (var i in error) { - if (Object.prototype.hasOwnProperty.call(error, i)) { - err[i] = error[i]; - } - } - return err; + if (options.serverName && !event.server_name) { + event.server_name = global.process.env.SENTRY_NAME || os.hostname(); } - if (is_1.isEvent(value)) { - var event_1 = value; - var source = {}; - source.type = event_1.type; - // Accessing event.target can throw (see getsentry/raven-js#838, #768) - try { - source.target = is_1.isElement(event_1.target) - ? browser_1.htmlTreeAsString(event_1.target) - : Object.prototype.toString.call(event_1.target); - } - catch (_oO) { - source.target = ''; - } - try { - source.currentTarget = is_1.isElement(event_1.currentTarget) - ? browser_1.htmlTreeAsString(event_1.currentTarget) - : Object.prototype.toString.call(event_1.currentTarget); - } - catch (_oO) { - source.currentTarget = ''; - } - if (typeof CustomEvent !== 'undefined' && is_1.isInstanceOf(value, CustomEvent)) { - source.detail = event_1.detail; - } - for (var i in event_1) { - if (Object.prototype.hasOwnProperty.call(event_1, i)) { - source[i] = event_1; - } + if (options.user) { + var extractedUser = req.user && utils_1.isPlainObject(req.user) ? extractUserData(req.user, options.user) : {}; + if (Object.keys(extractedUser)) { + event.user = tslib_1.__assign(tslib_1.__assign({}, event.user), extractedUser); } - return source; - } - return value; -} -/** Calculates bytes size of input string */ -function utf8Length(value) { - // eslint-disable-next-line no-bitwise - return ~-encodeURI(value).split(/%..|./).length; -} -/** Calculates bytes size of input object */ -function jsonSize(value) { - return utf8Length(JSON.stringify(value)); -} -/** JSDoc */ -function normalizeToSize(object, -// Default Node.js REPL depth -depth, -// 100kB, as 200kB is max payload size, so half sounds reasonable -maxSize) { - if (depth === void 0) { depth = 3; } - if (maxSize === void 0) { maxSize = 100 * 1024; } - var serialized = normalize(object, depth); - if (jsonSize(serialized) > maxSize) { - return normalizeToSize(object, depth - 1, maxSize); - } - return serialized; -} -exports.normalizeToSize = normalizeToSize; -/** - * Transform any non-primitive, BigInt, or Symbol-type value into a string. Acts as a no-op on strings, numbers, - * booleans, null, and undefined. - * - * @param value The value to stringify - * @returns For non-primitive, BigInt, and Symbol-type values, a string denoting the value's type, type and value, or - * type and `description` property, respectively. For non-BigInt, non-Symbol primitives, returns the original value, - * unchanged. - */ -function serializeValue(value) { - var type = Object.prototype.toString.call(value); - // Node.js REPL notation - if (typeof value === 'string') { - return value; - } - if (type === '[object Object]') { - return '[Object]'; - } - if (type === '[object Array]') { - return '[Array]'; - } - var normalized = normalizeValue(value); - return is_1.isPrimitive(normalized) ? normalized : type; -} -/** - * normalizeValue() - * - * Takes unserializable input and make it serializable friendly - * - * - translates undefined/NaN values to "[undefined]"/"[NaN]" respectively, - * - serializes Error objects - * - filter global objects - */ -function normalizeValue(value, key) { - if (key === 'domain' && value && typeof value === 'object' && value._events) { - return '[Domain]'; - } - if (key === 'domainEmitter') { - return '[DomainEmitter]'; - } - if (typeof global !== 'undefined' && value === global) { - return '[Global]'; - } - if (typeof window !== 'undefined' && value === window) { - return '[Window]'; - } - if (typeof document !== 'undefined' && value === document) { - return '[Document]'; - } - // React's SyntheticEvent thingy - if (is_1.isSyntheticEvent(value)) { - return '[SyntheticEvent]'; - } - if (typeof value === 'number' && value !== value) { - return '[NaN]'; - } - if (value === void 0) { - return '[undefined]'; - } - if (typeof value === 'function') { - return "[Function: " + stacktrace_1.getFunctionName(value) + "]"; - } - // symbols and bigints are considered primitives by TS, but aren't natively JSON-serilaizable - if (typeof value === 'symbol') { - return "[" + String(value) + "]"; - } - if (typeof value === 'bigint') { - return "[BigInt: " + String(value) + "]"; - } - return value; -} -/** - * Walks an object to perform a normalization on it - * - * @param key of object that's walked in current iteration - * @param value object to be walked - * @param depth Optional number indicating how deep should walking be performed - * @param memo Optional Memo class handling decycling - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -function walk(key, value, depth, memo) { - if (depth === void 0) { depth = +Infinity; } - if (memo === void 0) { memo = new memo_1.Memo(); } - // If we reach the maximum depth, serialize whatever has left - if (depth === 0) { - return serializeValue(value); - } - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - // If value implements `toJSON` method, call it and return early - if (value !== null && value !== undefined && typeof value.toJSON === 'function') { - return value.toJSON(); } - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ - // If normalized value is a primitive, there are no branches left to walk, so we can just bail out, as theres no point in going down that branch any further - var normalized = normalizeValue(value, key); - if (is_1.isPrimitive(normalized)) { - return normalized; - } - // Create source that we will use for next itterations, either objectified error object (Error type with extracted keys:value pairs) or the input itself - var source = getWalkSource(value); - // Create an accumulator that will act as a parent for all future itterations of that branch - var acc = Array.isArray(value) ? [] : {}; - // If we already walked that branch, bail out, as it's circular reference - if (memo.memoize(value)) { - return '[Circular ~]'; - } - // Walk all keys of the source - for (var innerKey in source) { - // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration. - if (!Object.prototype.hasOwnProperty.call(source, innerKey)) { - continue; + // client ip: + // node, nextjs: req.connection.remoteAddress + // express, koa: req.ip + if (options.ip) { + var ip = req.ip || (req.connection && req.connection.remoteAddress); + if (ip) { + event.user = tslib_1.__assign(tslib_1.__assign({}, event.user), { ip_address: ip }); } - // Recursively walk through all the child nodes - acc[innerKey] = walk(innerKey, source[innerKey], depth - 1, memo); - } - // Once walked through all the branches, remove the parent from memo storage - memo.unmemoize(value); - // Return accumulated values - return acc; -} -exports.walk = walk; -/** - * normalize() - * - * - Creates a copy to prevent original input mutation - * - Skip non-enumerablers - * - Calls `toJSON` if implemented - * - Removes circular references - * - Translates non-serializeable values (undefined/NaN/Functions) to serializable format - * - Translates known global objects/Classes to a string representations - * - Takes care of Error objects serialization - * - Optionally limit depth of final output - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -function normalize(input, depth) { - try { - return JSON.parse(JSON.stringify(input, function (key, value) { return walk(key, value, depth); })); } - catch (_oO) { - return '**non-serializable**'; + if (options.transaction && !event.transaction) { + // TODO do we even need this anymore? + // TODO make this work for nextjs + event.transaction = extractTransaction(req, options.transaction); } + return event; } -exports.normalize = normalize; +exports.parseRequest = parseRequest; /** - * Given any captured exception, extract its keys and create a sorted - * and truncated list that will be used inside the event message. - * eg. `Non-error exception captured with keys: foo, bar, baz` - */ -// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types -function extractExceptionKeysForMessage(exception, maxLength) { - if (maxLength === void 0) { maxLength = 40; } - var keys = Object.keys(getWalkSource(exception)); - keys.sort(); - if (!keys.length) { - return '[object has no keys]'; - } - if (keys[0].length >= maxLength) { - return string_1.truncate(keys[0], maxLength); - } - for (var includedKeys = keys.length; includedKeys > 0; includedKeys--) { - var serialized = keys.slice(0, includedKeys).join(', '); - if (serialized.length > maxLength) { - continue; - } - if (includedKeys === keys.length) { - return serialized; + * Express compatible request handler. + * @see Exposed as `Handlers.requestHandler` + */ +function requestHandler(options) { + var currentHub = core_1.getCurrentHub(); + var client = currentHub.getClient(); + // Initialise an instance of SessionFlusher on the client when `autoSessionTracking` is enabled and the + // `requestHandler` middleware is used indicating that we are running in SessionAggregates mode + if (client && sdk_1.isAutoSessionTrackingEnabled(client)) { + client.initSessionFlusher(); + // If Scope contains a Single mode Session, it is removed in favor of using Session Aggregates mode + var scope = currentHub.getScope(); + if (scope && scope.getSession()) { + scope.setSession(); } - return string_1.truncate(serialized, maxLength); } - return ''; + return function sentryRequestMiddleware(req, res, next) { + if (options && options.flushTimeout && options.flushTimeout > 0) { + // eslint-disable-next-line @typescript-eslint/unbound-method + var _end_1 = res.end; + res.end = function (chunk, encoding, cb) { + var _this = this; + void sdk_1.flush(options.flushTimeout) + .then(function () { + _end_1.call(_this, chunk, encoding, cb); + }) + .then(null, function (e) { + utils_1.logger.error(e); + }); + }; + } + var local = domain.create(); + local.add(req); + local.add(res); + local.on('error', next); + local.run(function () { + var currentHub = core_1.getCurrentHub(); + currentHub.configureScope(function (scope) { + scope.addEventProcessor(function (event) { return parseRequest(event, req, options); }); + var client = currentHub.getClient(); + if (sdk_1.isAutoSessionTrackingEnabled(client)) { + var scope_1 = currentHub.getScope(); + if (scope_1) { + // Set `status` of `RequestSession` to Ok, at the beginning of the request + scope_1.setRequestSession({ status: types_1.RequestSessionStatus.Ok }); + } + } + }); + res.once('finish', function () { + var client = currentHub.getClient(); + if (sdk_1.isAutoSessionTrackingEnabled(client)) { + setImmediate(function () { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (client && client._captureRequestSession) { + // Calling _captureRequestSession to capture request session at the end of the request by incrementing + // the correct SessionAggregates bucket i.e. crashed, errored or exited + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + client._captureRequestSession(); + } + }); + } + }); + next(); + }); + }; +} +exports.requestHandler = requestHandler; +/** JSDoc */ +function getStatusCodeFromResponse(error) { + var statusCode = error.status || error.statusCode || error.status_code || (error.output && error.output.statusCode); + return statusCode ? parseInt(statusCode, 10) : 500; +} +/** Returns true if response code is internal server error */ +function defaultShouldHandleError(error) { + var status = getStatusCodeFromResponse(error); + return status >= 500; } -exports.extractExceptionKeysForMessage = extractExceptionKeysForMessage; /** - * Given any object, return the new object with removed keys that value was `undefined`. - * Works recursively on objects and arrays. + * Express compatible error handler. + * @see Exposed as `Handlers.errorHandler` */ -function dropUndefinedKeys(val) { - var e_1, _a; - if (is_1.isPlainObject(val)) { - var obj = val; - var rv = {}; - try { - for (var _b = tslib_1.__values(Object.keys(obj)), _c = _b.next(); !_c.done; _c = _b.next()) { - var key = _c.value; - if (typeof obj[key] !== 'undefined') { - rv[key] = dropUndefinedKeys(obj[key]); +function errorHandler(options) { + return function sentryErrorMiddleware(error, _req, res, next) { + // eslint-disable-next-line @typescript-eslint/unbound-method + var shouldHandleError = (options && options.shouldHandleError) || defaultShouldHandleError; + if (shouldHandleError(error)) { + core_1.withScope(function (_scope) { + // For some reason we need to set the transaction on the scope again + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + var transaction = res.__sentry_transaction; + if (transaction && _scope.getSpan() === undefined) { + _scope.setSpan(transaction); } + var client = core_1.getCurrentHub().getClient(); + if (client && sdk_1.isAutoSessionTrackingEnabled(client)) { + // Check if the `SessionFlusher` is instantiated on the client to go into this branch that marks the + // `requestSession.status` as `Crashed`, and this check is necessary because the `SessionFlusher` is only + // instantiated when the the`requestHandler` middleware is initialised, which indicates that we should be + // running in SessionAggregates mode + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + var isSessionAggregatesMode = client._sessionFlusher !== undefined; + if (isSessionAggregatesMode) { + var requestSession = _scope.getRequestSession(); + // If an error bubbles to the `errorHandler`, then this is an unhandled error, and should be reported as a + // Crashed session. The `_requestSession.status` is checked to ensure that this error is happening within + // the bounds of a request, and if so the status is updated + if (requestSession && requestSession.status !== undefined) + requestSession.status = types_1.RequestSessionStatus.Crashed; + } + } + var eventId = core_1.captureException(error); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + res.sentry = eventId; + next(error); + }); + return; + } + next(error); + }; +} +exports.errorHandler = errorHandler; +//# sourceMappingURL=handlers.js.map + +/***/ }), + +/***/ 22783: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var types_1 = __nccwpck_require__(83789); +exports.Severity = types_1.Severity; +exports.Status = types_1.Status; +var core_1 = __nccwpck_require__(79212); +exports.addGlobalEventProcessor = core_1.addGlobalEventProcessor; +exports.addBreadcrumb = core_1.addBreadcrumb; +exports.captureException = core_1.captureException; +exports.captureEvent = core_1.captureEvent; +exports.captureMessage = core_1.captureMessage; +exports.configureScope = core_1.configureScope; +exports.getHubFromCarrier = core_1.getHubFromCarrier; +exports.getCurrentHub = core_1.getCurrentHub; +exports.Hub = core_1.Hub; +exports.makeMain = core_1.makeMain; +exports.Scope = core_1.Scope; +exports.startTransaction = core_1.startTransaction; +exports.SDK_VERSION = core_1.SDK_VERSION; +exports.setContext = core_1.setContext; +exports.setExtra = core_1.setExtra; +exports.setExtras = core_1.setExtras; +exports.setTag = core_1.setTag; +exports.setTags = core_1.setTags; +exports.setUser = core_1.setUser; +exports.withScope = core_1.withScope; +var backend_1 = __nccwpck_require__(40508); +exports.NodeBackend = backend_1.NodeBackend; +var client_1 = __nccwpck_require__(86147); +exports.NodeClient = client_1.NodeClient; +var sdk_1 = __nccwpck_require__(38836); +exports.defaultIntegrations = sdk_1.defaultIntegrations; +exports.init = sdk_1.init; +exports.lastEventId = sdk_1.lastEventId; +exports.flush = sdk_1.flush; +exports.close = sdk_1.close; +exports.getSentryRelease = sdk_1.getSentryRelease; +var utils_1 = __nccwpck_require__(27937); +exports.deepReadDirSync = utils_1.deepReadDirSync; +var version_1 = __nccwpck_require__(31271); +exports.SDK_NAME = version_1.SDK_NAME; +var core_2 = __nccwpck_require__(79212); +var hub_1 = __nccwpck_require__(6393); +var domain = __nccwpck_require__(85229); +var Handlers = __nccwpck_require__(45400); +exports.Handlers = Handlers; +var NodeIntegrations = __nccwpck_require__(72310); +var Transports = __nccwpck_require__(21437); +exports.Transports = Transports; +var INTEGRATIONS = tslib_1.__assign(tslib_1.__assign({}, core_2.Integrations), NodeIntegrations); +exports.Integrations = INTEGRATIONS; +// We need to patch domain on the global __SENTRY__ object to make it work for node in cross-platform packages like +// @sentry/hub. If we don't do this, browser bundlers will have troubles resolving `require('domain')`. +var carrier = hub_1.getMainCarrier(); +if (carrier.__SENTRY__) { + carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; + carrier.__SENTRY__.extensions.domain = carrier.__SENTRY__.extensions.domain || domain; +} +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 29552: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var util = __nccwpck_require__(31669); +/** Console module integration */ +var Console = /** @class */ (function () { + function Console() { + /** + * @inheritDoc + */ + this.name = Console.id; + } + /** + * @inheritDoc + */ + Console.prototype.setupOnce = function () { + var e_1, _a; + try { + for (var _b = tslib_1.__values(['debug', 'info', 'warn', 'error', 'log']), _c = _b.next(); !_c.done; _c = _b.next()) { + var level = _c.value; + utils_1.fill(console, level, createConsoleWrapper(level)); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } @@ -25614,16517 +25455,19823 @@ function dropUndefinedKeys(val) { } finally { if (e_1) throw e_1.error; } } - return rv; - } - if (Array.isArray(val)) { - return val.map(dropUndefinedKeys); - } - return val; + }; + /** + * @inheritDoc + */ + Console.id = 'Console'; + return Console; +}()); +exports.Console = Console; +/** + * Wrapper function that'll be used for every console level + */ +function createConsoleWrapper(level) { + return function consoleWrapper(originalConsoleMethod) { + var sentryLevel; + switch (level) { + case 'debug': + sentryLevel = types_1.Severity.Debug; + break; + case 'error': + sentryLevel = types_1.Severity.Error; + break; + case 'info': + sentryLevel = types_1.Severity.Info; + break; + case 'warn': + sentryLevel = types_1.Severity.Warning; + break; + default: + sentryLevel = types_1.Severity.Log; + } + return function () { + if (core_1.getCurrentHub().getIntegration(Console)) { + core_1.getCurrentHub().addBreadcrumb({ + category: 'console', + level: sentryLevel, + message: util.format.apply(undefined, arguments), + }, { + input: tslib_1.__spread(arguments), + level: level, + }); + } + originalConsoleMethod.apply(this, arguments); + }; + }; } -exports.dropUndefinedKeys = dropUndefinedKeys; -//# sourceMappingURL=object.js.map +//# sourceMappingURL=console.js.map /***/ }), -/***/ 39188: -/***/ ((__unused_webpack_module, exports) => { +/***/ 76280: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript -// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js Object.defineProperty(exports, "__esModule", ({ value: true })); -/** JSDoc */ -function normalizeArray(parts, allowAboveRoot) { - // if the path tries to go above the root, `up` ends up > 0 - var up = 0; - for (var i = parts.length - 1; i >= 0; i--) { - var last = parts[i]; - if (last === '.') { - parts.splice(i, 1); - } - else if (last === '..') { - parts.splice(i, 1); - // eslint-disable-next-line no-plusplus - up++; - } - else if (up) { - parts.splice(i, 1); - // eslint-disable-next-line no-plusplus - up--; - } - } - // if the path is allowed to go above the root, restore leading ..s - if (allowAboveRoot) { - // eslint-disable-next-line no-plusplus - for (; up--; up) { - parts.unshift('..'); - } - } - return parts; -} -// Split a filename into [root, dir, basename, ext], unix version -// 'root' is just a slash, or nothing. -var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/; -/** JSDoc */ -function splitPath(filename) { - var parts = splitPathRe.exec(filename); - return parts ? parts.slice(1) : []; -} -// path.resolve([from ...], to) -// posix version -/** JSDoc */ -function resolve() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - var resolvedPath = ''; - var resolvedAbsolute = false; - for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { - var path = i >= 0 ? args[i] : '/'; - // Skip empty entries - if (!path) { - continue; - } - resolvedPath = path + "/" + resolvedPath; - resolvedAbsolute = path.charAt(0) === '/'; - } - // At this point the path should be resolved to a full absolute path, but - // handle relative paths to be safe (might happen when process.cwd() fails) - // Normalize the path - resolvedPath = normalizeArray(resolvedPath.split('/').filter(function (p) { return !!p; }), !resolvedAbsolute).join('/'); - return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; -} -exports.resolve = resolve; -/** JSDoc */ -function trim(arr) { - var start = 0; - for (; start < arr.length; start++) { - if (arr[start] !== '') { - break; - } +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var utils_1 = __nccwpck_require__(1620); +var http_1 = __nccwpck_require__(84103); +var NODE_VERSION = utils_1.parseSemver(process.versions.node); +/** http module integration */ +var Http = /** @class */ (function () { + /** + * @inheritDoc + */ + function Http(options) { + if (options === void 0) { options = {}; } + /** + * @inheritDoc + */ + this.name = Http.id; + this._breadcrumbs = typeof options.breadcrumbs === 'undefined' ? true : options.breadcrumbs; + this._tracing = typeof options.tracing === 'undefined' ? false : options.tracing; } - var end = arr.length - 1; - for (; end >= 0; end--) { - if (arr[end] !== '') { - break; + /** + * @inheritDoc + */ + Http.prototype.setupOnce = function () { + // No need to instrument if we don't want to track anything + if (!this._breadcrumbs && !this._tracing) { + return; } - } - if (start > end) { - return []; - } - return arr.slice(start, end - start + 1); -} -// path.relative(from, to) -// posix version -/** JSDoc */ -function relative(from, to) { - /* eslint-disable no-param-reassign */ - from = resolve(from).substr(1); - to = resolve(to).substr(1); - /* eslint-enable no-param-reassign */ - var fromParts = trim(from.split('/')); - var toParts = trim(to.split('/')); - var length = Math.min(fromParts.length, toParts.length); - var samePartsLength = length; - for (var i = 0; i < length; i++) { - if (fromParts[i] !== toParts[i]) { - samePartsLength = i; - break; + var wrappedHandlerMaker = _createWrappedRequestMethodFactory(this._breadcrumbs, this._tracing); + var httpModule = __nccwpck_require__(98605); + utils_1.fill(httpModule, 'get', wrappedHandlerMaker); + utils_1.fill(httpModule, 'request', wrappedHandlerMaker); + // NOTE: Prior to Node 9, `https` used internals of `http` module, thus we don't patch it. + // If we do, we'd get double breadcrumbs and double spans for `https` calls. + // It has been changed in Node 9, so for all versions equal and above, we patch `https` separately. + if (NODE_VERSION.major && NODE_VERSION.major > 8) { + var httpsModule = __nccwpck_require__(57211); + utils_1.fill(httpsModule, 'get', wrappedHandlerMaker); + utils_1.fill(httpsModule, 'request', wrappedHandlerMaker); } - } - var outputParts = []; - for (var i = samePartsLength; i < fromParts.length; i++) { - outputParts.push('..'); - } - outputParts = outputParts.concat(toParts.slice(samePartsLength)); - return outputParts.join('/'); -} -exports.relative = relative; -// path.normalize(path) -// posix version -/** JSDoc */ -function normalizePath(path) { - var isPathAbsolute = isAbsolute(path); - var trailingSlash = path.substr(-1) === '/'; - // Normalize the path - var normalizedPath = normalizeArray(path.split('/').filter(function (p) { return !!p; }), !isPathAbsolute).join('/'); - if (!normalizedPath && !isPathAbsolute) { - normalizedPath = '.'; - } - if (normalizedPath && trailingSlash) { - normalizedPath += '/'; - } - return (isPathAbsolute ? '/' : '') + normalizedPath; -} -exports.normalizePath = normalizePath; -// posix version -/** JSDoc */ -function isAbsolute(path) { - return path.charAt(0) === '/'; -} -exports.isAbsolute = isAbsolute; -// posix version -/** JSDoc */ -function join() { - var args = []; - for (var _i = 0; _i < arguments.length; _i++) { - args[_i] = arguments[_i]; - } - return normalizePath(args.join('/')); -} -exports.join = join; -/** JSDoc */ -function dirname(path) { - var result = splitPath(path); - var root = result[0]; - var dir = result[1]; - if (!root && !dir) { - // No dirname whatsoever - return '.'; - } - if (dir) { - // It has a dirname, strip trailing slash - dir = dir.substr(0, dir.length - 1); - } - return root + dir; + }; + /** + * @inheritDoc + */ + Http.id = 'Http'; + return Http; +}()); +exports.Http = Http; +/** + * Function which creates a function which creates wrapped versions of internal `request` and `get` calls within `http` + * and `https` modules. (NB: Not a typo - this is a creator^2!) + * + * @param breadcrumbsEnabled Whether or not to record outgoing requests as breadcrumbs + * @param tracingEnabled Whether or not to record outgoing requests as tracing spans + * + * @returns A function which accepts the exiting handler and returns a wrapped handler + */ +function _createWrappedRequestMethodFactory(breadcrumbsEnabled, tracingEnabled) { + return function wrappedRequestMethodFactory(originalRequestMethod) { + return function wrappedMethod() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + // eslint-disable-next-line @typescript-eslint/no-this-alias + var httpModule = this; + var requestArgs = http_1.normalizeRequestArgs(args); + var requestOptions = requestArgs[0]; + var requestUrl = http_1.extractUrl(requestOptions); + // we don't want to record requests to Sentry as either breadcrumbs or spans, so just use the original method + if (http_1.isSentryRequest(requestUrl)) { + return originalRequestMethod.apply(httpModule, requestArgs); + } + var span; + var parentSpan; + var scope = core_1.getCurrentHub().getScope(); + if (scope && tracingEnabled) { + parentSpan = scope.getSpan(); + if (parentSpan) { + span = parentSpan.startChild({ + description: (requestOptions.method || 'GET') + " " + requestUrl, + op: 'request', + }); + var sentryTraceHeader = span.toTraceparent(); + utils_1.logger.log("[Tracing] Adding sentry-trace header " + sentryTraceHeader + " to outgoing request to " + requestUrl + ": "); + requestOptions.headers = tslib_1.__assign(tslib_1.__assign({}, requestOptions.headers), { 'sentry-trace': sentryTraceHeader }); + } + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return originalRequestMethod + .apply(httpModule, requestArgs) + .once('response', function (res) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + var req = this; + if (breadcrumbsEnabled) { + addRequestBreadcrumb('response', requestUrl, req, res); + } + if (tracingEnabled && span) { + if (res.statusCode) { + span.setHttpStatus(res.statusCode); + } + span.description = http_1.cleanSpanDescription(span.description, requestOptions, req); + span.finish(); + } + }) + .once('error', function () { + // eslint-disable-next-line @typescript-eslint/no-this-alias + var req = this; + if (breadcrumbsEnabled) { + addRequestBreadcrumb('error', requestUrl, req); + } + if (tracingEnabled && span) { + span.setHttpStatus(500); + span.description = http_1.cleanSpanDescription(span.description, requestOptions, req); + span.finish(); + } + }); + }; + }; } -exports.dirname = dirname; -/** JSDoc */ -function basename(path, ext) { - var f = splitPath(path)[2]; - if (ext && f.substr(ext.length * -1) === ext) { - f = f.substr(0, f.length - ext.length); +/** + * Captures Breadcrumb based on provided request/response pair + */ +function addRequestBreadcrumb(event, url, req, res) { + if (!core_1.getCurrentHub().getIntegration(Http)) { + return; } - return f; + core_1.getCurrentHub().addBreadcrumb({ + category: 'http', + data: { + method: req.method, + status_code: res && res.statusCode, + url: url, + }, + type: 'http', + }, { + event: event, + request: req, + response: res, + }); } -exports.basename = basename; -//# sourceMappingURL=path.js.map +//# sourceMappingURL=http.js.map /***/ }), -/***/ 1243: -/***/ ((__unused_webpack_module, exports) => { +/***/ 72310: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.setPrototypeOf = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties); -/** - * setPrototypeOf polyfill using __proto__ - */ -// eslint-disable-next-line @typescript-eslint/ban-types -function setProtoOf(obj, proto) { - // @ts-ignore __proto__ does not exist on obj - obj.__proto__ = proto; - return obj; -} -/** - * setPrototypeOf polyfill using mixin - */ -// eslint-disable-next-line @typescript-eslint/ban-types -function mixinProperties(obj, proto) { - for (var prop in proto) { - // eslint-disable-next-line no-prototype-builtins - if (!obj.hasOwnProperty(prop)) { - // @ts-ignore typescript complains about indexing so we remove - obj[prop] = proto[prop]; - } - } - return obj; -} -//# sourceMappingURL=polyfill.js.map +var console_1 = __nccwpck_require__(29552); +exports.Console = console_1.Console; +var http_1 = __nccwpck_require__(76280); +exports.Http = http_1.Http; +var onuncaughtexception_1 = __nccwpck_require__(50443); +exports.OnUncaughtException = onuncaughtexception_1.OnUncaughtException; +var onunhandledrejection_1 = __nccwpck_require__(87344); +exports.OnUnhandledRejection = onunhandledrejection_1.OnUnhandledRejection; +var linkederrors_1 = __nccwpck_require__(70208); +exports.LinkedErrors = linkederrors_1.LinkedErrors; +var modules_1 = __nccwpck_require__(90046); +exports.Modules = modules_1.Modules; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 31811: +/***/ 70208: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var error_1 = __nccwpck_require__(66238); -var syncpromise_1 = __nccwpck_require__(87833); -/** A simple queue that holds promises. */ -var PromiseBuffer = /** @class */ (function () { - function PromiseBuffer(_limit) { - this._limit = _limit; - /** Internal set of queued Promises */ - this._buffer = []; +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var utils_1 = __nccwpck_require__(1620); +var parsers_1 = __nccwpck_require__(19090); +var DEFAULT_KEY = 'cause'; +var DEFAULT_LIMIT = 5; +/** Adds SDK info to an event. */ +var LinkedErrors = /** @class */ (function () { + /** + * @inheritDoc + */ + function LinkedErrors(options) { + if (options === void 0) { options = {}; } + /** + * @inheritDoc + */ + this.name = LinkedErrors.id; + this._key = options.key || DEFAULT_KEY; + this._limit = options.limit || DEFAULT_LIMIT; } /** - * Says if the buffer is ready to take more requests + * @inheritDoc */ - PromiseBuffer.prototype.isReady = function () { - return this._limit === undefined || this.length() < this._limit; + LinkedErrors.prototype.setupOnce = function () { + core_1.addGlobalEventProcessor(function (event, hint) { + var self = core_1.getCurrentHub().getIntegration(LinkedErrors); + if (self) { + var handler = self._handler && self._handler.bind(self); + return typeof handler === 'function' ? handler(event, hint) : event; + } + return event; + }); }; /** - * Add a promise to the queue. - * - * @param task Can be any PromiseLike - * @returns The original promise. + * @inheritDoc */ - PromiseBuffer.prototype.add = function (task) { + LinkedErrors.prototype._handler = function (event, hint) { var _this = this; - if (!this.isReady()) { - return syncpromise_1.SyncPromise.reject(new error_1.SentryError('Not adding Promise due to buffer limit reached.')); - } - if (this._buffer.indexOf(task) === -1) { - this._buffer.push(task); + if (!event.exception || !event.exception.values || !hint || !utils_1.isInstanceOf(hint.originalException, Error)) { + return utils_1.SyncPromise.resolve(event); } - task - .then(function () { return _this.remove(task); }) - .then(null, function () { - return _this.remove(task).then(null, function () { - // We have to add this catch here otherwise we have an unhandledPromiseRejection - // because it's a new Promise chain. + return new utils_1.SyncPromise(function (resolve) { + void _this._walkErrorTree(hint.originalException, _this._key) + .then(function (linkedErrors) { + if (event && event.exception && event.exception.values) { + event.exception.values = tslib_1.__spread(linkedErrors, event.exception.values); + } + resolve(event); + }) + .then(null, function () { + resolve(event); }); }); - return task; - }; - /** - * Remove a promise to the queue. - * - * @param task Can be any PromiseLike - * @returns Removed promise. - */ - PromiseBuffer.prototype.remove = function (task) { - var removedTask = this._buffer.splice(this._buffer.indexOf(task), 1)[0]; - return removedTask; - }; - /** - * This function returns the number of unresolved promises in the queue. - */ - PromiseBuffer.prototype.length = function () { - return this._buffer.length; }; /** - * This will drain the whole queue, returns true if queue is empty or drained. - * If timeout is provided and the queue takes longer to drain, the promise still resolves but with false. - * - * @param timeout Number in ms to wait until it resolves with false. + * @inheritDoc */ - PromiseBuffer.prototype.drain = function (timeout) { + LinkedErrors.prototype._walkErrorTree = function (error, key, stack) { var _this = this; - return new syncpromise_1.SyncPromise(function (resolve) { - var capturedSetTimeout = setTimeout(function () { - if (timeout && timeout > 0) { - resolve(false); - } - }, timeout); - syncpromise_1.SyncPromise.all(_this._buffer) - .then(function () { - clearTimeout(capturedSetTimeout); - resolve(true); + if (stack === void 0) { stack = []; } + if (!utils_1.isInstanceOf(error[key], Error) || stack.length + 1 >= this._limit) { + return utils_1.SyncPromise.resolve(stack); + } + return new utils_1.SyncPromise(function (resolve, reject) { + void parsers_1.getExceptionFromError(error[key]) + .then(function (exception) { + void _this._walkErrorTree(error[key], key, tslib_1.__spread([exception], stack)) + .then(resolve) + .then(null, function () { + reject(); + }); }) .then(null, function () { - resolve(true); + reject(); }); }); }; - return PromiseBuffer; + /** + * @inheritDoc + */ + LinkedErrors.id = 'LinkedErrors'; + return LinkedErrors; }()); -exports.PromiseBuffer = PromiseBuffer; -//# sourceMappingURL=promisebuffer.js.map +exports.LinkedErrors = LinkedErrors; +//# sourceMappingURL=linkederrors.js.map /***/ }), -/***/ 5986: -/***/ ((__unused_webpack_module, exports) => { +/***/ 90046: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var defaultFunctionName = ''; -/** - * Safely extract function name from itself - */ -function getFunctionName(fn) { +var tslib_1 = __nccwpck_require__(4351); +var fs_1 = __nccwpck_require__(35747); +var path_1 = __nccwpck_require__(85622); +var moduleCache; +/** Extract information about paths */ +function getPaths() { try { - if (!fn || typeof fn !== 'function') { - return defaultFunctionName; - } - return fn.name || defaultFunctionName; + return require.cache ? Object.keys(require.cache) : []; } catch (e) { - // Just accessing custom props in some Selenium environments - // can cause a "Permission denied" exception (see raven-js#495). - return defaultFunctionName; + return []; } } -exports.getFunctionName = getFunctionName; -//# sourceMappingURL=stacktrace.js.map +/** Extract information about package.json modules */ +function collectModules() { + var mainPaths = (require.main && require.main.paths) || []; + var paths = getPaths(); + var infos = {}; + var seen = {}; + paths.forEach(function (path) { + var dir = path; + /** Traverse directories upward in the search of package.json file */ + var updir = function () { + var orig = dir; + dir = path_1.dirname(orig); + if (!dir || orig === dir || seen[orig]) { + return undefined; + } + if (mainPaths.indexOf(dir) < 0) { + return updir(); + } + var pkgfile = path_1.join(orig, 'package.json'); + seen[orig] = true; + if (!fs_1.existsSync(pkgfile)) { + return updir(); + } + try { + var info = JSON.parse(fs_1.readFileSync(pkgfile, 'utf8')); + infos[info.name] = info.version; + } + catch (_oO) { + // no-empty + } + }; + updir(); + }); + return infos; +} +/** Add node modules / packages to the event */ +var Modules = /** @class */ (function () { + function Modules() { + /** + * @inheritDoc + */ + this.name = Modules.id; + } + /** + * @inheritDoc + */ + Modules.prototype.setupOnce = function (addGlobalEventProcessor, getCurrentHub) { + var _this = this; + addGlobalEventProcessor(function (event) { + if (!getCurrentHub().getIntegration(Modules)) { + return event; + } + return tslib_1.__assign(tslib_1.__assign({}, event), { modules: _this._getModules() }); + }); + }; + /** Fetches the list of modules and the versions loaded by the entry file for your node.js app. */ + Modules.prototype._getModules = function () { + if (!moduleCache) { + moduleCache = collectModules(); + } + return moduleCache; + }; + /** + * @inheritDoc + */ + Modules.id = 'Modules'; + return Modules; +}()); +exports.Modules = Modules; +//# sourceMappingURL=modules.js.map /***/ }), -/***/ 66538: +/***/ 50443: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var is_1 = __nccwpck_require__(92757); -/** - * Truncates given string to the maximum characters count - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string - * @returns string Encoded - */ -function truncate(str, max) { - if (max === void 0) { max = 0; } - if (typeof str !== 'string' || max === 0) { - return str; - } - return str.length <= max ? str : str.substr(0, max) + "..."; -} -exports.truncate = truncate; -/** - * This is basically just `trim_line` from - * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67 - * - * @param str An object that contains serializable values - * @param max Maximum number of characters in truncated string - * @returns string Encoded - */ -function snipLine(line, colno) { - var newLine = line; - var ll = newLine.length; - if (ll <= 150) { - return newLine; - } - if (colno > ll) { - // eslint-disable-next-line no-param-reassign - colno = ll; - } - var start = Math.max(colno - 60, 0); - if (start < 5) { - start = 0; - } - var end = Math.min(start + 140, ll); - if (end > ll - 5) { - end = ll; - } - if (end === ll) { - start = Math.max(end - 140, 0); - } - newLine = newLine.slice(start, end); - if (start > 0) { - newLine = "'{snip} " + newLine; - } - if (end < ll) { - newLine += ' {snip}'; +var core_1 = __nccwpck_require__(79212); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var errorhandling_1 = __nccwpck_require__(5635); +/** Global Promise Rejection handler */ +var OnUncaughtException = /** @class */ (function () { + /** + * @inheritDoc + */ + function OnUncaughtException(_options) { + if (_options === void 0) { _options = {}; } + this._options = _options; + /** + * @inheritDoc + */ + this.name = OnUncaughtException.id; + /** + * @inheritDoc + */ + this.handler = this._makeErrorHandler(); } - return newLine; -} -exports.snipLine = snipLine; -/** - * Join values in array - * @param input array of values to be joined together - * @param delimiter string to be placed in-between values - * @returns Joined values - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function safeJoin(input, delimiter) { - if (!Array.isArray(input)) { - return ''; + /** + * @inheritDoc + */ + OnUncaughtException.prototype.setupOnce = function () { + global.process.on('uncaughtException', this.handler.bind(this)); + }; + /** + * @hidden + */ + OnUncaughtException.prototype._makeErrorHandler = function () { + var _this = this; + var timeout = 2000; + var caughtFirstError = false; + var caughtSecondError = false; + var calledFatalError = false; + var firstError; + return function (error) { + var onFatalError = errorhandling_1.logAndExitProcess; + var client = core_1.getCurrentHub().getClient(); + if (_this._options.onFatalError) { + // eslint-disable-next-line @typescript-eslint/unbound-method + onFatalError = _this._options.onFatalError; + } + else if (client && client.getOptions().onFatalError) { + // eslint-disable-next-line @typescript-eslint/unbound-method + onFatalError = client.getOptions().onFatalError; + } + if (!caughtFirstError) { + var hub_1 = core_1.getCurrentHub(); + // this is the first uncaught error and the ultimate reason for shutting down + // we want to do absolutely everything possible to ensure it gets captured + // also we want to make sure we don't go recursion crazy if more errors happen after this one + firstError = error; + caughtFirstError = true; + if (hub_1.getIntegration(OnUncaughtException)) { + hub_1.withScope(function (scope) { + scope.setLevel(types_1.Severity.Fatal); + hub_1.captureException(error, { + originalException: error, + data: { mechanism: { handled: false, type: 'onuncaughtexception' } }, + }); + if (!calledFatalError) { + calledFatalError = true; + onFatalError(error); + } + }); + } + else { + if (!calledFatalError) { + calledFatalError = true; + onFatalError(error); + } + } + } + else if (calledFatalError) { + // we hit an error *after* calling onFatalError - pretty boned at this point, just shut it down + utils_1.logger.warn('uncaught exception after calling fatal error shutdown callback - this is bad! forcing shutdown'); + errorhandling_1.logAndExitProcess(error); + } + else if (!caughtSecondError) { + // two cases for how we can hit this branch: + // - capturing of first error blew up and we just caught the exception from that + // - quit trying to capture, proceed with shutdown + // - a second independent error happened while waiting for first error to capture + // - want to avoid causing premature shutdown before first error capture finishes + // it's hard to immediately tell case 1 from case 2 without doing some fancy/questionable domain stuff + // so let's instead just delay a bit before we proceed with our action here + // in case 1, we just wait a bit unnecessarily but ultimately do the same thing + // in case 2, the delay hopefully made us wait long enough for the capture to finish + // two potential nonideal outcomes: + // nonideal case 1: capturing fails fast, we sit around for a few seconds unnecessarily before proceeding correctly by calling onFatalError + // nonideal case 2: case 2 happens, 1st error is captured but slowly, timeout completes before capture and we treat second error as the sendErr of (nonexistent) failure from trying to capture first error + // note that after hitting this branch, we might catch more errors where (caughtSecondError && !calledFatalError) + // we ignore them - they don't matter to us, we're just waiting for the second error timeout to finish + caughtSecondError = true; + setTimeout(function () { + if (!calledFatalError) { + // it was probably case 1, let's treat err as the sendErr and call onFatalError + calledFatalError = true; + onFatalError(firstError, error); + } + else { + // it was probably case 2, our first error finished capturing while we waited, cool, do nothing + } + }, timeout); // capturing could take at least sendTimeout to fail, plus an arbitrary second for how long it takes to collect surrounding source etc + } + }; + }; + /** + * @inheritDoc + */ + OnUncaughtException.id = 'OnUncaughtException'; + return OnUncaughtException; +}()); +exports.OnUncaughtException = OnUncaughtException; +//# sourceMappingURL=onuncaughtexception.js.map + +/***/ }), + +/***/ 87344: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var core_1 = __nccwpck_require__(79212); +var utils_1 = __nccwpck_require__(1620); +var errorhandling_1 = __nccwpck_require__(5635); +/** Global Promise Rejection handler */ +var OnUnhandledRejection = /** @class */ (function () { + /** + * @inheritDoc + */ + function OnUnhandledRejection(_options) { + if (_options === void 0) { _options = { mode: 'warn' }; } + this._options = _options; + /** + * @inheritDoc + */ + this.name = OnUnhandledRejection.id; } - var output = []; - // eslint-disable-next-line @typescript-eslint/prefer-for-of - for (var i = 0; i < input.length; i++) { - var value = input[i]; - try { - output.push(String(value)); + /** + * @inheritDoc + */ + OnUnhandledRejection.prototype.setupOnce = function () { + global.process.on('unhandledRejection', this.sendUnhandledPromise.bind(this)); + }; + /** + * Send an exception with reason + * @param reason string + * @param promise promise + */ + // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any + OnUnhandledRejection.prototype.sendUnhandledPromise = function (reason, promise) { + var hub = core_1.getCurrentHub(); + if (!hub.getIntegration(OnUnhandledRejection)) { + this._handleRejection(reason); + return; + } + /* eslint-disable @typescript-eslint/no-unsafe-member-access */ + var context = (promise.domain && promise.domain.sentryContext) || {}; + hub.withScope(function (scope) { + scope.setExtra('unhandledPromiseRejection', true); + // Preserve backwards compatibility with raven-node for now + if (context.user) { + scope.setUser(context.user); + } + if (context.tags) { + scope.setTags(context.tags); + } + if (context.extra) { + scope.setExtras(context.extra); + } + hub.captureException(reason, { + originalException: promise, + data: { mechanism: { handled: false, type: 'onunhandledrejection' } }, + }); + }); + /* eslint-disable @typescript-eslint/no-unsafe-member-access */ + this._handleRejection(reason); + }; + /** + * Handler for `mode` option + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + OnUnhandledRejection.prototype._handleRejection = function (reason) { + // https://github.com/nodejs/node/blob/7cf6f9e964aa00772965391c23acda6d71972a9a/lib/internal/process/promises.js#L234-L240 + var rejectionWarning = 'This error originated either by ' + + 'throwing inside of an async function without a catch block, ' + + 'or by rejecting a promise which was not handled with .catch().' + + ' The promise rejected with the reason:'; + /* eslint-disable no-console */ + if (this._options.mode === 'warn') { + utils_1.consoleSandbox(function () { + console.warn(rejectionWarning); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + console.error(reason && reason.stack ? reason.stack : reason); + }); } - catch (e) { - output.push('[value cannot be serialized]'); + else if (this._options.mode === 'strict') { + utils_1.consoleSandbox(function () { + console.warn(rejectionWarning); + }); + errorhandling_1.logAndExitProcess(reason); } - } - return output.join(delimiter); -} -exports.safeJoin = safeJoin; + /* eslint-enable no-console */ + }; + /** + * @inheritDoc + */ + OnUnhandledRejection.id = 'OnUnhandledRejection'; + return OnUnhandledRejection; +}()); +exports.OnUnhandledRejection = OnUnhandledRejection; +//# sourceMappingURL=onunhandledrejection.js.map + +/***/ }), + +/***/ 5635: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var core_1 = __nccwpck_require__(79212); +var utils_1 = __nccwpck_require__(1620); +var DEFAULT_SHUTDOWN_TIMEOUT = 2000; /** - * Checks if the value matches a regex or includes the string - * @param value The string value to be checked against - * @param pattern Either a regex or a string that must be contained in value + * @hidden */ -function isMatchingPattern(value, pattern) { - if (!is_1.isString(value)) { - return false; - } - if (is_1.isRegExp(pattern)) { - return pattern.test(value); - } - if (typeof pattern === 'string') { - return value.indexOf(pattern) !== -1; +function logAndExitProcess(error) { + // eslint-disable-next-line no-console + console.error(error && error.stack ? error.stack : error); + var client = core_1.getCurrentHub().getClient(); + if (client === undefined) { + utils_1.logger.warn('No NodeClient was defined, we are exiting the process now.'); + global.process.exit(1); + return; } - return false; + var options = client.getOptions(); + var timeout = (options && options.shutdownTimeout && options.shutdownTimeout > 0 && options.shutdownTimeout) || + DEFAULT_SHUTDOWN_TIMEOUT; + utils_1.forget(client.close(timeout).then(function (result) { + if (!result) { + utils_1.logger.warn('We reached the timeout for emptying the request buffer, still exiting now!'); + } + global.process.exit(1); + })); } -exports.isMatchingPattern = isMatchingPattern; -//# sourceMappingURL=string.js.map +exports.logAndExitProcess = logAndExitProcess; +//# sourceMappingURL=errorhandling.js.map /***/ }), -/***/ 88714: +/***/ 84103: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { Object.defineProperty(exports, "__esModule", ({ value: true })); -var logger_1 = __nccwpck_require__(15577); -var misc_1 = __nccwpck_require__(32154); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var url_1 = __nccwpck_require__(78835); /** - * Tells whether current environment supports ErrorEvent objects - * {@link supportsErrorEvent}. - * - * @returns Answer to the given question. + * Checks whether given url points to Sentry server + * @param url url to verify */ -function supportsErrorEvent() { - try { - new ErrorEvent(''); - return true; - } - catch (e) { - return false; - } +function isSentryRequest(url) { + var _a; + var dsn = (_a = core_1.getCurrentHub() + .getClient()) === null || _a === void 0 ? void 0 : _a.getDsn(); + return dsn ? url.includes(dsn.host) : false; } -exports.supportsErrorEvent = supportsErrorEvent; +exports.isSentryRequest = isSentryRequest; /** - * Tells whether current environment supports DOMError objects - * {@link supportsDOMError}. + * Assemble a URL to be used for breadcrumbs and spans. * - * @returns Answer to the given question. + * @param requestOptions RequestOptions object containing the component parts for a URL + * @returns Fully-formed URL */ -function supportsDOMError() { - try { - // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError': - // 1 argument required, but only 0 present. - // @ts-ignore It really needs 1 argument, not 0. - new DOMError(''); - return true; - } - catch (e) { - return false; - } +function extractUrl(requestOptions) { + var protocol = requestOptions.protocol || ''; + var hostname = requestOptions.hostname || requestOptions.host || ''; + // Don't log standard :80 (http) and :443 (https) ports to reduce the noise + var port = !requestOptions.port || requestOptions.port === 80 || requestOptions.port === 443 ? '' : ":" + requestOptions.port; + var path = requestOptions.path ? requestOptions.path : '/'; + return protocol + "//" + hostname + port + path; } -exports.supportsDOMError = supportsDOMError; +exports.extractUrl = extractUrl; /** - * Tells whether current environment supports DOMException objects - * {@link supportsDOMException}. + * Handle various edge cases in the span description (for spans representing http(s) requests). * - * @returns Answer to the given question. - */ -function supportsDOMException() { - try { - new DOMException(''); - return true; - } - catch (e) { - return false; - } -} -exports.supportsDOMException = supportsDOMException; -/** - * Tells whether current environment supports Fetch API - * {@link supportsFetch}. + * @param description current `description` property of the span representing the request + * @param requestOptions Configuration data for the request + * @param Request Request object * - * @returns Answer to the given question. + * @returns The cleaned description */ -function supportsFetch() { - if (!('fetch' in misc_1.getGlobalObject())) { - return false; +function cleanSpanDescription(description, requestOptions, request) { + var _a, _b, _c; + // nothing to clean + if (!description) { + return description; } - try { - new Headers(); - new Request(''); - new Response(); - return true; + // eslint-disable-next-line prefer-const + var _d = tslib_1.__read(description.split(' '), 2), method = _d[0], requestUrl = _d[1]; + // superagent sticks the protocol in a weird place (we check for host because if both host *and* protocol are missing, + // we're likely dealing with an internal route and this doesn't apply) + if (requestOptions.host && !requestOptions.protocol) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + requestOptions.protocol = (_b = (_a = request) === null || _a === void 0 ? void 0 : _a.agent) === null || _b === void 0 ? void 0 : _b.protocol; // worst comes to worst, this is undefined and nothing changes + requestUrl = extractUrl(requestOptions); } - catch (e) { - return false; + // internal routes can end up starting with a triple slash rather than a single one + if ((_c = requestUrl) === null || _c === void 0 ? void 0 : _c.startsWith('///')) { + requestUrl = requestUrl.slice(2); } + return method + " " + requestUrl; } -exports.supportsFetch = supportsFetch; -/** - * isNativeFetch checks if the given function is a native implementation of fetch() - */ -// eslint-disable-next-line @typescript-eslint/ban-types -function isNativeFetch(func) { - return func && /^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString()); -} +exports.cleanSpanDescription = cleanSpanDescription; /** - * Tells whether current environment supports Fetch API natively - * {@link supportsNativeFetch}. + * Convert a URL object into a RequestOptions object. * - * @returns true if `window.fetch` is natively implemented, false otherwise + * Copied from Node's internals (where it's used in http(s).request() and http(s).get()), modified only to use the + * RequestOptions type above. + * + * See https://github.com/nodejs/node/blob/master/lib/internal/url.js. */ -function supportsNativeFetch() { - if (!supportsFetch()) { - return false; - } - var global = misc_1.getGlobalObject(); - // Fast path to avoid DOM I/O - // eslint-disable-next-line @typescript-eslint/unbound-method - if (isNativeFetch(global.fetch)) { - return true; +function urlToOptions(url) { + var options = { + protocol: url.protocol, + hostname: typeof url.hostname === 'string' && url.hostname.startsWith('[') ? url.hostname.slice(1, -1) : url.hostname, + hash: url.hash, + search: url.search, + pathname: url.pathname, + path: "" + (url.pathname || '') + (url.search || ''), + href: url.href, + }; + if (url.port !== '') { + options.port = Number(url.port); } - // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension) - // so create a "pure" iframe to see if that has native fetch - var result = false; - var doc = global.document; - // eslint-disable-next-line deprecation/deprecation - if (doc && typeof doc.createElement === "function") { - try { - var sandbox = doc.createElement('iframe'); - sandbox.hidden = true; - doc.head.appendChild(sandbox); - if (sandbox.contentWindow && sandbox.contentWindow.fetch) { - // eslint-disable-next-line @typescript-eslint/unbound-method - result = isNativeFetch(sandbox.contentWindow.fetch); - } - doc.head.removeChild(sandbox); - } - catch (err) { - logger_1.logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err); - } + if (url.username || url.password) { + options.auth = url.username + ":" + url.password; } - return result; + return options; } -exports.supportsNativeFetch = supportsNativeFetch; +exports.urlToOptions = urlToOptions; /** - * Tells whether current environment supports ReportingObserver API - * {@link supportsReportingObserver}. + * Normalize inputs to `http(s).request()` and `http(s).get()`. * - * @returns Answer to the given question. - */ -function supportsReportingObserver() { - return 'ReportingObserver' in misc_1.getGlobalObject(); -} -exports.supportsReportingObserver = supportsReportingObserver; -/** - * Tells whether current environment supports Referrer Policy API - * {@link supportsReferrerPolicy}. + * Legal inputs to `http(s).request()` and `http(s).get()` can take one of ten forms: + * [ RequestOptions | string | URL ], + * [ RequestOptions | string | URL, RequestCallback ], + * [ string | URL, RequestOptions ], and + * [ string | URL, RequestOptions, RequestCallback ]. * - * @returns Answer to the given question. - */ -function supportsReferrerPolicy() { - // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default - // https://caniuse.com/#feat=referrer-policy - // It doesn't. And it throw exception instead of ignoring this parameter... - // REF: https://github.com/getsentry/raven-js/issues/1233 - if (!supportsFetch()) { - return false; - } - try { - new Request('_', { - referrerPolicy: 'origin', - }); - return true; - } - catch (e) { - return false; - } -} -exports.supportsReferrerPolicy = supportsReferrerPolicy; -/** - * Tells whether current environment supports History API - * {@link supportsHistory}. + * This standardizes to one of two forms: [ RequestOptions ] and [ RequestOptions, RequestCallback ]. A similar thing is + * done as the first step of `http(s).request()` and `http(s).get()`; this just does it early so that we can interact + * with the args in a standard way. * - * @returns Answer to the given question. - */ -function supportsHistory() { - // NOTE: in Chrome App environment, touching history.pushState, *even inside - // a try/catch block*, will cause Chrome to output an error to console.error - // borrowed from: https://github.com/angular/angular.js/pull/13945/files - var global = misc_1.getGlobalObject(); - /* eslint-disable @typescript-eslint/no-unsafe-member-access */ - // eslint-disable-next-line @typescript-eslint/no-explicit-any - var chrome = global.chrome; - var isChromePackagedApp = chrome && chrome.app && chrome.app.runtime; - /* eslint-enable @typescript-eslint/no-unsafe-member-access */ - var hasHistoryApi = 'history' in global && !!global.history.pushState && !!global.history.replaceState; - return !isChromePackagedApp && hasHistoryApi; -} -exports.supportsHistory = supportsHistory; -//# sourceMappingURL=supports.js.map - -/***/ }), - -/***/ 87833: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -Object.defineProperty(exports, "__esModule", ({ value: true })); -/* eslint-disable @typescript-eslint/explicit-function-return-type */ -/* eslint-disable @typescript-eslint/typedef */ -/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ -/* eslint-disable @typescript-eslint/no-explicit-any */ -var is_1 = __nccwpck_require__(92757); -/** SyncPromise internal states */ -var States; -(function (States) { - /** Pending */ - States["PENDING"] = "PENDING"; - /** Resolved / OK */ - States["RESOLVED"] = "RESOLVED"; - /** Rejected / Error */ - States["REJECTED"] = "REJECTED"; -})(States || (States = {})); -/** - * Thenable class that behaves like a Promise and follows it's interface - * but is not async internally + * @param requestArgs The inputs to `http(s).request()` or `http(s).get()`, as an array. + * + * @returns Equivalent args of the form [ RequestOptions ] or [ RequestOptions, RequestCallback ]. */ -var SyncPromise = /** @class */ (function () { - function SyncPromise(executor) { - var _this = this; - this._state = States.PENDING; - this._handlers = []; - /** JSDoc */ - this._resolve = function (value) { - _this._setResult(States.RESOLVED, value); - }; - /** JSDoc */ - this._reject = function (reason) { - _this._setResult(States.REJECTED, reason); - }; - /** JSDoc */ - this._setResult = function (state, value) { - if (_this._state !== States.PENDING) { - return; - } - if (is_1.isThenable(value)) { - value.then(_this._resolve, _this._reject); - return; - } - _this._state = state; - _this._value = value; - _this._executeHandlers(); - }; - // TODO: FIXME - /** JSDoc */ - this._attachHandler = function (handler) { - _this._handlers = _this._handlers.concat(handler); - _this._executeHandlers(); - }; - /** JSDoc */ - this._executeHandlers = function () { - if (_this._state === States.PENDING) { - return; - } - var cachedHandlers = _this._handlers.slice(); - _this._handlers = []; - cachedHandlers.forEach(function (handler) { - if (handler.done) { - return; - } - if (_this._state === States.RESOLVED) { - if (handler.onfulfilled) { - // eslint-disable-next-line @typescript-eslint/no-floating-promises - handler.onfulfilled(_this._value); - } - } - if (_this._state === States.REJECTED) { - if (handler.onrejected) { - handler.onrejected(_this._value); - } - } - handler.done = true; - }); - }; - try { - executor(this._resolve, this._reject); - } - catch (e) { - this._reject(e); - } - } - /** JSDoc */ - SyncPromise.resolve = function (value) { - return new SyncPromise(function (resolve) { - resolve(value); - }); - }; - /** JSDoc */ - SyncPromise.reject = function (reason) { - return new SyncPromise(function (_, reject) { - reject(reason); - }); - }; - /** JSDoc */ - SyncPromise.all = function (collection) { - return new SyncPromise(function (resolve, reject) { - if (!Array.isArray(collection)) { - reject(new TypeError("Promise.all requires an array as input.")); - return; - } - if (collection.length === 0) { - resolve([]); - return; - } - var counter = collection.length; - var resolvedCollection = []; - collection.forEach(function (item, index) { - SyncPromise.resolve(item) - .then(function (value) { - resolvedCollection[index] = value; - counter -= 1; - if (counter !== 0) { - return; - } - resolve(resolvedCollection); - }) - .then(null, reject); - }); - }); - }; - /** JSDoc */ - SyncPromise.prototype.then = function (onfulfilled, onrejected) { - var _this = this; - return new SyncPromise(function (resolve, reject) { - _this._attachHandler({ - done: false, - onfulfilled: function (result) { - if (!onfulfilled) { - // TODO: ¯\_(ツ)_/¯ - // TODO: FIXME - resolve(result); - return; - } - try { - resolve(onfulfilled(result)); - return; - } - catch (e) { - reject(e); - return; - } - }, - onrejected: function (reason) { - if (!onrejected) { - reject(reason); - return; - } - try { - resolve(onrejected(reason)); - return; - } - catch (e) { - reject(e); - return; - } - }, - }); - }); - }; - /** JSDoc */ - SyncPromise.prototype.catch = function (onrejected) { - return this.then(function (val) { return val; }, onrejected); - }; - /** JSDoc */ - SyncPromise.prototype.finally = function (onfinally) { - var _this = this; - return new SyncPromise(function (resolve, reject) { - var val; - var isRejected; - return _this.then(function (value) { - isRejected = false; - val = value; - if (onfinally) { - onfinally(); - } - }, function (reason) { - isRejected = true; - val = reason; - if (onfinally) { - onfinally(); - } - }).then(function () { - if (isRejected) { - reject(val); - return; - } - resolve(val); - }); - }); - }; - /** JSDoc */ - SyncPromise.prototype.toString = function () { - return '[object SyncPromise]'; - }; - return SyncPromise; -}()); -exports.SyncPromise = SyncPromise; -//# sourceMappingURL=syncpromise.js.map +function normalizeRequestArgs(requestArgs) { + var callback, requestOptions; + // pop off the callback, if there is one + if (typeof requestArgs[requestArgs.length - 1] === 'function') { + callback = requestArgs.pop(); + } + // create a RequestOptions object of whatever's at index 0 + if (typeof requestArgs[0] === 'string') { + requestOptions = urlToOptions(new url_1.URL(requestArgs[0])); + } + else if (requestArgs[0] instanceof url_1.URL) { + requestOptions = urlToOptions(requestArgs[0]); + } + else { + requestOptions = requestArgs[0]; + } + // if the options were given separately from the URL, fold them in + if (requestArgs.length === 2) { + requestOptions = tslib_1.__assign(tslib_1.__assign({}, requestOptions), requestArgs[1]); + } + // return args in standardized form + if (callback) { + return [requestOptions, callback]; + } + else { + return [requestOptions]; + } +} +exports.normalizeRequestArgs = normalizeRequestArgs; +//# sourceMappingURL=http.js.map /***/ }), -/***/ 1735: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 19090: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/* module decorator */ module = __nccwpck_require__.nmd(module); Object.defineProperty(exports, "__esModule", ({ value: true })); -var misc_1 = __nccwpck_require__(32154); -var node_1 = __nccwpck_require__(16411); +var utils_1 = __nccwpck_require__(1620); +var fs_1 = __nccwpck_require__(35747); +var lru_map_1 = __nccwpck_require__(18424); +var stacktrace = __nccwpck_require__(46276); +var DEFAULT_LINES_OF_CONTEXT = 7; +var FILE_CONTENT_CACHE = new lru_map_1.LRUMap(100); /** - * A TimestampSource implementation for environments that do not support the Performance Web API natively. - * - * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier - * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It - * is more obvious to explain "why does my span have negative duration" than "why my spans have zero duration". + * Resets the file cache. Exists for testing purposes. + * @hidden */ -var dateTimestampSource = { - nowSeconds: function () { return Date.now() / 1000; }, -}; +function resetFileContentCache() { + FILE_CONTENT_CACHE.clear(); +} +exports.resetFileContentCache = resetFileContentCache; +/** JSDoc */ +function getFunction(frame) { + try { + return frame.functionName || frame.typeName + "." + (frame.methodName || ''); + } + catch (e) { + // This seems to happen sometimes when using 'use strict', + // stemming from `getTypeName`. + // [TypeError: Cannot read property 'constructor' of undefined] + return ''; + } +} +var mainModule = ((require.main && require.main.filename && utils_1.dirname(require.main.filename)) || + global.process.cwd()) + "/"; +/** JSDoc */ +function getModule(filename, base) { + if (!base) { + // eslint-disable-next-line no-param-reassign + base = mainModule; + } + // It's specifically a module + var file = utils_1.basename(filename, '.js'); + // eslint-disable-next-line no-param-reassign + filename = utils_1.dirname(filename); + var n = filename.lastIndexOf('/node_modules/'); + if (n > -1) { + // /node_modules/ is 14 chars + return filename.substr(n + 14).replace(/\//g, '.') + ":" + file; + } + // Let's see if it's a part of the main module + // To be a part of main module, it has to share the same base + n = (filename + "/").lastIndexOf(base, 0); + if (n === 0) { + var moduleName = filename.substr(base.length).replace(/\//g, '.'); + if (moduleName) { + moduleName += ':'; + } + moduleName += file; + return moduleName; + } + return file; +} /** - * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not - * support the API. + * This function reads file contents and caches them in a global LRU cache. + * Returns a Promise filepath => content array for all files that we were able to read. * - * Wrapping the native API works around differences in behavior from different browsers. + * @param filenames Array of filepaths to read content from. */ -function getBrowserPerformance() { - var performance = misc_1.getGlobalObject().performance; - if (!performance || !performance.now) { - return undefined; +function readSourceFiles(filenames) { + // we're relying on filenames being de-duped already + if (filenames.length === 0) { + return utils_1.SyncPromise.resolve({}); } - // Replace performance.timeOrigin with our own timeOrigin based on Date.now(). - // - // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin + - // performance.now() gives a date arbitrarily in the past. - // - // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is - // undefined. - // - // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to - // interact with data coming out of performance entries. - // - // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that - // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes - // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have - // observed skews that can be as long as days, weeks or months. - // - // See https://github.com/getsentry/sentry-javascript/issues/2590. - // - // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload - // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation - // transactions of long-lived web pages. - var timeOrigin = Date.now() - performance.now(); - return { - now: function () { return performance.now(); }, - timeOrigin: timeOrigin, - }; + return new utils_1.SyncPromise(function (resolve) { + var sourceFiles = {}; + var count = 0; + var _loop_1 = function (i) { + var filename = filenames[i]; + var cache = FILE_CONTENT_CACHE.get(filename); + // We have a cache hit + if (cache !== undefined) { + // If it's not null (which means we found a file and have a content) + // we set the content and return it later. + if (cache !== null) { + sourceFiles[filename] = cache; + } + // eslint-disable-next-line no-plusplus + count++; + // In any case we want to skip here then since we have a content already or we couldn't + // read the file and don't want to try again. + if (count === filenames.length) { + resolve(sourceFiles); + } + return "continue"; + } + fs_1.readFile(filename, function (err, data) { + var content = err ? null : data.toString(); + sourceFiles[filename] = content; + // We always want to set the cache, even to null which means there was an error reading the file. + // We do not want to try to read the file again. + FILE_CONTENT_CACHE.set(filename, content); + // eslint-disable-next-line no-plusplus + count++; + if (count === filenames.length) { + resolve(sourceFiles); + } + }); + }; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (var i = 0; i < filenames.length; i++) { + _loop_1(i); + } + }); } /** - * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't - * implement the API. + * @hidden */ -function getNodePerformance() { +function extractStackFromError(error) { + var stack = stacktrace.parse(error); + if (!stack) { + return []; + } + return stack; +} +exports.extractStackFromError = extractStackFromError; +/** + * @hidden + */ +function parseStack(stack, options) { + var filesToRead = []; + var linesOfContext = options && options.frameContextLines !== undefined ? options.frameContextLines : DEFAULT_LINES_OF_CONTEXT; + var frames = stack.map(function (frame) { + var _a; + var parsedFrame = { + colno: frame.columnNumber, + filename: ((_a = frame.fileName) === null || _a === void 0 ? void 0 : _a.startsWith('file://')) ? frame.fileName.substr(7) : frame.fileName || '', + function: getFunction(frame), + lineno: frame.lineNumber, + }; + var isInternal = frame.native || + (parsedFrame.filename && + !parsedFrame.filename.startsWith('/') && + !parsedFrame.filename.startsWith('.') && + parsedFrame.filename.indexOf(':\\') !== 1); + // in_app is all that's not an internal Node function or a module within node_modules + // note that isNative appears to return true even for node core libraries + // see https://github.com/getsentry/raven-node/issues/176 + parsedFrame.in_app = + !isInternal && parsedFrame.filename !== undefined && parsedFrame.filename.indexOf('node_modules/') === -1; + // Extract a module name based on the filename + if (parsedFrame.filename) { + parsedFrame.module = getModule(parsedFrame.filename); + if (!isInternal && linesOfContext > 0 && filesToRead.indexOf(parsedFrame.filename) === -1) { + filesToRead.push(parsedFrame.filename); + } + } + return parsedFrame; + }); + // We do an early return if we do not want to fetch context liens + if (linesOfContext <= 0) { + return utils_1.SyncPromise.resolve(frames); + } try { - var perfHooks = node_1.dynamicRequire(module, 'perf_hooks'); - return perfHooks.performance; + return addPrePostContext(filesToRead, frames, linesOfContext); } catch (_) { - return undefined; + // This happens in electron for example where we are not able to read files from asar. + // So it's fine, we recover be just returning all frames without pre/post context. + return utils_1.SyncPromise.resolve(frames); } } +exports.parseStack = parseStack; /** - * The Performance API implementation for the current platform, if available. - */ -var platformPerformance = node_1.isNodeEnv() ? getNodePerformance() : getBrowserPerformance(); -var timestampSource = platformPerformance === undefined - ? dateTimestampSource - : { - nowSeconds: function () { return (platformPerformance.timeOrigin + platformPerformance.now()) / 1000; }, - }; -/** - * Returns a timestamp in seconds since the UNIX epoch using the Date API. + * This function tries to read the source files + adding pre and post context (source code) + * to a frame. + * @param filesToRead string[] of filepaths + * @param frames StackFrame[] containg all frames */ -exports.dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource); +function addPrePostContext(filesToRead, frames, linesOfContext) { + return new utils_1.SyncPromise(function (resolve) { + return readSourceFiles(filesToRead).then(function (sourceFiles) { + var result = frames.map(function (frame) { + if (frame.filename && sourceFiles[frame.filename]) { + try { + var lines = sourceFiles[frame.filename].split('\n'); + utils_1.addContextToFrame(lines, frame, linesOfContext); + } + catch (e) { + // anomaly, being defensive in case + // unlikely to ever happen in practice but can definitely happen in theory + } + } + return frame; + }); + resolve(result); + }); + }); +} /** - * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the - * availability of the Performance API. - * - * See `usingPerformanceAPI` to test whether the Performance API is used. - * - * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is - * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The - * skew can grow to arbitrary amounts like days, weeks or months. - * See https://github.com/getsentry/sentry-javascript/issues/2590. + * @hidden */ -exports.timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource); -// Re-exported with an old name for backwards-compatibility. -exports.timestampWithMs = exports.timestampInSeconds; +function getExceptionFromError(error, options) { + var name = error.name || error.constructor.name; + var stack = extractStackFromError(error); + return new utils_1.SyncPromise(function (resolve) { + return parseStack(stack, options).then(function (frames) { + var result = { + stacktrace: { + frames: prepareFramesForEvent(frames), + }, + type: name, + value: error.message, + }; + resolve(result); + }); + }); +} +exports.getExceptionFromError = getExceptionFromError; /** - * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps. + * @hidden */ -exports.usingPerformanceAPI = platformPerformance !== undefined; +function parseError(error, options) { + return new utils_1.SyncPromise(function (resolve) { + return getExceptionFromError(error, options).then(function (exception) { + resolve({ + exception: { + values: [exception], + }, + }); + }); + }); +} +exports.parseError = parseError; /** - * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the - * performance API is available. + * @hidden */ -exports.browserPerformanceTimeOrigin = (function () { - var performance = misc_1.getGlobalObject().performance; - if (!performance) { - return undefined; +function prepareFramesForEvent(stack) { + if (!stack || !stack.length) { + return []; } - if (performance.timeOrigin) { - return performance.timeOrigin; + var localStack = stack; + var firstFrameFunction = localStack[0].function || ''; + if (firstFrameFunction.indexOf('captureMessage') !== -1 || firstFrameFunction.indexOf('captureException') !== -1) { + localStack = localStack.slice(1); } - // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin - // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing. - // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always - // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the - // Date API. - // eslint-disable-next-line deprecation/deprecation - return (performance.timing && performance.timing.navigationStart) || Date.now(); -})(); -//# sourceMappingURL=time.js.map + // The frame where the crash happened, should be the last entry in the array + return localStack.reverse(); +} +exports.prepareFramesForEvent = prepareFramesForEvent; +//# sourceMappingURL=parsers.js.map /***/ }), -/***/ 83633: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * accepts - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - * @private - */ - -var Negotiator = __nccwpck_require__(95385) -var mime = __nccwpck_require__(66918) - -/** - * Module exports. - * @public - */ - -module.exports = Accepts +/***/ 38836: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var hub_1 = __nccwpck_require__(6393); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var domain = __nccwpck_require__(85229); +var client_1 = __nccwpck_require__(86147); +var integrations_1 = __nccwpck_require__(72310); +exports.defaultIntegrations = [ + // Common + new core_1.Integrations.InboundFilters(), + new core_1.Integrations.FunctionToString(), + // Native Wrappers + new integrations_1.Console(), + new integrations_1.Http(), + // Global Handlers + new integrations_1.OnUncaughtException(), + new integrations_1.OnUnhandledRejection(), + // Misc + new integrations_1.LinkedErrors(), +]; /** - * Create a new Accepts object for the given req. + * The Sentry Node SDK Client. * - * @param {object} req - * @public - */ - -function Accepts (req) { - if (!(this instanceof Accepts)) { - return new Accepts(req) - } - - this.headers = req.headers - this.negotiator = new Negotiator(req) -} - -/** - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". + * To use this SDK, call the {@link init} function as early as possible in the + * main entry module. To set context information or send manual events, use the + * provided methods. * - * The `type` value may be a single mime type string - * such as "application/json", the extension name - * such as "json" or an array `["json", "html", "text/plain"]`. When a list - * or array is given the _best_ match, if any is returned. + * @example + * ``` * - * Examples: + * const { init } = require('@sentry/node'); * - * // Accept: text/html - * this.types('html'); - * // => "html" + * init({ + * dsn: '__DSN__', + * // ... + * }); + * ``` * - * // Accept: text/*, application/json - * this.types('html'); - * // => "html" - * this.types('text/html'); - * // => "text/html" - * this.types('json', 'text'); - * // => "json" - * this.types('application/json'); - * // => "application/json" + * @example + * ``` * - * // Accept: text/*, application/json - * this.types('image/png'); - * this.types('png'); - * // => undefined + * const { configureScope } = require('@sentry/node'); + * configureScope((scope: Scope) => { + * scope.setExtra({ battery: 0.7 }); + * scope.setTag({ user_mode: 'admin' }); + * scope.setUser({ id: '4711' }); + * }); + * ``` * - * // Accept: text/*;q=.5, application/json - * this.types(['html', 'json']); - * this.types('html', 'json'); - * // => "json" + * @example + * ``` * - * @param {String|Array} types... - * @return {String|Array|Boolean} - * @public + * const { addBreadcrumb } = require('@sentry/node'); + * addBreadcrumb({ + * message: 'My Breadcrumb', + * // ... + * }); + * ``` + * + * @example + * ``` + * + * const Sentry = require('@sentry/node'); + * Sentry.captureMessage('Hello, world!'); + * Sentry.captureException(new Error('Good bye')); + * Sentry.captureEvent({ + * message: 'Manual', + * stacktrace: [ + * // ... + * ], + * }); + * ``` + * + * @see {@link NodeOptions} for documentation on configuration options. */ - -Accepts.prototype.type = -Accepts.prototype.types = function (types_) { - var types = types_ - - // support flattened arguments - if (types && !Array.isArray(types)) { - types = new Array(arguments.length) - for (var i = 0; i < types.length; i++) { - types[i] = arguments[i] +function init(options) { + if (options === void 0) { options = {}; } + var _a; + var carrier = hub_1.getMainCarrier(); + var autoloadedIntegrations = ((_a = carrier.__SENTRY__) === null || _a === void 0 ? void 0 : _a.integrations) || []; + options.defaultIntegrations = + options.defaultIntegrations === false + ? [] + : tslib_1.__spread((Array.isArray(options.defaultIntegrations) ? options.defaultIntegrations : exports.defaultIntegrations), autoloadedIntegrations); + if (options.dsn === undefined && process.env.SENTRY_DSN) { + options.dsn = process.env.SENTRY_DSN; + } + if (options.tracesSampleRate === undefined && process.env.SENTRY_TRACES_SAMPLE_RATE) { + var tracesSampleRate = parseFloat(process.env.SENTRY_TRACES_SAMPLE_RATE); + if (isFinite(tracesSampleRate)) { + options.tracesSampleRate = tracesSampleRate; + } + } + if (options.release === undefined) { + var detectedRelease = getSentryRelease(); + if (detectedRelease !== undefined) { + options.release = detectedRelease; + } + else { + // If release is not provided, then we should disable autoSessionTracking + options.autoSessionTracking = false; + } + } + if (options.environment === undefined && process.env.SENTRY_ENVIRONMENT) { + options.environment = process.env.SENTRY_ENVIRONMENT; + } + if (options.autoSessionTracking === undefined) { + options.autoSessionTracking = true; + } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, @typescript-eslint/no-explicit-any + if (domain.active) { + hub_1.setHubOnCarrier(carrier, core_1.getCurrentHub()); + } + core_1.initAndBind(client_1.NodeClient, options); + if (options.autoSessionTracking) { + startSessionTracking(); } - } - - // no types, return all requested types - if (!types || types.length === 0) { - return this.negotiator.mediaTypes() - } - - // no accept header, return first given type - if (!this.headers.accept) { - return types[0] - } - - var mimes = types.map(extToMime) - var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) - var first = accepts[0] - - return first - ? types[mimes.indexOf(first)] - : false } - +exports.init = init; /** - * Return accepted encodings or best fit based on `encodings`. - * - * Given `Accept-Encoding: gzip, deflate` - * an array sorted by quality is returned: - * - * ['gzip', 'deflate'] + * This is the getter for lastEventId. * - * @param {String|Array} encodings... - * @return {String|Array} - * @public + * @returns The last event id of a captured event. */ - -Accepts.prototype.encoding = -Accepts.prototype.encodings = function (encodings_) { - var encodings = encodings_ - - // support flattened arguments - if (encodings && !Array.isArray(encodings)) { - encodings = new Array(arguments.length) - for (var i = 0; i < encodings.length; i++) { - encodings[i] = arguments[i] - } - } - - // no encodings, return all requested encodings - if (!encodings || encodings.length === 0) { - return this.negotiator.encodings() - } - - return this.negotiator.encodings(encodings)[0] || false +function lastEventId() { + return core_1.getCurrentHub().lastEventId(); } - +exports.lastEventId = lastEventId; /** - * Return accepted charsets or best fit based on `charsets`. - * - * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` - * an array sorted by quality is returned: + * Call `flush()` on the current client, if there is one. See {@link Client.flush}. * - * ['utf-8', 'utf-7', 'iso-8859-1'] - * - * @param {String|Array} charsets... - * @return {String|Array} - * @public + * @param timeout Maximum time in ms the client should wait to flush its event queue. Omitting this parameter will cause + * the client to wait until all events are sent before resolving the promise. + * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it + * doesn't (or if there's no client defined). */ - -Accepts.prototype.charset = -Accepts.prototype.charsets = function (charsets_) { - var charsets = charsets_ - - // support flattened arguments - if (charsets && !Array.isArray(charsets)) { - charsets = new Array(arguments.length) - for (var i = 0; i < charsets.length; i++) { - charsets[i] = arguments[i] - } - } - - // no charsets, return all requested charsets - if (!charsets || charsets.length === 0) { - return this.negotiator.charsets() - } - - return this.negotiator.charsets(charsets)[0] || false +function flush(timeout) { + return tslib_1.__awaiter(this, void 0, void 0, function () { + var client; + return tslib_1.__generator(this, function (_a) { + client = core_1.getCurrentHub().getClient(); + if (client) { + return [2 /*return*/, client.flush(timeout)]; + } + utils_1.logger.warn('Cannot flush events. No client defined.'); + return [2 /*return*/, Promise.resolve(false)]; + }); + }); } - +exports.flush = flush; /** - * Return accepted languages or best fit based on `langs`. - * - * Given `Accept-Language: en;q=0.8, es, pt` - * an array sorted by quality is returned: + * Call `close()` on the current client, if there is one. See {@link Client.close}. * - * ['es', 'pt', 'en'] - * - * @param {String|Array} langs... - * @return {Array|String} - * @public + * @param timeout Maximum time in ms the client should wait to flush its event queue before shutting down. Omitting this + * parameter will cause the client to wait until all events are sent before disabling itself. + * @returns A promise which resolves to `true` if the queue successfully drains before the timeout, or `false` if it + * doesn't (or if there's no client defined). */ - -Accepts.prototype.lang = -Accepts.prototype.langs = -Accepts.prototype.language = -Accepts.prototype.languages = function (languages_) { - var languages = languages_ - - // support flattened arguments - if (languages && !Array.isArray(languages)) { - languages = new Array(arguments.length) - for (var i = 0; i < languages.length; i++) { - languages[i] = arguments[i] - } - } - - // no languages, return all requested languages - if (!languages || languages.length === 0) { - return this.negotiator.languages() - } - - return this.negotiator.languages(languages)[0] || false +function close(timeout) { + return tslib_1.__awaiter(this, void 0, void 0, function () { + var client; + return tslib_1.__generator(this, function (_a) { + client = core_1.getCurrentHub().getClient(); + if (client) { + return [2 /*return*/, client.close(timeout)]; + } + utils_1.logger.warn('Cannot flush events and disable SDK. No client defined.'); + return [2 /*return*/, Promise.resolve(false)]; + }); + }); } - +exports.close = close; /** - * Convert extnames to mime. - * - * @param {String} type - * @return {String} - * @private + * Function that takes an instance of NodeClient and checks if autoSessionTracking option is enabled for that client */ - -function extToMime (type) { - return type.indexOf('/') === -1 - ? mime.lookup(type) - : type +function isAutoSessionTrackingEnabled(client) { + if (client === undefined) { + return false; + } + var clientOptions = client && client.getOptions(); + if (clientOptions && clientOptions.autoSessionTracking !== undefined) { + return clientOptions.autoSessionTracking; + } + return false; } - +exports.isAutoSessionTrackingEnabled = isAutoSessionTrackingEnabled; /** - * Check if mime is valid. - * - * @param {String} type - * @return {String} - * @private + * Returns a release dynamically from environment variables. */ - -function validMime (type) { - return typeof type === 'string' +function getSentryRelease(fallback) { + // Always read first as Sentry takes this as precedence + if (process.env.SENTRY_RELEASE) { + return process.env.SENTRY_RELEASE; + } + // This supports the variable that sentry-webpack-plugin injects + var global = utils_1.getGlobalObject(); + if (global.SENTRY_RELEASE && global.SENTRY_RELEASE.id) { + return global.SENTRY_RELEASE.id; + } + return ( + // GitHub Actions - https://help.github.com/en/actions/configuring-and-managing-workflows/using-environment-variables#default-environment-variables + process.env.GITHUB_SHA || + // Netlify - https://docs.netlify.com/configure-builds/environment-variables/#build-metadata + process.env.COMMIT_REF || + // Vercel - https://vercel.com/docs/v2/build-step#system-environment-variables + process.env.VERCEL_GIT_COMMIT_SHA || + process.env.VERCEL_GITHUB_COMMIT_SHA || + process.env.VERCEL_GITLAB_COMMIT_SHA || + process.env.VERCEL_BITBUCKET_COMMIT_SHA || + // Zeit (now known as Vercel) + process.env.ZEIT_GITHUB_COMMIT_SHA || + process.env.ZEIT_GITLAB_COMMIT_SHA || + process.env.ZEIT_BITBUCKET_COMMIT_SHA || + fallback); +} +exports.getSentryRelease = getSentryRelease; +/** + * Enable automatic Session Tracking for the node process. + */ +function startSessionTracking() { + var hub = core_1.getCurrentHub(); + hub.startSession(); + // Emitted in the case of healthy sessions, error of `mechanism.handled: true` and unhandledrejections because + // The 'beforeExit' event is not emitted for conditions causing explicit termination, + // such as calling process.exit() or uncaught exceptions. + // Ref: https://nodejs.org/api/process.html#process_event_beforeexit + process.on('beforeExit', function () { + var _a; + var session = (_a = hub.getScope()) === null || _a === void 0 ? void 0 : _a.getSession(); + var terminalStates = [types_1.SessionStatus.Exited, types_1.SessionStatus.Crashed]; + // Only call endSession, if the Session exists on Scope and SessionStatus is not a + // Terminal Status i.e. Exited or Crashed because + // "When a session is moved away from ok it must not be updated anymore." + // Ref: https://develop.sentry.dev/sdk/sessions/ + if (session && !terminalStates.includes(session.status)) + hub.endSession(); + }); } - +//# sourceMappingURL=sdk.js.map /***/ }), -/***/ 2122: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/*! - * mime-db - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed - */ +/***/ 46276: +/***/ ((__unused_webpack_module, exports) => { /** - * Module exports. + * stack-trace - Parses node.js stack traces + * + * This was originally forked to fix this issue: + * https://github.com/felixge/node-stack-trace/issues/31 + * + * Mar 19,2019 - #4fd379e + * + * https://github.com/felixge/node-stack-trace/ + * @license MIT */ - -module.exports = __nccwpck_require__(12016) - +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** Extracts StackFrames from the Error */ +function parse(err) { + if (!err.stack) { + return []; + } + var lines = err.stack.split('\n').slice(1); + return lines + .map(function (line) { + if (line.match(/^\s*[-]{4,}$/)) { + return { + columnNumber: null, + fileName: line, + functionName: null, + lineNumber: null, + methodName: null, + native: null, + typeName: null, + }; + } + var lineMatch = line.match(/at (?:(.+?)\s+\()?(?:(.+?):(\d+)(?::(\d+))?|([^)]+))\)?/); + if (!lineMatch) { + return undefined; + } + var object = null; + var method = null; + var functionName = null; + var typeName = null; + var methodName = null; + var isNative = lineMatch[5] === 'native'; + if (lineMatch[1]) { + functionName = lineMatch[1]; + var methodStart = functionName.lastIndexOf('.'); + if (functionName[methodStart - 1] === '.') { + // eslint-disable-next-line no-plusplus + methodStart--; + } + if (methodStart > 0) { + object = functionName.substr(0, methodStart); + method = functionName.substr(methodStart + 1); + var objectEnd = object.indexOf('.Module'); + if (objectEnd > 0) { + functionName = functionName.substr(objectEnd + 1); + object = object.substr(0, objectEnd); + } + } + typeName = null; + } + if (method) { + typeName = object; + methodName = method; + } + if (method === '') { + methodName = null; + functionName = null; + } + var properties = { + columnNumber: parseInt(lineMatch[4], 10) || null, + fileName: lineMatch[2] || null, + functionName: functionName, + lineNumber: parseInt(lineMatch[3], 10) || null, + methodName: methodName, + native: isNative, + typeName: typeName, + }; + return properties; + }) + .filter(function (callSite) { return !!callSite; }); +} +exports.parse = parse; +//# sourceMappingURL=stacktrace.js.map /***/ }), -/***/ 66918: +/***/ 41194: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; -/*! - * mime-types - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - * @private - */ - -var db = __nccwpck_require__(2122) -var extname = __nccwpck_require__(85622).extname - -/** - * Module variables. - * @private - */ - -var EXTRACT_TYPE_REGEXP = /^\s*([^;\s]*)(?:;|\s|$)/ -var TEXT_TYPE_REGEXP = /^text\//i - -/** - * Module exports. - * @public - */ - -exports.charset = charset -exports.charsets = { lookup: charset } -exports.contentType = contentType -exports.extension = extension -exports.extensions = Object.create(null) -exports.lookup = lookup -exports.types = Object.create(null) - -// Populate the extensions/types maps -populateMaps(exports.extensions, exports.types) - -/** - * Get the default charset for a MIME type. - * - * @param {string} type - * @return {boolean|string} - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var fs = __nccwpck_require__(35747); +var url_1 = __nccwpck_require__(78835); +var version_1 = __nccwpck_require__(31271); +var CATEGORY_MAPPING = { + event: 'error', + transaction: 'transaction', + session: 'session', + attachment: 'attachment', +}; +/** Base Transport class implementation */ +var BaseTransport = /** @class */ (function () { + /** Create instance and set this.dsn */ + function BaseTransport(options) { + this.options = options; + /** A simple buffer holding all requests. */ + this._buffer = new utils_1.PromiseBuffer(30); + /** Locks transport after receiving rate limits in a response */ + this._rateLimits = {}; + /** Default function used to parse URLs */ + this.urlParser = function (url) { return new url_1.URL(url); }; + this._api = new core_1.API(options.dsn, options._metadata, options.tunnel); + } + /** + * @inheritDoc + */ + BaseTransport.prototype.sendEvent = function (_) { + throw new utils_1.SentryError('Transport Class has to implement `sendEvent` method.'); + }; + /** + * @inheritDoc + */ + BaseTransport.prototype.close = function (timeout) { + return this._buffer.drain(timeout); + }; + /** + * Extracts proxy settings from client options and env variables. + * + * Honors `no_proxy` env variable with the highest priority to allow for hosts exclusion. + * + * An order of priority for available protocols is: + * `http` => `options.httpProxy` | `process.env.http_proxy` + * `https` => `options.httpsProxy` | `options.httpProxy` | `process.env.https_proxy` | `process.env.http_proxy` + */ + BaseTransport.prototype._getProxy = function (protocol) { + var e_1, _a; + var _b = process.env, no_proxy = _b.no_proxy, http_proxy = _b.http_proxy, https_proxy = _b.https_proxy; + var _c = this.options, httpProxy = _c.httpProxy, httpsProxy = _c.httpsProxy; + var proxy = protocol === 'http' ? httpProxy || http_proxy : httpsProxy || httpProxy || https_proxy || http_proxy; + if (!no_proxy) { + return proxy; + } + var _d = this._api.getDsn(), host = _d.host, port = _d.port; + try { + for (var _e = tslib_1.__values(no_proxy.split(',')), _f = _e.next(); !_f.done; _f = _e.next()) { + var np = _f.value; + if (host.endsWith(np) || (host + ":" + port).endsWith(np)) { + return; + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_f && !_f.done && (_a = _e.return)) _a.call(_e); + } + finally { if (e_1) throw e_1.error; } + } + return proxy; + }; + /** Returns a build request option object used by request */ + BaseTransport.prototype._getRequestOptions = function (urlParts) { + var headers = tslib_1.__assign(tslib_1.__assign({}, this._api.getRequestHeaders(version_1.SDK_NAME, core_1.SDK_VERSION)), this.options.headers); + var hostname = urlParts.hostname, pathname = urlParts.pathname, port = urlParts.port, protocol = urlParts.protocol; + // See https://github.com/nodejs/node/blob/38146e717fed2fabe3aacb6540d839475e0ce1c6/lib/internal/url.js#L1268-L1290 + // We ignore the query string on purpose + var path = "" + pathname; + return tslib_1.__assign({ agent: this.client, headers: headers, + hostname: hostname, method: 'POST', path: path, + port: port, + protocol: protocol }, (this.options.caCerts && { + ca: fs.readFileSync(this.options.caCerts), + })); + }; + /** + * Gets the time that given category is disabled until for rate limiting + */ + BaseTransport.prototype._disabledUntil = function (requestType) { + var category = CATEGORY_MAPPING[requestType]; + return this._rateLimits[category] || this._rateLimits.all; + }; + /** + * Checks if a category is rate limited + */ + BaseTransport.prototype._isRateLimited = function (requestType) { + return this._disabledUntil(requestType) > new Date(Date.now()); + }; + /** + * Sets internal _rateLimits from incoming headers. Returns true if headers contains a non-empty rate limiting header. + */ + BaseTransport.prototype._handleRateLimit = function (headers) { + var e_2, _a, e_3, _b; + var now = Date.now(); + var rlHeader = headers['x-sentry-rate-limits']; + var raHeader = headers['retry-after']; + if (rlHeader) { + try { + // rate limit headers are of the form + //
,
,.. + // where each
is of the form + // : : : + // where + // is a delay in ms + // is the event type(s) (error, transaction, etc) being rate limited and is of the form + // ;;... + // is what's being limited (org, project, or key) - ignored by SDK + // is an arbitrary string like "org_quota" - ignored by SDK + for (var _c = tslib_1.__values(rlHeader.trim().split(',')), _d = _c.next(); !_d.done; _d = _c.next()) { + var limit = _d.value; + var parameters = limit.split(':', 2); + var headerDelay = parseInt(parameters[0], 10); + var delay = (!isNaN(headerDelay) ? headerDelay : 60) * 1000; // 60sec default + try { + for (var _e = (e_3 = void 0, tslib_1.__values((parameters[1] && parameters[1].split(';')) || ['all'])), _f = _e.next(); !_f.done; _f = _e.next()) { + var category = _f.value; + // categoriesAllowed is added here to ensure we are only storing rate limits for categories we support in this + // sdk and any categories that are not supported will not be added redundantly to the rateLimits object + var categoriesAllowed = tslib_1.__spread(Object.keys(CATEGORY_MAPPING).map(function (k) { return CATEGORY_MAPPING[k]; }), [ + 'all', + ]); + if (categoriesAllowed.includes(category)) + this._rateLimits[category] = new Date(now + delay); + } + } + catch (e_3_1) { e_3 = { error: e_3_1 }; } + finally { + try { + if (_f && !_f.done && (_b = _e.return)) _b.call(_e); + } + finally { if (e_3) throw e_3.error; } + } + } + } + catch (e_2_1) { e_2 = { error: e_2_1 }; } + finally { + try { + if (_d && !_d.done && (_a = _c.return)) _a.call(_c); + } + finally { if (e_2) throw e_2.error; } + } + return true; + } + else if (raHeader) { + this._rateLimits.all = new Date(now + utils_1.parseRetryAfterHeader(now, raHeader)); + return true; + } + return false; + }; + /** JSDoc */ + BaseTransport.prototype._send = function (sentryRequest, originalPayload) { + return tslib_1.__awaiter(this, void 0, void 0, function () { + var _this = this; + return tslib_1.__generator(this, function (_a) { + if (!this.module) { + throw new utils_1.SentryError('No module available'); + } + if (originalPayload && this._isRateLimited(sentryRequest.type)) { + return [2 /*return*/, Promise.reject({ + payload: originalPayload, + type: sentryRequest.type, + reason: "Transport for " + sentryRequest.type + " requests locked till " + this._disabledUntil(sentryRequest.type) + " due to too many requests.", + status: 429, + })]; + } + if (!this._buffer.isReady()) { + return [2 /*return*/, Promise.reject(new utils_1.SentryError('Not adding Promise due to buffer limit reached.'))]; + } + return [2 /*return*/, this._buffer.add(function () { + return new Promise(function (resolve, reject) { + if (!_this.module) { + throw new utils_1.SentryError('No module available'); + } + var options = _this._getRequestOptions(_this.urlParser(sentryRequest.url)); + var req = _this.module.request(options, function (res) { + var statusCode = res.statusCode || 500; + var status = types_1.Status.fromHttpCode(statusCode); + res.setEncoding('utf8'); + /** + * "Key-value pairs of header names and values. Header names are lower-cased." + * https://nodejs.org/api/http.html#http_message_headers + */ + var retryAfterHeader = res.headers ? res.headers['retry-after'] : ''; + retryAfterHeader = (Array.isArray(retryAfterHeader) ? retryAfterHeader[0] : retryAfterHeader); + var rlHeader = res.headers ? res.headers['x-sentry-rate-limits'] : ''; + rlHeader = (Array.isArray(rlHeader) ? rlHeader[0] : rlHeader); + var headers = { + 'x-sentry-rate-limits': rlHeader, + 'retry-after': retryAfterHeader, + }; + var limited = _this._handleRateLimit(headers); + if (limited) + utils_1.logger.warn("Too many " + sentryRequest.type + " requests, backing off until: " + _this._disabledUntil(sentryRequest.type)); + if (status === types_1.Status.Success) { + resolve({ status: status }); + } + else { + var rejectionMessage = "HTTP Error (" + statusCode + ")"; + if (res.headers && res.headers['x-sentry-error']) { + rejectionMessage += ": " + res.headers['x-sentry-error']; + } + reject(new utils_1.SentryError(rejectionMessage)); + } + // Force the socket to drain + res.on('data', function () { + // Drain + }); + res.on('end', function () { + // Drain + }); + }); + req.on('error', reject); + req.end(sentryRequest.body); + }); + })]; + }); + }); + }; + return BaseTransport; +}()); +exports.BaseTransport = BaseTransport; +//# sourceMappingURL=index.js.map -function charset (type) { - if (!type || typeof type !== 'string') { - return false - } +/***/ }), - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) - var mime = match && db[match[1].toLowerCase()] +/***/ 84490: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (mime && mime.charset) { - return mime.charset - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var http = __nccwpck_require__(98605); +var base_1 = __nccwpck_require__(41194); +/** Node http module transport */ +var HTTPTransport = /** @class */ (function (_super) { + tslib_1.__extends(HTTPTransport, _super); + /** Create a new instance and set this.agent */ + function HTTPTransport(options) { + var _this = _super.call(this, options) || this; + _this.options = options; + var proxy = _this._getProxy('http'); + _this.module = http; + _this.client = proxy + ? new (__nccwpck_require__(77219))(proxy) + : new http.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 }); + return _this; + } + /** + * @inheritDoc + */ + HTTPTransport.prototype.sendEvent = function (event) { + return this._send(core_1.eventToSentryRequest(event, this._api), event); + }; + /** + * @inheritDoc + */ + HTTPTransport.prototype.sendSession = function (session) { + return this._send(core_1.sessionToSentryRequest(session, this._api), session); + }; + return HTTPTransport; +}(base_1.BaseTransport)); +exports.HTTPTransport = HTTPTransport; +//# sourceMappingURL=http.js.map - // default text/* to utf-8 - if (match && TEXT_TYPE_REGEXP.test(match[1])) { - return 'UTF-8' - } +/***/ }), - return false -} +/***/ 68621: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Create a full Content-Type header given a MIME type or extension. - * - * @param {string} str - * @return {boolean|string} - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var core_1 = __nccwpck_require__(79212); +var https = __nccwpck_require__(57211); +var base_1 = __nccwpck_require__(41194); +/** Node https module transport */ +var HTTPSTransport = /** @class */ (function (_super) { + tslib_1.__extends(HTTPSTransport, _super); + /** Create a new instance and set this.agent */ + function HTTPSTransport(options) { + var _this = _super.call(this, options) || this; + _this.options = options; + var proxy = _this._getProxy('https'); + _this.module = https; + _this.client = proxy + ? new (__nccwpck_require__(77219))(proxy) + : new https.Agent({ keepAlive: false, maxSockets: 30, timeout: 2000 }); + return _this; + } + /** + * @inheritDoc + */ + HTTPSTransport.prototype.sendEvent = function (event) { + return this._send(core_1.eventToSentryRequest(event, this._api), event); + }; + /** + * @inheritDoc + */ + HTTPSTransport.prototype.sendSession = function (session) { + return this._send(core_1.sessionToSentryRequest(session, this._api), session); + }; + return HTTPSTransport; +}(base_1.BaseTransport)); +exports.HTTPSTransport = HTTPSTransport; +//# sourceMappingURL=https.js.map -function contentType (str) { - // TODO: should this even be in this module? - if (!str || typeof str !== 'string') { - return false - } +/***/ }), - var mime = str.indexOf('/') === -1 - ? exports.lookup(str) - : str +/***/ 21437: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!mime) { - return false - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +var base_1 = __nccwpck_require__(41194); +exports.BaseTransport = base_1.BaseTransport; +var http_1 = __nccwpck_require__(84490); +exports.HTTPTransport = http_1.HTTPTransport; +var https_1 = __nccwpck_require__(68621); +exports.HTTPSTransport = https_1.HTTPSTransport; +//# sourceMappingURL=index.js.map - // TODO: use content-type or other module - if (mime.indexOf('charset') === -1) { - var charset = exports.charset(mime) - if (charset) mime += '; charset=' + charset.toLowerCase() - } +/***/ }), - return mime -} +/***/ 27937: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var fs = __nccwpck_require__(35747); +var path = __nccwpck_require__(85622); /** - * Get the default extension for a MIME type. + * Recursively read the contents of a directory. * - * @param {string} type - * @return {boolean|string} + * @param targetDir Absolute or relative path of the directory to scan. All returned paths will be relative to this + * directory. + * @returns Array holding all relative paths */ +function deepReadDirSync(targetDir) { + var targetDirAbsPath = path.resolve(targetDir); + if (!fs.existsSync(targetDirAbsPath)) { + throw new Error("Cannot read contents of " + targetDirAbsPath + ". Directory does not exist."); + } + if (!fs.statSync(targetDirAbsPath).isDirectory()) { + throw new Error("Cannot read contents of " + targetDirAbsPath + ", because it is not a directory."); + } + // This does the same thing as its containing function, `deepReadDirSync` (except that - purely for convenience - it + // deals in absolute paths rather than relative ones). We need this to be separate from the outer function to preserve + // the difference between `targetDirAbsPath` and `currentDirAbsPath`. + var deepReadCurrentDir = function (currentDirAbsPath) { + return fs.readdirSync(currentDirAbsPath).reduce(function (absPaths, itemName) { + var itemAbsPath = path.join(currentDirAbsPath, itemName); + if (fs.statSync(itemAbsPath).isDirectory()) { + return tslib_1.__spread(absPaths, deepReadCurrentDir(itemAbsPath)); + } + return tslib_1.__spread(absPaths, [itemAbsPath]); + }, []); + }; + return deepReadCurrentDir(targetDirAbsPath).map(function (absPath) { return path.relative(targetDirAbsPath, absPath); }); +} +exports.deepReadDirSync = deepReadDirSync; +//# sourceMappingURL=utils.js.map -function extension (type) { - if (!type || typeof type !== 'string') { - return false - } +/***/ }), - // TODO: use media-typer - var match = EXTRACT_TYPE_REGEXP.exec(type) +/***/ 31271: +/***/ ((__unused_webpack_module, exports) => { - // get extensions - var exts = match && exports.extensions[match[1].toLowerCase()] +Object.defineProperty(exports, "__esModule", ({ value: true })); +// TODO: Remove in the next major release and rely only on @sentry/core SDK_VERSION and SdkMetadata +exports.SDK_NAME = 'sentry.javascript.node'; +//# sourceMappingURL=version.js.map - if (!exts || !exts.length) { - return false - } +/***/ }), - return exts[0] +/***/ 81867: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var utils_1 = __nccwpck_require__(1620); +var spanstatus_1 = __nccwpck_require__(58522); +var utils_2 = __nccwpck_require__(31386); +var global = utils_1.getGlobalObject(); +/** + * Add a listener that cancels and finishes a transaction when the global + * document is hidden. + */ +function registerBackgroundTabDetection() { + if (global && global.document) { + global.document.addEventListener('visibilitychange', function () { + var activeTransaction = utils_2.getActiveTransaction(); + if (global.document.hidden && activeTransaction) { + utils_1.logger.log("[Tracing] Transaction: " + spanstatus_1.SpanStatus.Cancelled + " -> since tab moved to the background, op: " + activeTransaction.op); + // We should not set status if it is already set, this prevent important statuses like + // error or data loss from being overwritten on transaction. + if (!activeTransaction.status) { + activeTransaction.setStatus(spanstatus_1.SpanStatus.Cancelled); + } + activeTransaction.setTag('visibilitychange', 'document.hidden'); + activeTransaction.finish(); + } + }); + } + else { + utils_1.logger.warn('[Tracing] Could not set up background tab detection due to lack of global document'); + } } +exports.registerBackgroundTabDetection = registerBackgroundTabDetection; +//# sourceMappingURL=backgroundtab.js.map + +/***/ }), + +/***/ 33577: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var hubextensions_1 = __nccwpck_require__(31409); +var idletransaction_1 = __nccwpck_require__(2171); +var spanstatus_1 = __nccwpck_require__(58522); +var utils_2 = __nccwpck_require__(31386); +var backgroundtab_1 = __nccwpck_require__(81867); +var metrics_1 = __nccwpck_require__(68451); +var request_1 = __nccwpck_require__(27854); +var router_1 = __nccwpck_require__(40348); +exports.DEFAULT_MAX_TRANSACTION_DURATION_SECONDS = 600; +var DEFAULT_BROWSER_TRACING_OPTIONS = tslib_1.__assign({ idleTimeout: idletransaction_1.DEFAULT_IDLE_TIMEOUT, markBackgroundTransactions: true, maxTransactionDuration: exports.DEFAULT_MAX_TRANSACTION_DURATION_SECONDS, routingInstrumentation: router_1.instrumentRoutingWithDefaults, startTransactionOnLocationChange: true, startTransactionOnPageLoad: true }, request_1.defaultRequestInstrumentationOptions); /** - * Lookup the MIME type for a file path/extension. + * The Browser Tracing integration automatically instruments browser pageload/navigation + * actions as transactions, and captures requests, metrics and errors as spans. * - * @param {string} path - * @return {boolean|string} + * The integration can be configured with a variety of options, and can be extended to use + * any routing library. This integration uses {@see IdleTransaction} to create transactions. + */ +var BrowserTracing = /** @class */ (function () { + function BrowserTracing(_options) { + /** + * @inheritDoc + */ + this.name = BrowserTracing.id; + this._metrics = new metrics_1.MetricsInstrumentation(); + this._emitOptionsWarning = false; + var tracingOrigins = request_1.defaultRequestInstrumentationOptions.tracingOrigins; + // NOTE: Logger doesn't work in constructors, as it's initialized after integrations instances + if (_options && + _options.tracingOrigins && + Array.isArray(_options.tracingOrigins) && + _options.tracingOrigins.length !== 0) { + tracingOrigins = _options.tracingOrigins; + } + else { + this._emitOptionsWarning = true; + } + this.options = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, DEFAULT_BROWSER_TRACING_OPTIONS), _options), { tracingOrigins: tracingOrigins }); + } + /** + * @inheritDoc + */ + BrowserTracing.prototype.setupOnce = function (_, getCurrentHub) { + var _this = this; + this._getCurrentHub = getCurrentHub; + if (this._emitOptionsWarning) { + utils_1.logger.warn('[Tracing] You need to define `tracingOrigins` in the options. Set an array of urls or patterns to trace.'); + utils_1.logger.warn("[Tracing] We added a reasonable default for you: " + request_1.defaultRequestInstrumentationOptions.tracingOrigins); + } + // eslint-disable-next-line @typescript-eslint/unbound-method + var _a = this.options, instrumentRouting = _a.routingInstrumentation, startTransactionOnLocationChange = _a.startTransactionOnLocationChange, startTransactionOnPageLoad = _a.startTransactionOnPageLoad, markBackgroundTransactions = _a.markBackgroundTransactions, traceFetch = _a.traceFetch, traceXHR = _a.traceXHR, tracingOrigins = _a.tracingOrigins, shouldCreateSpanForRequest = _a.shouldCreateSpanForRequest; + instrumentRouting(function (context) { return _this._createRouteTransaction(context); }, startTransactionOnPageLoad, startTransactionOnLocationChange); + if (markBackgroundTransactions) { + backgroundtab_1.registerBackgroundTabDetection(); + } + request_1.instrumentOutgoingRequests({ traceFetch: traceFetch, traceXHR: traceXHR, tracingOrigins: tracingOrigins, shouldCreateSpanForRequest: shouldCreateSpanForRequest }); + }; + /** Create routing idle transaction. */ + BrowserTracing.prototype._createRouteTransaction = function (context) { + var _this = this; + if (!this._getCurrentHub) { + utils_1.logger.warn("[Tracing] Did not create " + context.op + " transaction because _getCurrentHub is invalid."); + return undefined; + } + // eslint-disable-next-line @typescript-eslint/unbound-method + var _a = this.options, beforeNavigate = _a.beforeNavigate, idleTimeout = _a.idleTimeout, maxTransactionDuration = _a.maxTransactionDuration; + var parentContextFromHeader = context.op === 'pageload' ? getHeaderContext() : undefined; + var expandedContext = tslib_1.__assign(tslib_1.__assign(tslib_1.__assign({}, context), parentContextFromHeader), { trimEnd: true }); + var modifiedContext = typeof beforeNavigate === 'function' ? beforeNavigate(expandedContext) : expandedContext; + // For backwards compatibility reasons, beforeNavigate can return undefined to "drop" the transaction (prevent it + // from being sent to Sentry). + var finalContext = modifiedContext === undefined ? tslib_1.__assign(tslib_1.__assign({}, expandedContext), { sampled: false }) : modifiedContext; + if (finalContext.sampled === false) { + utils_1.logger.log("[Tracing] Will not send " + finalContext.op + " transaction because of beforeNavigate."); + } + utils_1.logger.log("[Tracing] Starting " + finalContext.op + " transaction on scope"); + var hub = this._getCurrentHub(); + var location = utils_1.getGlobalObject().location; + var idleTransaction = hubextensions_1.startIdleTransaction(hub, finalContext, idleTimeout, true, { location: location }); + idleTransaction.registerBeforeFinishCallback(function (transaction, endTimestamp) { + _this._metrics.addPerformanceEntries(transaction); + adjustTransactionDuration(utils_2.secToMs(maxTransactionDuration), transaction, endTimestamp); + }); + return idleTransaction; + }; + /** + * @inheritDoc + */ + BrowserTracing.id = 'BrowserTracing'; + return BrowserTracing; +}()); +exports.BrowserTracing = BrowserTracing; +/** + * Gets transaction context from a sentry-trace meta. + * + * @returns Transaction context data from the header or undefined if there's no header or the header is malformed */ +function getHeaderContext() { + var header = getMetaContent('sentry-trace'); + if (header) { + return utils_2.extractTraceparentData(header); + } + return undefined; +} +exports.getHeaderContext = getHeaderContext; +/** Returns the value of a meta tag */ +function getMetaContent(metaName) { + var el = document.querySelector("meta[name=" + metaName + "]"); + return el ? el.getAttribute('content') : null; +} +exports.getMetaContent = getMetaContent; +/** Adjusts transaction value based on max transaction duration */ +function adjustTransactionDuration(maxDuration, transaction, endTimestamp) { + var diff = endTimestamp - transaction.startTimestamp; + var isOutdatedTransaction = endTimestamp && (diff > maxDuration || diff < 0); + if (isOutdatedTransaction) { + transaction.setStatus(spanstatus_1.SpanStatus.DeadlineExceeded); + transaction.setTag('maxTransactionDurationExceeded', 'true'); + } +} +//# sourceMappingURL=browsertracing.js.map -function lookup (path) { - if (!path || typeof path !== 'string') { - return false - } +/***/ }), - // get the extension ("ext" or ".ext" or full path) - var extension = extname('x.' + path) - .toLowerCase() - .substr(1) +/***/ 71425: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (!extension) { - return false - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +var browsertracing_1 = __nccwpck_require__(33577); +exports.BrowserTracing = browsertracing_1.BrowserTracing; +var request_1 = __nccwpck_require__(27854); +exports.instrumentOutgoingRequests = request_1.instrumentOutgoingRequests; +exports.defaultRequestInstrumentationOptions = request_1.defaultRequestInstrumentationOptions; +//# sourceMappingURL=index.js.map - return exports.types[extension] || false +/***/ }), + +/***/ 68451: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var utils_2 = __nccwpck_require__(31386); +var getCLS_1 = __nccwpck_require__(56982); +var getFID_1 = __nccwpck_require__(82496); +var getLCP_1 = __nccwpck_require__(99382); +var getVisibilityWatcher_1 = __nccwpck_require__(10522); +var global = utils_1.getGlobalObject(); +/** Class tracking metrics */ +var MetricsInstrumentation = /** @class */ (function () { + function MetricsInstrumentation() { + var _a; + this._measurements = {}; + this._performanceCursor = 0; + if (!utils_1.isNodeEnv() && ((_a = global) === null || _a === void 0 ? void 0 : _a.performance)) { + if (global.performance.mark) { + global.performance.mark('sentry-tracing-init'); + } + this._trackCLS(); + this._trackLCP(); + this._trackFID(); + } + } + /** Add performance related spans to a transaction */ + MetricsInstrumentation.prototype.addPerformanceEntries = function (transaction) { + var _this = this; + if (!global || !global.performance || !global.performance.getEntries || !utils_1.browserPerformanceTimeOrigin) { + // Gatekeeper if performance API not available + return; + } + utils_1.logger.log('[Tracing] Adding & adjusting spans using Performance API'); + var timeOrigin = utils_2.msToSec(utils_1.browserPerformanceTimeOrigin); + var entryScriptSrc; + if (global.document && global.document.scripts) { + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (var i = 0; i < global.document.scripts.length; i++) { + // We go through all scripts on the page and look for 'data-entry' + // We remember the name and measure the time between this script finished loading and + // our mark 'sentry-tracing-init' + if (global.document.scripts[i].dataset.entry === 'true') { + entryScriptSrc = global.document.scripts[i].src; + break; + } + } + } + var entryScriptStartTimestamp; + var tracingInitMarkStartTime; + var responseStartTimestamp; + var requestStartTimestamp; + global.performance + .getEntries() + .slice(this._performanceCursor) + .forEach(function (entry) { + var startTime = utils_2.msToSec(entry.startTime); + var duration = utils_2.msToSec(entry.duration); + if (transaction.op === 'navigation' && timeOrigin + startTime < transaction.startTimestamp) { + return; + } + switch (entry.entryType) { + case 'navigation': { + addNavigationSpans(transaction, entry, timeOrigin); + responseStartTimestamp = timeOrigin + utils_2.msToSec(entry.responseStart); + requestStartTimestamp = timeOrigin + utils_2.msToSec(entry.requestStart); + break; + } + case 'mark': + case 'paint': + case 'measure': { + var startTimestamp = addMeasureSpans(transaction, entry, startTime, duration, timeOrigin); + if (tracingInitMarkStartTime === undefined && entry.name === 'sentry-tracing-init') { + tracingInitMarkStartTime = startTimestamp; + } + // capture web vitals + var firstHidden = getVisibilityWatcher_1.getVisibilityWatcher(); + // Only report if the page wasn't hidden prior to the web vital. + var shouldRecord = entry.startTime < firstHidden.firstHiddenTime; + if (entry.name === 'first-paint' && shouldRecord) { + utils_1.logger.log('[Measurements] Adding FP'); + _this._measurements['fp'] = { value: entry.startTime }; + _this._measurements['mark.fp'] = { value: startTimestamp }; + } + if (entry.name === 'first-contentful-paint' && shouldRecord) { + utils_1.logger.log('[Measurements] Adding FCP'); + _this._measurements['fcp'] = { value: entry.startTime }; + _this._measurements['mark.fcp'] = { value: startTimestamp }; + } + break; + } + case 'resource': { + var resourceName = entry.name.replace(window.location.origin, ''); + var endTimestamp = addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin); + // We remember the entry script end time to calculate the difference to the first init mark + if (entryScriptStartTimestamp === undefined && (entryScriptSrc || '').indexOf(resourceName) > -1) { + entryScriptStartTimestamp = endTimestamp; + } + break; + } + default: + // Ignore other entry types. + } + }); + if (entryScriptStartTimestamp !== undefined && tracingInitMarkStartTime !== undefined) { + _startChild(transaction, { + description: 'evaluation', + endTimestamp: tracingInitMarkStartTime, + op: 'script', + startTimestamp: entryScriptStartTimestamp, + }); + } + this._performanceCursor = Math.max(performance.getEntries().length - 1, 0); + this._trackNavigator(transaction); + // Measurements are only available for pageload transactions + if (transaction.op === 'pageload') { + // normalize applicable web vital values to be relative to transaction.startTimestamp + var timeOrigin_1 = utils_2.msToSec(utils_1.browserPerformanceTimeOrigin); + // Generate TTFB (Time to First Byte), which measured as the time between the beginning of the transaction and the + // start of the response in milliseconds + if (typeof responseStartTimestamp === 'number') { + utils_1.logger.log('[Measurements] Adding TTFB'); + this._measurements['ttfb'] = { value: (responseStartTimestamp - transaction.startTimestamp) * 1000 }; + if (typeof requestStartTimestamp === 'number' && requestStartTimestamp <= responseStartTimestamp) { + // Capture the time spent making the request and receiving the first byte of the response. + // This is the time between the start of the request and the start of the response in milliseconds. + this._measurements['ttfb.requestTime'] = { value: (responseStartTimestamp - requestStartTimestamp) * 1000 }; + } + } + ['fcp', 'fp', 'lcp'].forEach(function (name) { + if (!_this._measurements[name] || timeOrigin_1 >= transaction.startTimestamp) { + return; + } + // The web vitals, fcp, fp, lcp, and ttfb, all measure relative to timeOrigin. + // Unfortunately, timeOrigin is not captured within the transaction span data, so these web vitals will need + // to be adjusted to be relative to transaction.startTimestamp. + var oldValue = _this._measurements[name].value; + var measurementTimestamp = timeOrigin_1 + utils_2.msToSec(oldValue); + // normalizedValue should be in milliseconds + var normalizedValue = Math.abs((measurementTimestamp - transaction.startTimestamp) * 1000); + var delta = normalizedValue - oldValue; + utils_1.logger.log("[Measurements] Normalized " + name + " from " + oldValue + " to " + normalizedValue + " (" + delta + ")"); + _this._measurements[name].value = normalizedValue; + }); + if (this._measurements['mark.fid'] && this._measurements['fid']) { + // create span for FID + _startChild(transaction, { + description: 'first input delay', + endTimestamp: this._measurements['mark.fid'].value + utils_2.msToSec(this._measurements['fid'].value), + op: 'web.vitals', + startTimestamp: this._measurements['mark.fid'].value, + }); + } + // If FCP is not recorded we should not record the cls value + // according to the new definition of CLS. + if (!('fcp' in this._measurements)) { + delete this._measurements.cls; + } + transaction.setMeasurements(this._measurements); + this._tagMetricInfo(transaction); + } + }; + /** Add LCP / CLS data to transaction to allow debugging */ + MetricsInstrumentation.prototype._tagMetricInfo = function (transaction) { + if (this._lcpEntry) { + utils_1.logger.log('[Measurements] Adding LCP Data'); + // Capture Properties of the LCP element that contributes to the LCP. + if (this._lcpEntry.element) { + transaction.setTag('lcp.element', utils_1.htmlTreeAsString(this._lcpEntry.element)); + } + if (this._lcpEntry.id) { + transaction.setTag('lcp.id', this._lcpEntry.id); + } + if (this._lcpEntry.url) { + // Trim URL to the first 200 characters. + transaction.setTag('lcp.url', this._lcpEntry.url.trim().slice(0, 200)); + } + transaction.setTag('lcp.size', this._lcpEntry.size); + } + // See: https://developer.mozilla.org/en-US/docs/Web/API/LayoutShift + if (this._clsEntry && this._clsEntry.sources) { + utils_1.logger.log('[Measurements] Adding CLS Data'); + this._clsEntry.sources.forEach(function (source, index) { + return transaction.setTag("cls.source." + (index + 1), utils_1.htmlTreeAsString(source.node)); + }); + } + }; + /** Starts tracking the Cumulative Layout Shift on the current page. */ + MetricsInstrumentation.prototype._trackCLS = function () { + var _this = this; + // See: + // https://web.dev/evolving-cls/ + // https://web.dev/cls-web-tooling/ + getCLS_1.getCLS(function (metric) { + var entry = metric.entries.pop(); + if (!entry) { + return; + } + utils_1.logger.log('[Measurements] Adding CLS'); + _this._measurements['cls'] = { value: metric.value }; + _this._clsEntry = entry; + }); + }; + /** + * Capture the information of the user agent. + */ + MetricsInstrumentation.prototype._trackNavigator = function (transaction) { + var navigator = global.navigator; + if (!navigator) { + return; + } + // track network connectivity + var connection = navigator.connection; + if (connection) { + if (connection.effectiveType) { + transaction.setTag('effectiveConnectionType', connection.effectiveType); + } + if (connection.type) { + transaction.setTag('connectionType', connection.type); + } + if (isMeasurementValue(connection.rtt)) { + this._measurements['connection.rtt'] = { value: connection.rtt }; + } + if (isMeasurementValue(connection.downlink)) { + this._measurements['connection.downlink'] = { value: connection.downlink }; + } + } + if (isMeasurementValue(navigator.deviceMemory)) { + transaction.setTag('deviceMemory', String(navigator.deviceMemory)); + } + if (isMeasurementValue(navigator.hardwareConcurrency)) { + transaction.setTag('hardwareConcurrency', String(navigator.hardwareConcurrency)); + } + }; + /** Starts tracking the Largest Contentful Paint on the current page. */ + MetricsInstrumentation.prototype._trackLCP = function () { + var _this = this; + getLCP_1.getLCP(function (metric) { + var entry = metric.entries.pop(); + if (!entry) { + return; + } + var timeOrigin = utils_2.msToSec(utils_1.browserPerformanceTimeOrigin); + var startTime = utils_2.msToSec(entry.startTime); + utils_1.logger.log('[Measurements] Adding LCP'); + _this._measurements['lcp'] = { value: metric.value }; + _this._measurements['mark.lcp'] = { value: timeOrigin + startTime }; + _this._lcpEntry = entry; + }); + }; + /** Starts tracking the First Input Delay on the current page. */ + MetricsInstrumentation.prototype._trackFID = function () { + var _this = this; + getFID_1.getFID(function (metric) { + var entry = metric.entries.pop(); + if (!entry) { + return; + } + var timeOrigin = utils_2.msToSec(utils_1.browserPerformanceTimeOrigin); + var startTime = utils_2.msToSec(entry.startTime); + utils_1.logger.log('[Measurements] Adding FID'); + _this._measurements['fid'] = { value: metric.value }; + _this._measurements['mark.fid'] = { value: timeOrigin + startTime }; + }); + }; + return MetricsInstrumentation; +}()); +exports.MetricsInstrumentation = MetricsInstrumentation; +/** Instrument navigation entries */ +function addNavigationSpans(transaction, entry, timeOrigin) { + addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'unloadEvent', timeOrigin: timeOrigin }); + addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'redirect', timeOrigin: timeOrigin }); + addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'domContentLoadedEvent', timeOrigin: timeOrigin }); + addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'loadEvent', timeOrigin: timeOrigin }); + addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'connect', timeOrigin: timeOrigin }); + addPerformanceNavigationTiming({ + transaction: transaction, + entry: entry, + event: 'secureConnection', + timeOrigin: timeOrigin, + eventEnd: 'connectEnd', + description: 'TLS/SSL', + }); + addPerformanceNavigationTiming({ + transaction: transaction, + entry: entry, + event: 'fetch', + timeOrigin: timeOrigin, + eventEnd: 'domainLookupStart', + description: 'cache', + }); + addPerformanceNavigationTiming({ transaction: transaction, entry: entry, event: 'domainLookup', timeOrigin: timeOrigin, description: 'DNS' }); + addRequest(transaction, entry, timeOrigin); +} +/** Create measure related spans */ +function addMeasureSpans(transaction, entry, startTime, duration, timeOrigin) { + var measureStartTimestamp = timeOrigin + startTime; + var measureEndTimestamp = measureStartTimestamp + duration; + _startChild(transaction, { + description: entry.name, + endTimestamp: measureEndTimestamp, + op: entry.entryType, + startTimestamp: measureStartTimestamp, + }); + return measureStartTimestamp; +} +/** Create resource-related spans */ +function addResourceSpans(transaction, entry, resourceName, startTime, duration, timeOrigin) { + // we already instrument based on fetch and xhr, so we don't need to + // duplicate spans here. + if (entry.initiatorType === 'xmlhttprequest' || entry.initiatorType === 'fetch') { + return undefined; + } + var data = {}; + if ('transferSize' in entry) { + data['Transfer Size'] = entry.transferSize; + } + if ('encodedBodySize' in entry) { + data['Encoded Body Size'] = entry.encodedBodySize; + } + if ('decodedBodySize' in entry) { + data['Decoded Body Size'] = entry.decodedBodySize; + } + var startTimestamp = timeOrigin + startTime; + var endTimestamp = startTimestamp + duration; + _startChild(transaction, { + description: resourceName, + endTimestamp: endTimestamp, + op: entry.initiatorType ? "resource." + entry.initiatorType : 'resource', + startTimestamp: startTimestamp, + data: data, + }); + return endTimestamp; +} +exports.addResourceSpans = addResourceSpans; +/** Create performance navigation related spans */ +function addPerformanceNavigationTiming(props) { + var transaction = props.transaction, entry = props.entry, event = props.event, timeOrigin = props.timeOrigin, eventEnd = props.eventEnd, description = props.description; + var end = eventEnd ? entry[eventEnd] : entry[event + "End"]; + var start = entry[event + "Start"]; + if (!start || !end) { + return; + } + _startChild(transaction, { + op: 'browser', + description: (description !== null && description !== void 0 ? description : event), + startTimestamp: timeOrigin + utils_2.msToSec(start), + endTimestamp: timeOrigin + utils_2.msToSec(end), + }); +} +/** Create request and response related spans */ +function addRequest(transaction, entry, timeOrigin) { + _startChild(transaction, { + op: 'browser', + description: 'request', + startTimestamp: timeOrigin + utils_2.msToSec(entry.requestStart), + endTimestamp: timeOrigin + utils_2.msToSec(entry.responseEnd), + }); + _startChild(transaction, { + op: 'browser', + description: 'response', + startTimestamp: timeOrigin + utils_2.msToSec(entry.responseStart), + endTimestamp: timeOrigin + utils_2.msToSec(entry.responseEnd), + }); } - /** - * Populate the extensions and types maps. - * @private + * Helper function to start child on transactions. This function will make sure that the transaction will + * use the start timestamp of the created child span if it is earlier than the transactions actual + * start timestamp. */ - -function populateMaps (extensions, types) { - // source preference (least -> most) - var preference = ['nginx', 'apache', undefined, 'iana'] - - Object.keys(db).forEach(function forEachMimeType (type) { - var mime = db[type] - var exts = mime.extensions - - if (!exts || !exts.length) { - return - } - - // mime -> extensions - extensions[type] = exts - - // extension -> mime - for (var i = 0; i < exts.length; i++) { - var extension = exts[i] - - if (types[extension]) { - var from = preference.indexOf(db[types[extension]].source) - var to = preference.indexOf(mime.source) - - if (types[extension] !== 'application/octet-stream' && - (from > to || (from === to && types[extension].substr(0, 12) === 'application/'))) { - // skip the remapping - continue - } - } - - // set the extension -> mime - types[extension] = type +function _startChild(transaction, _a) { + var startTimestamp = _a.startTimestamp, ctx = tslib_1.__rest(_a, ["startTimestamp"]); + if (startTimestamp && transaction.startTimestamp > startTimestamp) { + transaction.startTimestamp = startTimestamp; } - }) + return transaction.startChild(tslib_1.__assign({ startTimestamp: startTimestamp }, ctx)); } - +exports._startChild = _startChild; +/** + * Checks if a given value is a valid measurement value. + */ +function isMeasurementValue(value) { + return typeof value === 'number' && isFinite(value); +} +//# sourceMappingURL=metrics.js.map /***/ }), -/***/ 49690: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { - -"use strict"; +/***/ 27854: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var spanstatus_1 = __nccwpck_require__(58522); +var utils_2 = __nccwpck_require__(31386); +exports.DEFAULT_TRACING_ORIGINS = ['localhost', /^\//]; +exports.defaultRequestInstrumentationOptions = { + traceFetch: true, + traceXHR: true, + tracingOrigins: exports.DEFAULT_TRACING_ORIGINS, }; -const events_1 = __nccwpck_require__(28614); -const debug_1 = __importDefault(__nccwpck_require__(38237)); -const promisify_1 = __importDefault(__nccwpck_require__(66570)); -const debug = debug_1.default('agent-base'); -function isAgent(v) { - return Boolean(v) && typeof v.addRequest === 'function'; -} -function isSecureEndpoint() { - const { stack } = new Error(); - if (typeof stack !== 'string') - return false; - return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); -} -function createAgent(callback, opts) { - return new createAgent.Agent(callback, opts); +/** Registers span creators for xhr and fetch requests */ +function instrumentOutgoingRequests(_options) { + // eslint-disable-next-line @typescript-eslint/unbound-method + var _a = tslib_1.__assign(tslib_1.__assign({}, exports.defaultRequestInstrumentationOptions), _options), traceFetch = _a.traceFetch, traceXHR = _a.traceXHR, tracingOrigins = _a.tracingOrigins, shouldCreateSpanForRequest = _a.shouldCreateSpanForRequest; + // We should cache url -> decision so that we don't have to compute + // regexp everytime we create a request. + var urlMap = {}; + var defaultShouldCreateSpan = function (url) { + if (urlMap[url]) { + return urlMap[url]; + } + var origins = tracingOrigins; + urlMap[url] = + origins.some(function (origin) { return utils_1.isMatchingPattern(url, origin); }) && + !utils_1.isMatchingPattern(url, 'sentry_key'); + return urlMap[url]; + }; + // We want that our users don't have to re-implement shouldCreateSpanForRequest themselves + // That's why we filter out already unwanted Spans from tracingOrigins + var shouldCreateSpan = defaultShouldCreateSpan; + if (typeof shouldCreateSpanForRequest === 'function') { + shouldCreateSpan = function (url) { + return defaultShouldCreateSpan(url) && shouldCreateSpanForRequest(url); + }; + } + var spans = {}; + if (traceFetch) { + utils_1.addInstrumentationHandler({ + callback: function (handlerData) { + fetchCallback(handlerData, shouldCreateSpan, spans); + }, + type: 'fetch', + }); + } + if (traceXHR) { + utils_1.addInstrumentationHandler({ + callback: function (handlerData) { + xhrCallback(handlerData, shouldCreateSpan, spans); + }, + type: 'xhr', + }); + } } -(function (createAgent) { - /** - * Base `http.Agent` implementation. - * No pooling/keep-alive is implemented by default. - * - * @param {Function} callback - * @api public - */ - class Agent extends events_1.EventEmitter { - constructor(callback, _opts) { - super(); - let opts = _opts; - if (typeof callback === 'function') { - this.callback = callback; - } - else if (callback) { - opts = callback; - } - // Timeout for the socket to be returned from the callback - this.timeout = null; - if (opts && typeof opts.timeout === 'number') { - this.timeout = opts.timeout; +exports.instrumentOutgoingRequests = instrumentOutgoingRequests; +/** + * Create and track fetch request spans + */ +function fetchCallback(handlerData, shouldCreateSpan, spans) { + if (!utils_2.hasTracingEnabled() || !(handlerData.fetchData && shouldCreateSpan(handlerData.fetchData.url))) { + return; + } + if (handlerData.endTimestamp && handlerData.fetchData.__span) { + var span = spans[handlerData.fetchData.__span]; + if (span) { + if (handlerData.response) { + // TODO (kmclb) remove this once types PR goes through + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + span.setHttpStatus(handlerData.response.status); } - // These aren't actually used by `agent-base`, but are required - // for the TypeScript definition files in `@types/node` :/ - this.maxFreeSockets = 1; - this.maxSockets = 1; - this.maxTotalSockets = Infinity; - this.sockets = {}; - this.freeSockets = {}; - this.requests = {}; - this.options = {}; - } - get defaultPort() { - if (typeof this.explicitDefaultPort === 'number') { - return this.explicitDefaultPort; + else if (handlerData.error) { + span.setStatus(spanstatus_1.SpanStatus.InternalError); } - return isSecureEndpoint() ? 443 : 80; + span.finish(); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete spans[handlerData.fetchData.__span]; } - set defaultPort(v) { - this.explicitDefaultPort = v; + return; + } + var activeTransaction = utils_2.getActiveTransaction(); + if (activeTransaction) { + var span = activeTransaction.startChild({ + data: tslib_1.__assign(tslib_1.__assign({}, handlerData.fetchData), { type: 'fetch' }), + description: handlerData.fetchData.method + " " + handlerData.fetchData.url, + op: 'http.client', + }); + handlerData.fetchData.__span = span.spanId; + spans[span.spanId] = span; + var request = (handlerData.args[0] = handlerData.args[0]); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var options = (handlerData.args[1] = handlerData.args[1] || {}); + var headers = options.headers; + if (utils_1.isInstanceOf(request, Request)) { + headers = request.headers; } - get protocol() { - if (typeof this.explicitProtocol === 'string') { - return this.explicitProtocol; + if (headers) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (typeof headers.append === 'function') { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + headers.append('sentry-trace', span.toTraceparent()); + } + else if (Array.isArray(headers)) { + headers = tslib_1.__spread(headers, [['sentry-trace', span.toTraceparent()]]); + } + else { + headers = tslib_1.__assign(tslib_1.__assign({}, headers), { 'sentry-trace': span.toTraceparent() }); } - return isSecureEndpoint() ? 'https:' : 'http:'; } - set protocol(v) { - this.explicitProtocol = v; + else { + headers = { 'sentry-trace': span.toTraceparent() }; } - callback(req, opts, fn) { - throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); + options.headers = headers; + } +} +exports.fetchCallback = fetchCallback; +/** + * Create and track xhr request spans + */ +function xhrCallback(handlerData, shouldCreateSpan, spans) { + var _a, _b; + if (!utils_2.hasTracingEnabled() || ((_a = handlerData.xhr) === null || _a === void 0 ? void 0 : _a.__sentry_own_request__) || + !(((_b = handlerData.xhr) === null || _b === void 0 ? void 0 : _b.__sentry_xhr__) && shouldCreateSpan(handlerData.xhr.__sentry_xhr__.url))) { + return; + } + var xhr = handlerData.xhr.__sentry_xhr__; + // check first if the request has finished and is tracked by an existing span which should now end + if (handlerData.endTimestamp && handlerData.xhr.__sentry_xhr_span_id__) { + var span = spans[handlerData.xhr.__sentry_xhr_span_id__]; + if (span) { + span.setHttpStatus(xhr.status_code); + span.finish(); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete spans[handlerData.xhr.__sentry_xhr_span_id__]; } - /** - * Called by node-core's "_http_client.js" module when creating - * a new HTTP request with this Agent instance. - * - * @api public - */ - addRequest(req, _opts) { - const opts = Object.assign({}, _opts); - if (typeof opts.secureEndpoint !== 'boolean') { - opts.secureEndpoint = isSecureEndpoint(); - } - if (opts.host == null) { - opts.host = 'localhost'; - } - if (opts.port == null) { - opts.port = opts.secureEndpoint ? 443 : 80; - } - if (opts.protocol == null) { - opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; + return; + } + // if not, create a new span to track it + var activeTransaction = utils_2.getActiveTransaction(); + if (activeTransaction) { + var span = activeTransaction.startChild({ + data: tslib_1.__assign(tslib_1.__assign({}, xhr.data), { type: 'xhr', method: xhr.method, url: xhr.url }), + description: xhr.method + " " + xhr.url, + op: 'http.client', + }); + handlerData.xhr.__sentry_xhr_span_id__ = span.spanId; + spans[handlerData.xhr.__sentry_xhr_span_id__] = span; + if (handlerData.xhr.setRequestHeader) { + try { + handlerData.xhr.setRequestHeader('sentry-trace', span.toTraceparent()); } - if (opts.host && opts.path) { - // If both a `host` and `path` are specified then it's most - // likely the result of a `url.parse()` call... we need to - // remove the `path` portion so that `net.connect()` doesn't - // attempt to open that as a unix socket file. - delete opts.path; + catch (_) { + // Error: InvalidStateError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': The object's state must be OPENED. } - delete opts.agent; - delete opts.hostname; - delete opts._defaultAgent; - delete opts.defaultPort; - delete opts.createConnection; - // Hint to use "Connection: close" - // XXX: non-documented `http` module API :( - req._last = true; - req.shouldKeepAlive = false; - let timedOut = false; - let timeoutId = null; - const timeoutMs = opts.timeout || this.timeout; - const onerror = (err) => { - if (req._hadError) - return; - req.emit('error', err); - // For Safety. Some additional errors might fire later on - // and we need to make sure we don't double-fire the error event. - req._hadError = true; - }; - const ontimeout = () => { - timeoutId = null; - timedOut = true; - const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); - err.code = 'ETIMEOUT'; - onerror(err); - }; - const callbackError = (err) => { - if (timedOut) - return; - if (timeoutId !== null) { - clearTimeout(timeoutId); - timeoutId = null; - } - onerror(err); - }; - const onsocket = (socket) => { - if (timedOut) - return; - if (timeoutId != null) { - clearTimeout(timeoutId); - timeoutId = null; - } - if (isAgent(socket)) { - // `socket` is actually an `http.Agent` instance, so - // relinquish responsibility for this `req` to the Agent - // from here on - debug('Callback returned another Agent instance %o', socket.constructor.name); - socket.addRequest(req, opts); + } + } +} +exports.xhrCallback = xhrCallback; +//# sourceMappingURL=request.js.map + +/***/ }), + +/***/ 40348: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var utils_1 = __nccwpck_require__(1620); +var global = utils_1.getGlobalObject(); +/** + * Default function implementing pageload and navigation transactions + */ +function instrumentRoutingWithDefaults(customStartTransaction, startTransactionOnPageLoad, startTransactionOnLocationChange) { + if (startTransactionOnPageLoad === void 0) { startTransactionOnPageLoad = true; } + if (startTransactionOnLocationChange === void 0) { startTransactionOnLocationChange = true; } + if (!global || !global.location) { + utils_1.logger.warn('Could not initialize routing instrumentation due to invalid location'); + return; + } + var startingUrl = global.location.href; + var activeTransaction; + if (startTransactionOnPageLoad) { + activeTransaction = customStartTransaction({ name: global.location.pathname, op: 'pageload' }); + } + if (startTransactionOnLocationChange) { + utils_1.addInstrumentationHandler({ + callback: function (_a) { + var to = _a.to, from = _a.from; + /** + * This early return is there to account for some cases where a navigation transaction starts right after + * long-running pageload. We make sure that if `from` is undefined and a valid `startingURL` exists, we don't + * create an uneccessary navigation transaction. + * + * This was hard to duplicate, but this behavior stopped as soon as this fix was applied. This issue might also + * only be caused in certain development environments where the usage of a hot module reloader is causing + * errors. + */ + if (from === undefined && startingUrl && startingUrl.indexOf(to) !== -1) { + startingUrl = undefined; return; } - if (socket) { - socket.once('free', () => { - this.freeSocket(socket, opts); - }); - req.onSocket(socket); - return; + if (from !== to) { + startingUrl = undefined; + if (activeTransaction) { + utils_1.logger.log("[Tracing] Finishing current transaction with op: " + activeTransaction.op); + // If there's an open transaction on the scope, we need to finish it before creating an new one. + activeTransaction.finish(); + } + activeTransaction = customStartTransaction({ name: global.location.pathname, op: 'navigation' }); } - const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); - onerror(err); - }; - if (typeof this.callback !== 'function') { - onerror(new Error('`callback` is not defined')); - return; + }, + type: 'history', + }); + } +} +exports.instrumentRoutingWithDefaults = instrumentRoutingWithDefaults; +//# sourceMappingURL=router.js.map + +/***/ }), + +/***/ 56982: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +/* + * Copyright 2020 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 + * + * https://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. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var bindReporter_1 = __nccwpck_require__(54592); +var initMetric_1 = __nccwpck_require__(45300); +var observe_1 = __nccwpck_require__(17984); +var onHidden_1 = __nccwpck_require__(9658); +exports.getCLS = function (onReport, reportAllChanges) { + var metric = initMetric_1.initMetric('CLS', 0); + var report; + var sessionValue = 0; + var sessionEntries = []; + var entryHandler = function (entry) { + // Only count layout shifts without recent user input. + // TODO: Figure out why entry can be undefined + if (entry && !entry.hadRecentInput) { + var firstSessionEntry = sessionEntries[0]; + var lastSessionEntry = sessionEntries[sessionEntries.length - 1]; + // If the entry occurred less than 1 second after the previous entry and + // less than 5 seconds after the first entry in the session, include the + // entry in the current session. Otherwise, start a new session. + if (sessionValue && + sessionEntries.length !== 0 && + entry.startTime - lastSessionEntry.startTime < 1000 && + entry.startTime - firstSessionEntry.startTime < 5000) { + sessionValue += entry.value; + sessionEntries.push(entry); } - if (!this.promisifiedCallback) { - if (this.callback.length >= 3) { - debug('Converting legacy callback function to promise'); - this.promisifiedCallback = promisify_1.default(this.callback); - } - else { - this.promisifiedCallback = this.callback; + else { + sessionValue = entry.value; + sessionEntries = [entry]; + } + // If the current session value is larger than the current CLS value, + // update CLS and the entries contributing to it. + if (sessionValue > metric.value) { + metric.value = sessionValue; + metric.entries = sessionEntries; + if (report) { + report(); } } - if (typeof timeoutMs === 'number' && timeoutMs > 0) { - timeoutId = setTimeout(ontimeout, timeoutMs); - } - if ('port' in opts && typeof opts.port !== 'number') { - opts.port = Number(opts.port); - } - try { - debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); - Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); - } - catch (err) { - Promise.reject(err).catch(callbackError); - } } - freeSocket(socket, opts) { - debug('Freeing socket %o %o', socket.constructor.name, opts); - socket.destroy(); + }; + var po = observe_1.observe('layout-shift', entryHandler); + if (po) { + report = bindReporter_1.bindReporter(onReport, metric, reportAllChanges); + onHidden_1.onHidden(function () { + po.takeRecords().map(entryHandler); + report(true); + }); + } +}; +//# sourceMappingURL=getCLS.js.map + +/***/ }), + +/***/ 82496: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +/* + * Copyright 2020 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 + * + * https://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. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var bindReporter_1 = __nccwpck_require__(54592); +var getVisibilityWatcher_1 = __nccwpck_require__(10522); +var initMetric_1 = __nccwpck_require__(45300); +var observe_1 = __nccwpck_require__(17984); +var onHidden_1 = __nccwpck_require__(9658); +exports.getFID = function (onReport, reportAllChanges) { + var visibilityWatcher = getVisibilityWatcher_1.getVisibilityWatcher(); + var metric = initMetric_1.initMetric('FID'); + var report; + var entryHandler = function (entry) { + // Only report if the page wasn't hidden prior to the first input. + if (report && entry.startTime < visibilityWatcher.firstHiddenTime) { + metric.value = entry.processingStart - entry.startTime; + metric.entries.push(entry); + report(true); + } + }; + var po = observe_1.observe('first-input', entryHandler); + if (po) { + report = bindReporter_1.bindReporter(onReport, metric, reportAllChanges); + onHidden_1.onHidden(function () { + po.takeRecords().map(entryHandler); + po.disconnect(); + }, true); + } +}; +//# sourceMappingURL=getFID.js.map + +/***/ }), + +/***/ 99382: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +/* + * Copyright 2020 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 + * + * https://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. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var bindReporter_1 = __nccwpck_require__(54592); +var getVisibilityWatcher_1 = __nccwpck_require__(10522); +var initMetric_1 = __nccwpck_require__(45300); +var observe_1 = __nccwpck_require__(17984); +var onHidden_1 = __nccwpck_require__(9658); +var reportedMetricIDs = {}; +exports.getLCP = function (onReport, reportAllChanges) { + var visibilityWatcher = getVisibilityWatcher_1.getVisibilityWatcher(); + var metric = initMetric_1.initMetric('LCP'); + var report; + var entryHandler = function (entry) { + // The startTime attribute returns the value of the renderTime if it is not 0, + // and the value of the loadTime otherwise. + var value = entry.startTime; + // If the page was hidden prior to paint time of the entry, + // ignore it and mark the metric as final, otherwise add the entry. + if (value < visibilityWatcher.firstHiddenTime) { + metric.value = value; + metric.entries.push(entry); } - destroy() { - debug('Destroying agent %o', this.constructor.name); + if (report) { + report(); } + }; + var po = observe_1.observe('largest-contentful-paint', entryHandler); + if (po) { + report = bindReporter_1.bindReporter(onReport, metric, reportAllChanges); + var stopListening_1 = function () { + if (!reportedMetricIDs[metric.id]) { + po.takeRecords().map(entryHandler); + po.disconnect(); + reportedMetricIDs[metric.id] = true; + report(true); + } + }; + // Stop listening after input. Note: while scrolling is an input that + // stop LCP observation, it's unreliable since it can be programmatically + // generated. See: https://github.com/GoogleChrome/web-vitals/issues/75 + ['keydown', 'click'].forEach(function (type) { + addEventListener(type, stopListening_1, { once: true, capture: true }); + }); + onHidden_1.onHidden(stopListening_1, true); } - createAgent.Agent = Agent; - // So that `instanceof` works correctly - createAgent.prototype = createAgent.Agent.prototype; -})(createAgent || (createAgent = {})); -module.exports = createAgent; -//# sourceMappingURL=index.js.map +}; +//# sourceMappingURL=getLCP.js.map /***/ }), -/***/ 66570: +/***/ 54592: /***/ ((__unused_webpack_module, exports) => { -"use strict"; - +/* + * Copyright 2020 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 + * + * https://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. + */ Object.defineProperty(exports, "__esModule", ({ value: true })); -function promisify(fn) { - return function (req, opts) { - return new Promise((resolve, reject) => { - fn.call(this, req, opts, (err, rtn) => { - if (err) { - reject(err); - } - else { - resolve(rtn); +exports.bindReporter = function (callback, metric, reportAllChanges) { + var prevValue; + return function (forceReport) { + if (metric.value >= 0) { + if (forceReport || reportAllChanges) { + metric.delta = metric.value - (prevValue || 0); + // Report the metric if there's a non-zero delta or if no previous + // value exists (which can happen in the case of the document becoming + // hidden when the metric value is 0). + // See: https://github.com/GoogleChrome/web-vitals/issues/14 + if (metric.delta || prevValue === undefined) { + prevValue = metric.value; + callback(metric); } - }); - }); + } + } }; -} -exports.default = promisify; -//# sourceMappingURL=promisify.js.map - -/***/ }), - -/***/ 61231: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -const indentString = __nccwpck_require__(98043); -const cleanStack = __nccwpck_require__(27972); - -const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); - -class AggregateError extends Error { - constructor(errors) { - if (!Array.isArray(errors)) { - throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); - } - - errors = [...errors].map(error => { - if (error instanceof Error) { - return error; - } - - if (error !== null && typeof error === 'object') { - // Handle plain error objects with message property and/or possibly other metadata - return Object.assign(new Error(error.message), error); - } - - return new Error(error); - }); - - let message = errors - .map(error => { - // The `stack` property is not standardized, so we can't assume it exists - return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); - }) - .join('\n'); - message = '\n' + indentString(message, 4); - super(message); - - this.name = 'AggregateError'; - - Object.defineProperty(this, '_errors', {value: errors}); - } - - * [Symbol.iterator]() { - for (const error of this._errors) { - yield error; - } - } -} - -module.exports = AggregateError; - +}; +//# sourceMappingURL=bindReporter.js.map /***/ }), -/***/ 65063: -/***/ ((module) => { - -"use strict"; - - -module.exports = ({onlyFirst = false} = {}) => { - const pattern = [ - '[\\u001B\\u009B][[\\]()#;?]*(?:(?:(?:[a-zA-Z\\d]*(?:;[-a-zA-Z\\d\\/#&.:=?%@~_]*)*)?\\u0007)', - '(?:(?:\\d{1,4}(?:;\\d{0,4})*)?[\\dA-PR-TZcf-ntqry=><~]))' - ].join('|'); +/***/ 70093: +/***/ ((__unused_webpack_module, exports) => { - return new RegExp(pattern, onlyFirst ? undefined : 'g'); +/* + * Copyright 2020 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 + * + * https://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. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Performantly generate a unique, 30-char string by combining a version + * number, the current timestamp with a 13-digit number integer. + * @return {string} + */ +exports.generateUniqueID = function () { + return "v2-" + Date.now() + "-" + (Math.floor(Math.random() * (9e12 - 1)) + 1e12); }; - +//# sourceMappingURL=generateUniqueID.js.map /***/ }), -/***/ 52068: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/* module decorator */ module = __nccwpck_require__.nmd(module); - +/***/ 10522: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -const wrapAnsi16 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${code + offset}m`; +/* + * Copyright 2020 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 + * + * https://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. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var onHidden_1 = __nccwpck_require__(9658); +var firstHiddenTime = -1; +var initHiddenTime = function () { + return document.visibilityState === 'hidden' ? 0 : Infinity; }; - -const wrapAnsi256 = (fn, offset) => (...args) => { - const code = fn(...args); - return `\u001B[${38 + offset};5;${code}m`; +var trackChanges = function () { + // Update the time if/when the document becomes hidden. + onHidden_1.onHidden(function (_a) { + var timeStamp = _a.timeStamp; + firstHiddenTime = timeStamp; + }, true); }; - -const wrapAnsi16m = (fn, offset) => (...args) => { - const rgb = fn(...args); - return `\u001B[${38 + offset};2;${rgb[0]};${rgb[1]};${rgb[2]}m`; +exports.getVisibilityWatcher = function () { + if (firstHiddenTime < 0) { + // If the document is hidden when this code runs, assume it was hidden + // since navigation start. This isn't a perfect heuristic, but it's the + // best we can do until an API is available to support querying past + // visibilityState. + firstHiddenTime = initHiddenTime(); + trackChanges(); + } + return { + get firstHiddenTime() { + return firstHiddenTime; + }, + }; }; +//# sourceMappingURL=getVisibilityWatcher.js.map -const ansi2ansi = n => n; -const rgb2rgb = (r, g, b) => [r, g, b]; - -const setLazyProperty = (object, property, get) => { - Object.defineProperty(object, property, { - get: () => { - const value = get(); +/***/ }), - Object.defineProperty(object, property, { - value, - enumerable: true, - configurable: true - }); +/***/ 45300: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return value; - }, - enumerable: true, - configurable: true - }); +/* + * Copyright 2020 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 + * + * https://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. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +var generateUniqueID_1 = __nccwpck_require__(70093); +exports.initMetric = function (name, value) { + return { + name: name, + value: (value !== null && value !== void 0 ? value : -1), + delta: 0, + entries: [], + id: generateUniqueID_1.generateUniqueID(), + }; }; +//# sourceMappingURL=initMetric.js.map -/** @type {typeof import('color-convert')} */ -let colorConvert; -const makeDynamicStyles = (wrap, targetSpace, identity, isBackground) => { - if (colorConvert === undefined) { - colorConvert = __nccwpck_require__(86931); - } - - const offset = isBackground ? 10 : 0; - const styles = {}; - - for (const [sourceSpace, suite] of Object.entries(colorConvert)) { - const name = sourceSpace === 'ansi16' ? 'ansi' : sourceSpace; - if (sourceSpace === targetSpace) { - styles[name] = wrap(identity, offset); - } else if (typeof suite === 'object') { - styles[name] = wrap(suite[targetSpace], offset); - } - } - - return styles; -}; - -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; +/***/ }), - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; +/***/ 17984: +/***/ ((__unused_webpack_module, exports) => { - group[styleName] = styles[styleName]; +/* + * Copyright 2020 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 + * + * https://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. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Takes a performance entry type and a callback function, and creates a + * `PerformanceObserver` instance that will observe the specified entry type + * with buffering enabled and call the callback _for each entry_. + * + * This function also feature-detects entry support and wraps the logic in a + * try/catch to avoid errors in unsupporting browsers. + */ +exports.observe = function (type, callback) { + try { + if (PerformanceObserver.supportedEntryTypes.includes(type)) { + // More extensive feature detect needed for Firefox due to: + // https://github.com/GoogleChrome/web-vitals/issues/142 + if (type === 'first-input' && !('PerformanceEventTiming' in self)) { + return; + } + var po = new PerformanceObserver(function (l) { return l.getEntries().map(callback); }); + po.observe({ type: type, buffered: true }); + return po; + } + } + catch (e) { + // Do nothing. + } + return; +}; +//# sourceMappingURL=observe.js.map - codes.set(style[0], style[1]); - } +/***/ }), - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } +/***/ 9658: +/***/ ((__unused_webpack_module, exports) => { - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); +/* + * Copyright 2020 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 + * + * https://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. + */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.onHidden = function (cb, once) { + var onHiddenOrPageHide = function (event) { + if (event.type === 'pagehide' || document.visibilityState === 'hidden') { + cb(event); + if (once) { + removeEventListener('visibilitychange', onHiddenOrPageHide, true); + removeEventListener('pagehide', onHiddenOrPageHide, true); + } + } + }; + addEventListener('visibilitychange', onHiddenOrPageHide, true); + // Some browsers have buggy implementations of visibilitychange, + // so we use pagehide in addition, just to be safe. + addEventListener('pagehide', onHiddenOrPageHide, true); +}; +//# sourceMappingURL=onHidden.js.map - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; +/***/ }), - setLazyProperty(styles.color, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, false)); - setLazyProperty(styles.color, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, false)); - setLazyProperty(styles.bgColor, 'ansi', () => makeDynamicStyles(wrapAnsi16, 'ansi16', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi256', () => makeDynamicStyles(wrapAnsi256, 'ansi256', ansi2ansi, true)); - setLazyProperty(styles.bgColor, 'ansi16m', () => makeDynamicStyles(wrapAnsi16m, 'rgb', rgb2rgb, true)); +/***/ 47906: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return styles; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var utils_1 = __nccwpck_require__(1620); +var spanstatus_1 = __nccwpck_require__(58522); +var utils_2 = __nccwpck_require__(31386); +/** + * Configures global error listeners + */ +function registerErrorInstrumentation() { + utils_1.addInstrumentationHandler({ + callback: errorCallback, + type: 'error', + }); + utils_1.addInstrumentationHandler({ + callback: errorCallback, + type: 'unhandledrejection', + }); } - -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); - +exports.registerErrorInstrumentation = registerErrorInstrumentation; +/** + * If an error or unhandled promise occurs, we mark the active transaction as failed + */ +function errorCallback() { + var activeTransaction = utils_2.getActiveTransaction(); + if (activeTransaction) { + utils_1.logger.log("[Tracing] Transaction: " + spanstatus_1.SpanStatus.InternalError + " -> Global error occured"); + activeTransaction.setStatus(spanstatus_1.SpanStatus.InternalError); + } +} +//# sourceMappingURL=errors.js.map /***/ }), -/***/ 62003: -/***/ ((module) => { - -"use strict"; - +/***/ 31409: +/***/ ((module, exports, __nccwpck_require__) => { +/* module decorator */ module = __nccwpck_require__.nmd(module); +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var hub_1 = __nccwpck_require__(6393); +var types_1 = __nccwpck_require__(83789); +var utils_1 = __nccwpck_require__(1620); +var errors_1 = __nccwpck_require__(47906); +var idletransaction_1 = __nccwpck_require__(2171); +var transaction_1 = __nccwpck_require__(8186); +var utils_2 = __nccwpck_require__(31386); +/** Returns all trace headers that are currently on the top scope. */ +function traceHeaders() { + var scope = this.getScope(); + if (scope) { + var span = scope.getSpan(); + if (span) { + return { + 'sentry-trace': span.toTraceparent(), + }; + } + } + return {}; +} /** - * Expose `arrayFlatten`. + * Makes a sampling decision for the given transaction and stores it on the transaction. + * + * Called every time a transaction is created. Only transactions which emerge with a `sampled` value of `true` will be + * sent to Sentry. + * + * @param hub: The hub off of which to read config options + * @param transaction: The transaction needing a sampling decision + * @param samplingContext: Default and user-provided data which may be used to help make the decision + * + * @returns The given transaction with its `sampled` value set */ -module.exports = arrayFlatten - +function sample(transaction, options, samplingContext) { + // nothing to do if tracing is not enabled + if (!utils_2.hasTracingEnabled()) { + transaction.sampled = false; + return transaction; + } + // if the user has forced a sampling decision by passing a `sampled` value in their transaction context, go with that + if (transaction.sampled !== undefined) { + transaction.setMetadata({ + transactionSampling: { method: types_1.TransactionSamplingMethod.Explicit }, + }); + return transaction; + } + // we would have bailed already if neither `tracesSampler` nor `tracesSampleRate` were defined, so one of these should + // work; prefer the hook if so + var sampleRate; + if (typeof options.tracesSampler === 'function') { + sampleRate = options.tracesSampler(samplingContext); + transaction.setMetadata({ + transactionSampling: { + method: types_1.TransactionSamplingMethod.Sampler, + // cast to number in case it's a boolean + rate: Number(sampleRate), + }, + }); + } + else if (samplingContext.parentSampled !== undefined) { + sampleRate = samplingContext.parentSampled; + transaction.setMetadata({ + transactionSampling: { method: types_1.TransactionSamplingMethod.Inheritance }, + }); + } + else { + sampleRate = options.tracesSampleRate; + transaction.setMetadata({ + transactionSampling: { + method: types_1.TransactionSamplingMethod.Rate, + // cast to number in case it's a boolean + rate: Number(sampleRate), + }, + }); + } + // Since this is coming from the user (or from a function provided by the user), who knows what we might get. (The + // only valid values are booleans or numbers between 0 and 1.) + if (!isValidSampleRate(sampleRate)) { + utils_1.logger.warn("[Tracing] Discarding transaction because of invalid sample rate."); + transaction.sampled = false; + return transaction; + } + // if the function returned 0 (or false), or if `tracesSampleRate` is 0, it's a sign the transaction should be dropped + if (!sampleRate) { + utils_1.logger.log("[Tracing] Discarding transaction because " + (typeof options.tracesSampler === 'function' + ? 'tracesSampler returned 0 or false' + : 'a negative sampling decision was inherited or tracesSampleRate is set to 0')); + transaction.sampled = false; + return transaction; + } + // Now we roll the dice. Math.random is inclusive of 0, but not of 1, so strict < is safe here. In case sampleRate is + // a boolean, the < comparison will cause it to be automatically cast to 1 if it's true and 0 if it's false. + transaction.sampled = Math.random() < sampleRate; + // if we're not going to keep it, we're done + if (!transaction.sampled) { + utils_1.logger.log("[Tracing] Discarding transaction because it's not included in the random sample (sampling rate = " + Number(sampleRate) + ")"); + return transaction; + } + utils_1.logger.log("[Tracing] starting " + transaction.op + " transaction - " + transaction.name); + return transaction; +} /** - * Recursive flatten function with depth. + * Checks the given sample rate to make sure it is valid type and value (a boolean, or a number between 0 and 1). + */ +function isValidSampleRate(rate) { + // we need to check NaN explicitly because it's of type 'number' and therefore wouldn't get caught by this typecheck + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (isNaN(rate) || !(typeof rate === 'number' || typeof rate === 'boolean')) { + utils_1.logger.warn("[Tracing] Given sample rate is invalid. Sample rate must be a boolean or a number between 0 and 1. Got " + JSON.stringify(rate) + " of type " + JSON.stringify(typeof rate) + "."); + return false; + } + // in case sampleRate is a boolean, it will get automatically cast to 1 if it's true and 0 if it's false + if (rate < 0 || rate > 1) { + utils_1.logger.warn("[Tracing] Given sample rate is invalid. Sample rate must be between 0 and 1. Got " + rate + "."); + return false; + } + return true; +} +/** + * Creates a new transaction and adds a sampling decision if it doesn't yet have one. * - * @param {Array} array - * @param {Array} result - * @param {Number} depth - * @return {Array} + * The Hub.startTransaction method delegates to this method to do its work, passing the Hub instance in as `this`, as if + * it had been called on the hub directly. Exists as a separate function so that it can be injected into the class as an + * "extension method." + * + * @param this: The Hub starting the transaction + * @param transactionContext: Data used to configure the transaction + * @param CustomSamplingContext: Optional data to be provided to the `tracesSampler` function (if any) + * + * @returns The new transaction + * + * @see {@link Hub.startTransaction} + */ +function _startTransaction(transactionContext, customSamplingContext) { + var _a, _b; + var options = ((_a = this.getClient()) === null || _a === void 0 ? void 0 : _a.getOptions()) || {}; + var transaction = new transaction_1.Transaction(transactionContext, this); + transaction = sample(transaction, options, tslib_1.__assign({ parentSampled: transactionContext.parentSampled, transactionContext: transactionContext }, customSamplingContext)); + if (transaction.sampled) { + transaction.initSpanRecorder((_b = options._experiments) === null || _b === void 0 ? void 0 : _b.maxSpans); + } + return transaction; +} +/** + * Create new idle transaction. + */ +function startIdleTransaction(hub, transactionContext, idleTimeout, onScope, customSamplingContext) { + var _a, _b; + var options = ((_a = hub.getClient()) === null || _a === void 0 ? void 0 : _a.getOptions()) || {}; + var transaction = new idletransaction_1.IdleTransaction(transactionContext, hub, idleTimeout, onScope); + transaction = sample(transaction, options, tslib_1.__assign({ parentSampled: transactionContext.parentSampled, transactionContext: transactionContext }, customSamplingContext)); + if (transaction.sampled) { + transaction.initSpanRecorder((_b = options._experiments) === null || _b === void 0 ? void 0 : _b.maxSpans); + } + return transaction; +} +exports.startIdleTransaction = startIdleTransaction; +/** + * @private */ -function flattenWithDepth (array, result, depth) { - for (var i = 0; i < array.length; i++) { - var value = array[i] - - if (depth > 0 && Array.isArray(value)) { - flattenWithDepth(value, result, depth - 1) - } else { - result.push(value) +function _addTracingExtensions() { + var carrier = hub_1.getMainCarrier(); + if (!carrier.__SENTRY__) { + return; + } + carrier.__SENTRY__.extensions = carrier.__SENTRY__.extensions || {}; + if (!carrier.__SENTRY__.extensions.startTransaction) { + carrier.__SENTRY__.extensions.startTransaction = _startTransaction; + } + if (!carrier.__SENTRY__.extensions.traceHeaders) { + carrier.__SENTRY__.extensions.traceHeaders = traceHeaders; } - } - - return result } - +exports._addTracingExtensions = _addTracingExtensions; /** - * Recursive flatten function. Omitting depth is slightly faster. - * - * @param {Array} array - * @param {Array} result - * @return {Array} + * @private */ -function flattenForever (array, result) { - for (var i = 0; i < array.length; i++) { - var value = array[i] - - if (Array.isArray(value)) { - flattenForever(value, result) - } else { - result.push(value) +function _autoloadDatabaseIntegrations() { + var carrier = hub_1.getMainCarrier(); + if (!carrier.__SENTRY__) { + return; + } + var packageToIntegrationMapping = { + mongodb: function () { + var integration = utils_1.dynamicRequire(module, './integrations/mongo'); + return new integration.Mongo(); + }, + mongoose: function () { + var integration = utils_1.dynamicRequire(module, './integrations/mongo'); + return new integration.Mongo({ mongoose: true }); + }, + mysql: function () { + var integration = utils_1.dynamicRequire(module, './integrations/mysql'); + return new integration.Mysql(); + }, + pg: function () { + var integration = utils_1.dynamicRequire(module, './integrations/postgres'); + return new integration.Postgres(); + }, + }; + var mappedPackages = Object.keys(packageToIntegrationMapping) + .filter(function (moduleName) { return !!utils_1.loadModule(moduleName); }) + .map(function (pkg) { + try { + return packageToIntegrationMapping[pkg](); + } + catch (e) { + return undefined; + } + }) + .filter(function (p) { return p; }); + if (mappedPackages.length > 0) { + carrier.__SENTRY__.integrations = tslib_1.__spread((carrier.__SENTRY__.integrations || []), mappedPackages); } - } - - return result } - /** - * Flatten an array, with the ability to define a depth. - * - * @param {Array} array - * @param {Number} depth - * @return {Array} + * This patches the global object and injects the Tracing extensions methods */ -function arrayFlatten (array, depth) { - if (depth == null) { - return flattenForever(array, []) - } - - return flattenWithDepth(array, [], depth) +function addExtensionMethods() { + _addTracingExtensions(); + // Detect and automatically load specified integrations. + if (utils_1.isNodeEnv()) { + _autoloadDatabaseIntegrations(); + } + // If an error happens globally, we should make sure transaction status is set to error. + errors_1.registerErrorInstrumentation(); } - - -/***/ }), - -/***/ 14812: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = -{ - parallel : __nccwpck_require__(8210), - serial : __nccwpck_require__(50445), - serialOrdered : __nccwpck_require__(3578) -}; - +exports.addExtensionMethods = addExtensionMethods; +//# sourceMappingURL=hubextensions.js.map /***/ }), -/***/ 1700: -/***/ ((module) => { - -// API -module.exports = abort; +/***/ 2171: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var span_1 = __nccwpck_require__(64655); +var spanstatus_1 = __nccwpck_require__(58522); +var transaction_1 = __nccwpck_require__(8186); +exports.DEFAULT_IDLE_TIMEOUT = 1000; /** - * Aborts leftover active jobs - * - * @param {object} state - current state object + * @inheritDoc */ -function abort(state) -{ - Object.keys(state.jobs).forEach(clean.bind(state)); - - // reset leftover jobs - state.jobs = {}; -} - +var IdleTransactionSpanRecorder = /** @class */ (function (_super) { + tslib_1.__extends(IdleTransactionSpanRecorder, _super); + function IdleTransactionSpanRecorder(_pushActivity, _popActivity, transactionSpanId, maxlen) { + if (transactionSpanId === void 0) { transactionSpanId = ''; } + var _this = _super.call(this, maxlen) || this; + _this._pushActivity = _pushActivity; + _this._popActivity = _popActivity; + _this.transactionSpanId = transactionSpanId; + return _this; + } + /** + * @inheritDoc + */ + IdleTransactionSpanRecorder.prototype.add = function (span) { + var _this = this; + // We should make sure we do not push and pop activities for + // the transaction that this span recorder belongs to. + if (span.spanId !== this.transactionSpanId) { + // We patch span.finish() to pop an activity after setting an endTimestamp. + span.finish = function (endTimestamp) { + span.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : utils_1.timestampWithMs(); + _this._popActivity(span.spanId); + }; + // We should only push new activities if the span does not have an end timestamp. + if (span.endTimestamp === undefined) { + this._pushActivity(span.spanId); + } + } + _super.prototype.add.call(this, span); + }; + return IdleTransactionSpanRecorder; +}(span_1.SpanRecorder)); +exports.IdleTransactionSpanRecorder = IdleTransactionSpanRecorder; /** - * Cleans up leftover job by invoking abort function for the provided job id - * - * @this state - * @param {string|number} key - job id to abort + * An IdleTransaction is a transaction that automatically finishes. It does this by tracking child spans as activities. + * You can have multiple IdleTransactions active, but if the `onScope` option is specified, the idle transaction will + * put itself on the scope on creation. */ -function clean(key) -{ - if (typeof this.jobs[key] == 'function') - { - this.jobs[key](); - } +var IdleTransaction = /** @class */ (function (_super) { + tslib_1.__extends(IdleTransaction, _super); + function IdleTransaction(transactionContext, _idleHub, + // The time to wait in ms until the idle transaction will be finished. Default: 1000 + _idleTimeout, + // If an idle transaction should be put itself on and off the scope automatically. + _onScope) { + if (_idleTimeout === void 0) { _idleTimeout = exports.DEFAULT_IDLE_TIMEOUT; } + if (_onScope === void 0) { _onScope = false; } + var _this = _super.call(this, transactionContext, _idleHub) || this; + _this._idleHub = _idleHub; + _this._idleTimeout = _idleTimeout; + _this._onScope = _onScope; + // Activities store a list of active spans + _this.activities = {}; + // Stores reference to the timeout that calls _beat(). + _this._heartbeatTimer = 0; + // Amount of times heartbeat has counted. Will cause transaction to finish after 3 beats. + _this._heartbeatCounter = 0; + // We should not use heartbeat if we finished a transaction + _this._finished = false; + _this._beforeFinishCallbacks = []; + if (_idleHub && _onScope) { + // There should only be one active transaction on the scope + clearActiveTransaction(_idleHub); + // We set the transaction here on the scope so error events pick up the trace + // context and attach it to the error. + utils_1.logger.log("Setting idle transaction on scope. Span ID: " + _this.spanId); + _idleHub.configureScope(function (scope) { return scope.setSpan(_this); }); + } + _this._initTimeout = setTimeout(function () { + if (!_this._finished) { + _this.finish(); + } + }, _this._idleTimeout); + return _this; + } + /** {@inheritDoc} */ + IdleTransaction.prototype.finish = function (endTimestamp) { + var e_1, _a; + var _this = this; + if (endTimestamp === void 0) { endTimestamp = utils_1.timestampWithMs(); } + this._finished = true; + this.activities = {}; + if (this.spanRecorder) { + utils_1.logger.log('[Tracing] finishing IdleTransaction', new Date(endTimestamp * 1000).toISOString(), this.op); + try { + for (var _b = tslib_1.__values(this._beforeFinishCallbacks), _c = _b.next(); !_c.done; _c = _b.next()) { + var callback = _c.value; + callback(this, endTimestamp); + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + this.spanRecorder.spans = this.spanRecorder.spans.filter(function (span) { + // If we are dealing with the transaction itself, we just return it + if (span.spanId === _this.spanId) { + return true; + } + // We cancel all pending spans with status "cancelled" to indicate the idle transaction was finished early + if (!span.endTimestamp) { + span.endTimestamp = endTimestamp; + span.setStatus(spanstatus_1.SpanStatus.Cancelled); + utils_1.logger.log('[Tracing] cancelling span since transaction ended early', JSON.stringify(span, undefined, 2)); + } + var keepSpan = span.startTimestamp < endTimestamp; + if (!keepSpan) { + utils_1.logger.log('[Tracing] discarding Span since it happened after Transaction was finished', JSON.stringify(span, undefined, 2)); + } + return keepSpan; + }); + utils_1.logger.log('[Tracing] flushing IdleTransaction'); + } + else { + utils_1.logger.log('[Tracing] No active IdleTransaction'); + } + // this._onScope is true if the transaction was previously on the scope. + if (this._onScope) { + clearActiveTransaction(this._idleHub); + } + return _super.prototype.finish.call(this, endTimestamp); + }; + /** + * Register a callback function that gets excecuted before the transaction finishes. + * Useful for cleanup or if you want to add any additional spans based on current context. + * + * This is exposed because users have no other way of running something before an idle transaction + * finishes. + */ + IdleTransaction.prototype.registerBeforeFinishCallback = function (callback) { + this._beforeFinishCallbacks.push(callback); + }; + /** + * @inheritDoc + */ + IdleTransaction.prototype.initSpanRecorder = function (maxlen) { + var _this = this; + if (!this.spanRecorder) { + var pushActivity = function (id) { + if (_this._finished) { + return; + } + _this._pushActivity(id); + }; + var popActivity = function (id) { + if (_this._finished) { + return; + } + _this._popActivity(id); + }; + this.spanRecorder = new IdleTransactionSpanRecorder(pushActivity, popActivity, this.spanId, maxlen); + // Start heartbeat so that transactions do not run forever. + utils_1.logger.log('Starting heartbeat'); + this._pingHeartbeat(); + } + this.spanRecorder.add(this); + }; + /** + * Start tracking a specific activity. + * @param spanId The span id that represents the activity + */ + IdleTransaction.prototype._pushActivity = function (spanId) { + if (this._initTimeout) { + clearTimeout(this._initTimeout); + this._initTimeout = undefined; + } + utils_1.logger.log("[Tracing] pushActivity: " + spanId); + this.activities[spanId] = true; + utils_1.logger.log('[Tracing] new activities count', Object.keys(this.activities).length); + }; + /** + * Remove an activity from usage + * @param spanId The span id that represents the activity + */ + IdleTransaction.prototype._popActivity = function (spanId) { + var _this = this; + if (this.activities[spanId]) { + utils_1.logger.log("[Tracing] popActivity " + spanId); + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete this.activities[spanId]; + utils_1.logger.log('[Tracing] new activities count', Object.keys(this.activities).length); + } + if (Object.keys(this.activities).length === 0) { + var timeout = this._idleTimeout; + // We need to add the timeout here to have the real endtimestamp of the transaction + // Remember timestampWithMs is in seconds, timeout is in ms + var end_1 = utils_1.timestampWithMs() + timeout / 1000; + setTimeout(function () { + if (!_this._finished) { + _this.finish(end_1); + } + }, timeout); + } + }; + /** + * Checks when entries of this.activities are not changing for 3 beats. + * If this occurs we finish the transaction. + */ + IdleTransaction.prototype._beat = function () { + clearTimeout(this._heartbeatTimer); + // We should not be running heartbeat if the idle transaction is finished. + if (this._finished) { + return; + } + var keys = Object.keys(this.activities); + var heartbeatString = keys.length ? keys.reduce(function (prev, current) { return prev + current; }) : ''; + if (heartbeatString === this._prevHeartbeatString) { + this._heartbeatCounter += 1; + } + else { + this._heartbeatCounter = 1; + } + this._prevHeartbeatString = heartbeatString; + if (this._heartbeatCounter >= 3) { + utils_1.logger.log("[Tracing] Transaction finished because of no change for 3 heart beats"); + this.setStatus(spanstatus_1.SpanStatus.DeadlineExceeded); + this.setTag('heartbeat', 'failed'); + this.finish(); + } + else { + this._pingHeartbeat(); + } + }; + /** + * Pings the heartbeat + */ + IdleTransaction.prototype._pingHeartbeat = function () { + var _this = this; + utils_1.logger.log("pinging Heartbeat -> current counter: " + this._heartbeatCounter); + this._heartbeatTimer = setTimeout(function () { + _this._beat(); + }, 5000); + }; + return IdleTransaction; +}(transaction_1.Transaction)); +exports.IdleTransaction = IdleTransaction; +/** + * Reset active transaction on scope + */ +function clearActiveTransaction(hub) { + if (hub) { + var scope = hub.getScope(); + if (scope) { + var transaction = scope.getTransaction(); + if (transaction) { + scope.setSpan(undefined); + } + } + } } - +//# sourceMappingURL=idletransaction.js.map /***/ }), -/***/ 72794: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 64358: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -var defer = __nccwpck_require__(15295); +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var browser_1 = __nccwpck_require__(71425); +var hubextensions_1 = __nccwpck_require__(31409); +exports.addExtensionMethods = hubextensions_1.addExtensionMethods; +var TracingIntegrations = __nccwpck_require__(28502); +var Integrations = tslib_1.__assign(tslib_1.__assign({}, TracingIntegrations), { BrowserTracing: browser_1.BrowserTracing }); +exports.Integrations = Integrations; +var span_1 = __nccwpck_require__(64655); +exports.Span = span_1.Span; +var transaction_1 = __nccwpck_require__(8186); +exports.Transaction = transaction_1.Transaction; +var browser_2 = __nccwpck_require__(71425); +// TODO deprecate old name in v7 +exports.registerRequestInstrumentation = browser_2.instrumentOutgoingRequests; +exports.defaultRequestInstrumentationOptions = browser_2.defaultRequestInstrumentationOptions; +var spanstatus_1 = __nccwpck_require__(58522); +exports.SpanStatus = spanstatus_1.SpanStatus; +var idletransaction_1 = __nccwpck_require__(2171); +exports.IdleTransaction = idletransaction_1.IdleTransaction; +var hubextensions_2 = __nccwpck_require__(31409); +exports.startIdleTransaction = hubextensions_2.startIdleTransaction; +// We are patching the global object with our hub extension methods +hubextensions_1.addExtensionMethods(); +var utils_1 = __nccwpck_require__(31386); +exports.extractTraceparentData = utils_1.extractTraceparentData; +exports.getActiveTransaction = utils_1.getActiveTransaction; +exports.hasTracingEnabled = utils_1.hasTracingEnabled; +exports.stripUrlQueryAndFragment = utils_1.stripUrlQueryAndFragment; +exports.TRACEPARENT_REGEXP = utils_1.TRACEPARENT_REGEXP; +//# sourceMappingURL=index.js.map -// API -module.exports = async; +/***/ }), + +/***/ 96221: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); /** - * Runs provided callback asynchronously - * even if callback itself is not + * Express integration * - * @param {function} callback - callback to invoke - * @returns {function} - augmented callback + * Provides an request and error handler for Express framework as well as tracing capabilities */ -function async(callback) -{ - var isAsync = false; - - // check if async happened - defer(function() { isAsync = true; }); - - return function async_callback(err, result) - { - if (isAsync) - { - callback(err, result); +var Express = /** @class */ (function () { + /** + * @inheritDoc + */ + function Express(options) { + if (options === void 0) { options = {}; } + /** + * @inheritDoc + */ + this.name = Express.id; + this._router = options.router || options.app; + this._methods = (Array.isArray(options.methods) ? options.methods : []).concat('use'); } - else - { - defer(function nextTick_callback() - { - callback(err, result); - }); + /** + * @inheritDoc + */ + Express.prototype.setupOnce = function () { + if (!this._router) { + utils_1.logger.error('ExpressIntegration is missing an Express instance'); + return; + } + instrumentMiddlewares(this._router, this._methods); + }; + /** + * @inheritDoc + */ + Express.id = 'Express'; + return Express; +}()); +exports.Express = Express; +/** + * Wraps original middleware function in a tracing call, which stores the info about the call as a span, + * and finishes it once the middleware is done invoking. + * + * Express middlewares have 3 various forms, thus we have to take care of all of them: + * // sync + * app.use(function (req, res) { ... }) + * // async + * app.use(function (req, res, next) { ... }) + * // error handler + * app.use(function (err, req, res, next) { ... }) + * + * They all internally delegate to the `router[method]` of the given application instance. + */ +// eslint-disable-next-line @typescript-eslint/ban-types, @typescript-eslint/no-explicit-any +function wrap(fn, method) { + var arity = fn.length; + switch (arity) { + case 2: { + return function (req, res) { + var transaction = res.__sentry_transaction; + if (transaction) { + var span_1 = transaction.startChild({ + description: fn.name, + op: "middleware." + method, + }); + res.once('finish', function () { + span_1.finish(); + }); + } + return fn.call(this, req, res); + }; + } + case 3: { + return function (req, res, next) { + var _a; + var transaction = res.__sentry_transaction; + var span = (_a = transaction) === null || _a === void 0 ? void 0 : _a.startChild({ + description: fn.name, + op: "middleware." + method, + }); + fn.call(this, req, res, function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + next.call.apply(next, tslib_1.__spread([this], args)); + }); + }; + } + case 4: { + return function (err, req, res, next) { + var _a; + var transaction = res.__sentry_transaction; + var span = (_a = transaction) === null || _a === void 0 ? void 0 : _a.startChild({ + description: fn.name, + op: "middleware." + method, + }); + fn.call(this, err, req, res, function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + next.call.apply(next, tslib_1.__spread([this], args)); + }); + }; + } + default: { + throw new Error("Express middleware takes 2-4 arguments. Got: " + arity); + } } - }; } - - -/***/ }), - -/***/ 15295: -/***/ ((module) => { - -module.exports = defer; - /** - * Runs provided function on next iteration of the event loop + * Takes all the function arguments passed to the original `app` or `router` method, eg. `app.use` or `router.use` + * and wraps every function, as well as array of functions with a call to our `wrap` method. + * We have to take care of the arrays as well as iterate over all of the arguments, + * as `app.use` can accept middlewares in few various forms. * - * @param {function} fn - function to run + * app.use([], ) + * app.use([], , ...) + * app.use([], ...[]) */ -function defer(fn) -{ - var nextTick = typeof setImmediate == 'function' - ? setImmediate - : ( - typeof process == 'object' && typeof process.nextTick == 'function' - ? process.nextTick - : null - ); - - if (nextTick) - { - nextTick(fn); - } - else - { - setTimeout(fn, 0); - } +function wrapMiddlewareArgs(args, method) { + return args.map(function (arg) { + if (typeof arg === 'function') { + return wrap(arg, method); + } + if (Array.isArray(arg)) { + return arg.map(function (a) { + if (typeof a === 'function') { + return wrap(a, method); + } + return a; + }); + } + return arg; + }); } - - -/***/ }), - -/***/ 9023: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var async = __nccwpck_require__(72794) - , abort = __nccwpck_require__(1700) - ; - -// API -module.exports = iterate; - /** - * Iterates over each job object - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {object} state - current job status - * @param {function} callback - invoked when all elements processed + * Patches original router to utilize our tracing functionality */ -function iterate(list, iterator, state, callback) -{ - // store current index - var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; - - state.jobs[key] = runJob(iterator, key, list[key], function(error, output) - { - // don't repeat yourself - // skip secondary callbacks - if (!(key in state.jobs)) - { - return; - } - - // clean up jobs - delete state.jobs[key]; - - if (error) - { - // don't process rest of the results - // stop still active jobs - // and reset the list - abort(state); - } - else - { - state.results[key] = output; - } - - // return salvaged results - callback(error, state.results); - }); +function patchMiddleware(router, method) { + var originalCallback = router[method]; + router[method] = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + return originalCallback.call.apply(originalCallback, tslib_1.__spread([this], wrapMiddlewareArgs(args, method))); + }; + return router; } - /** - * Runs iterator over provided job element - * - * @param {function} iterator - iterator to invoke - * @param {string|number} key - key/index of the element in the list of jobs - * @param {mixed} item - job description - * @param {function} callback - invoked after iterator is done with the job - * @returns {function|mixed} - job abort function or something else + * Patches original router methods */ -function runJob(iterator, key, item, callback) -{ - var aborter; +function instrumentMiddlewares(router, methods) { + if (methods === void 0) { methods = []; } + methods.forEach(function (method) { return patchMiddleware(router, method); }); +} +//# sourceMappingURL=express.js.map - // allow shortcut if iterator expects only two arguments - if (iterator.length == 2) - { - aborter = iterator(item, async(callback)); - } - // otherwise go with full three arguments - else - { - aborter = iterator(item, key, async(callback)); - } +/***/ }), - return aborter; -} +/***/ 28502: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var express_1 = __nccwpck_require__(96221); +exports.Express = express_1.Express; +var postgres_1 = __nccwpck_require__(31931); +exports.Postgres = postgres_1.Postgres; +var mysql_1 = __nccwpck_require__(67082); +exports.Mysql = mysql_1.Mysql; +var mongo_1 = __nccwpck_require__(22606); +exports.Mongo = mongo_1.Mongo; +//# sourceMappingURL=index.js.map /***/ }), -/***/ 42474: -/***/ ((module) => { +/***/ 22606: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// API -module.exports = state; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var OPERATIONS = [ + 'aggregate', + 'bulkWrite', + 'countDocuments', + 'createIndex', + 'createIndexes', + 'deleteMany', + 'deleteOne', + 'distinct', + 'drop', + 'dropIndex', + 'dropIndexes', + 'estimatedDocumentCount', + 'find', + 'findOne', + 'findOneAndDelete', + 'findOneAndReplace', + 'findOneAndUpdate', + 'indexes', + 'indexExists', + 'indexInformation', + 'initializeOrderedBulkOp', + 'insertMany', + 'insertOne', + 'isCapped', + 'mapReduce', + 'options', + 'parallelCollectionScan', + 'rename', + 'replaceOne', + 'stats', + 'updateMany', + 'updateOne', +]; +// All of the operations above take `options` and `callback` as their final parameters, but some of them +// take additional parameters as well. For those operations, this is a map of +// { : [] }, as a way to know what to call the operation's +// positional arguments when we add them to the span's `data` object later +var OPERATION_SIGNATURES = { + // aggregate intentionally not included because `pipeline` arguments are too complex to serialize well + // see https://github.com/getsentry/sentry-javascript/pull/3102 + bulkWrite: ['operations'], + countDocuments: ['query'], + createIndex: ['fieldOrSpec'], + createIndexes: ['indexSpecs'], + deleteMany: ['filter'], + deleteOne: ['filter'], + distinct: ['key', 'query'], + dropIndex: ['indexName'], + find: ['query'], + findOne: ['query'], + findOneAndDelete: ['filter'], + findOneAndReplace: ['filter', 'replacement'], + findOneAndUpdate: ['filter', 'update'], + indexExists: ['indexes'], + insertMany: ['docs'], + insertOne: ['doc'], + mapReduce: ['map', 'reduce'], + rename: ['newName'], + replaceOne: ['filter', 'doc'], + updateMany: ['filter', 'update'], + updateOne: ['filter', 'update'], +}; +/** Tracing integration for mongo package */ +var Mongo = /** @class */ (function () { + /** + * @inheritDoc + */ + function Mongo(options) { + if (options === void 0) { options = {}; } + /** + * @inheritDoc + */ + this.name = Mongo.id; + this._operations = Array.isArray(options.operations) + ? options.operations + : OPERATIONS; + this._describeOperations = 'describeOperations' in options ? options.describeOperations : true; + this._useMongoose = !!options.useMongoose; + } + /** + * @inheritDoc + */ + Mongo.prototype.setupOnce = function (_, getCurrentHub) { + var moduleName = this._useMongoose ? 'mongoose' : 'mongodb'; + var pkg = utils_1.loadModule(moduleName); + if (!pkg) { + utils_1.logger.error("Mongo Integration was unable to require `" + moduleName + "` package."); + return; + } + this._instrumentOperations(pkg.Collection, this._operations, getCurrentHub); + }; + /** + * Patches original collection methods + */ + Mongo.prototype._instrumentOperations = function (collection, operations, getCurrentHub) { + var _this = this; + operations.forEach(function (operation) { return _this._patchOperation(collection, operation, getCurrentHub); }); + }; + /** + * Patches original collection to utilize our tracing functionality + */ + Mongo.prototype._patchOperation = function (collection, operation, getCurrentHub) { + if (!(operation in collection.prototype)) + return; + var getSpanContext = this._getSpanContextFromOperationArguments.bind(this); + utils_1.fill(collection.prototype, operation, function (orig) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var _a, _b, _c, _d; + var lastArg = args[args.length - 1]; + var scope = getCurrentHub().getScope(); + var parentSpan = (_a = scope) === null || _a === void 0 ? void 0 : _a.getSpan(); + // Check if the operation was passed a callback. (mapReduce requires a different check, as + // its (non-callback) arguments can also be functions.) + if (typeof lastArg !== 'function' || (operation === 'mapReduce' && args.length === 2)) { + var span_1 = (_b = parentSpan) === null || _b === void 0 ? void 0 : _b.startChild(getSpanContext(this, operation, args)); + var maybePromise = orig.call.apply(orig, tslib_1.__spread([this], args)); + if (utils_1.isThenable(maybePromise)) { + return maybePromise.then(function (res) { + var _a; + (_a = span_1) === null || _a === void 0 ? void 0 : _a.finish(); + return res; + }); + } + else { + (_c = span_1) === null || _c === void 0 ? void 0 : _c.finish(); + return maybePromise; + } + } + var span = (_d = parentSpan) === null || _d === void 0 ? void 0 : _d.startChild(getSpanContext(this, operation, args.slice(0, -1))); + return orig.call.apply(orig, tslib_1.__spread([this], args.slice(0, -1), [function (err, result) { + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + lastArg(err, result); + }])); + }; + }); + }; + /** + * Form a SpanContext based on the user input to a given operation. + */ + Mongo.prototype._getSpanContextFromOperationArguments = function (collection, operation, args) { + var data = { + collectionName: collection.collectionName, + dbName: collection.dbName, + namespace: collection.namespace, + }; + var spanContext = { + op: "db", + description: operation, + data: data, + }; + // If the operation takes no arguments besides `options` and `callback`, or if argument + // collection is disabled for this operation, just return early. + var signature = OPERATION_SIGNATURES[operation]; + var shouldDescribe = Array.isArray(this._describeOperations) + ? this._describeOperations.includes(operation) + : this._describeOperations; + if (!signature || !shouldDescribe) { + return spanContext; + } + try { + // Special case for `mapReduce`, as the only one accepting functions as arguments. + if (operation === 'mapReduce') { + var _a = tslib_1.__read(args, 2), map = _a[0], reduce = _a[1]; + data[signature[0]] = typeof map === 'string' ? map : map.name || ''; + data[signature[1]] = typeof reduce === 'string' ? reduce : reduce.name || ''; + } + else { + for (var i = 0; i < signature.length; i++) { + data[signature[i]] = JSON.stringify(args[i]); + } + } + } + catch (_oO) { + // no-empty + } + return spanContext; + }; + /** + * @inheritDoc + */ + Mongo.id = 'Mongo'; + return Mongo; +}()); +exports.Mongo = Mongo; +//# sourceMappingURL=mongo.js.map -/** - * Creates initial state object - * for iteration over list - * - * @param {array|object} list - list to iterate over - * @param {function|null} sortMethod - function to use for keys sort, - * or `null` to keep them as is - * @returns {object} - initial state object - */ -function state(list, sortMethod) -{ - var isNamedList = !Array.isArray(list) - , initState = - { - index : 0, - keyedList: isNamedList || sortMethod ? Object.keys(list) : null, - jobs : {}, - results : isNamedList ? {} : [], - size : isNamedList ? Object.keys(list).length : list.length +/***/ }), + +/***/ 67082: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var utils_1 = __nccwpck_require__(1620); +/** Tracing integration for node-mysql package */ +var Mysql = /** @class */ (function () { + function Mysql() { + /** + * @inheritDoc + */ + this.name = Mysql.id; } - ; + /** + * @inheritDoc + */ + Mysql.prototype.setupOnce = function (_, getCurrentHub) { + var pkg = utils_1.loadModule('mysql/lib/Connection.js'); + if (!pkg) { + utils_1.logger.error('Mysql Integration was unable to require `mysql` package.'); + return; + } + // The original function will have one of these signatures: + // function (callback) => void + // function (options, callback) => void + // function (options, values, callback) => void + utils_1.fill(pkg, 'createQuery', function (orig) { + return function (options, values, callback) { + var _a, _b; + var scope = getCurrentHub().getScope(); + var parentSpan = (_a = scope) === null || _a === void 0 ? void 0 : _a.getSpan(); + var span = (_b = parentSpan) === null || _b === void 0 ? void 0 : _b.startChild({ + description: typeof options === 'string' ? options : options.sql, + op: "db", + }); + if (typeof callback === 'function') { + return orig.call(this, options, values, function (err, result, fields) { + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + callback(err, result, fields); + }); + } + if (typeof values === 'function') { + return orig.call(this, options, function (err, result, fields) { + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + values(err, result, fields); + }); + } + return orig.call(this, options, values, callback); + }; + }); + }; + /** + * @inheritDoc + */ + Mysql.id = 'Mysql'; + return Mysql; +}()); +exports.Mysql = Mysql; +//# sourceMappingURL=mysql.js.map - if (sortMethod) - { - // sort array keys based on it's values - // sort object's keys just on own merit - initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) - { - return sortMethod(list[a], list[b]); - }); - } +/***/ }), - return initState; -} +/***/ 31931: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var utils_1 = __nccwpck_require__(1620); +/** Tracing integration for node-postgres package */ +var Postgres = /** @class */ (function () { + function Postgres() { + /** + * @inheritDoc + */ + this.name = Postgres.id; + } + /** + * @inheritDoc + */ + Postgres.prototype.setupOnce = function (_, getCurrentHub) { + var pkg = utils_1.loadModule('pg'); + if (!pkg) { + utils_1.logger.error('Postgres Integration was unable to require `pg` package.'); + return; + } + /** + * function (query, callback) => void + * function (query, params, callback) => void + * function (query) => Promise + * function (query, params) => Promise + * function (pg.Cursor) => pg.Cursor + */ + utils_1.fill(pkg.Client.prototype, 'query', function (orig) { + return function (config, values, callback) { + var _a, _b, _c; + var scope = getCurrentHub().getScope(); + var parentSpan = (_a = scope) === null || _a === void 0 ? void 0 : _a.getSpan(); + var span = (_b = parentSpan) === null || _b === void 0 ? void 0 : _b.startChild({ + description: typeof config === 'string' ? config : config.text, + op: "db", + }); + if (typeof callback === 'function') { + return orig.call(this, config, values, function (err, result) { + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + callback(err, result); + }); + } + if (typeof values === 'function') { + return orig.call(this, config, function (err, result) { + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + values(err, result); + }); + } + var rv = typeof values !== 'undefined' ? orig.call(this, config, values) : orig.call(this, config); + if (utils_1.isThenable(rv)) { + return rv.then(function (res) { + var _a; + (_a = span) === null || _a === void 0 ? void 0 : _a.finish(); + return res; + }); + } + (_c = span) === null || _c === void 0 ? void 0 : _c.finish(); + return rv; + }; + }); + }; + /** + * @inheritDoc + */ + Postgres.id = 'Postgres'; + return Postgres; +}()); +exports.Postgres = Postgres; +//# sourceMappingURL=postgres.js.map /***/ }), -/***/ 37942: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var abort = __nccwpck_require__(1700) - , async = __nccwpck_require__(72794) - ; - -// API -module.exports = terminator; +/***/ 64655: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var utils_1 = __nccwpck_require__(1620); +var spanstatus_1 = __nccwpck_require__(58522); /** - * Terminates jobs in the attached state context - * - * @this AsyncKitState# - * @param {function} callback - final callback to invoke after termination + * Keeps track of finished spans for a given transaction + * @internal + * @hideconstructor + * @hidden */ -function terminator(callback) -{ - if (!Object.keys(this.jobs).length) - { - return; - } - - // fast forward iteration index - this.index = this.size; - - // abort jobs - abort(this); - - // send back results we have so far - async(callback)(null, this.results); -} - - -/***/ }), - -/***/ 8210: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var iterate = __nccwpck_require__(9023) - , initState = __nccwpck_require__(42474) - , terminator = __nccwpck_require__(37942) - ; - -// Public API -module.exports = parallel; - +var SpanRecorder = /** @class */ (function () { + function SpanRecorder(maxlen) { + if (maxlen === void 0) { maxlen = 1000; } + this.spans = []; + this._maxlen = maxlen; + } + /** + * This is just so that we don't run out of memory while recording a lot + * of spans. At some point we just stop and flush out the start of the + * trace tree (i.e.the first n spans with the smallest + * start_timestamp). + */ + SpanRecorder.prototype.add = function (span) { + if (this.spans.length > this._maxlen) { + span.spanRecorder = undefined; + } + else { + this.spans.push(span); + } + }; + return SpanRecorder; +}()); +exports.SpanRecorder = SpanRecorder; /** - * Runs iterator over provided array elements in parallel - * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator + * Span contains all data about a span */ -function parallel(list, iterator, callback) -{ - var state = initState(list); +var Span = /** @class */ (function () { + /** + * You should never call the constructor manually, always use `Sentry.startTransaction()` + * or call `startChild()` on an existing span. + * @internal + * @hideconstructor + * @hidden + */ + function Span(spanContext) { + /** + * @inheritDoc + */ + this.traceId = utils_1.uuid4(); + /** + * @inheritDoc + */ + this.spanId = utils_1.uuid4().substring(16); + /** + * Timestamp in seconds when the span was created. + */ + this.startTimestamp = utils_1.timestampWithMs(); + /** + * @inheritDoc + */ + this.tags = {}; + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.data = {}; + if (!spanContext) { + return this; + } + if (spanContext.traceId) { + this.traceId = spanContext.traceId; + } + if (spanContext.spanId) { + this.spanId = spanContext.spanId; + } + if (spanContext.parentSpanId) { + this.parentSpanId = spanContext.parentSpanId; + } + // We want to include booleans as well here + if ('sampled' in spanContext) { + this.sampled = spanContext.sampled; + } + if (spanContext.op) { + this.op = spanContext.op; + } + if (spanContext.description) { + this.description = spanContext.description; + } + if (spanContext.data) { + this.data = spanContext.data; + } + if (spanContext.tags) { + this.tags = spanContext.tags; + } + if (spanContext.status) { + this.status = spanContext.status; + } + if (spanContext.startTimestamp) { + this.startTimestamp = spanContext.startTimestamp; + } + if (spanContext.endTimestamp) { + this.endTimestamp = spanContext.endTimestamp; + } + } + /** + * @inheritDoc + * @deprecated + */ + Span.prototype.child = function (spanContext) { + return this.startChild(spanContext); + }; + /** + * @inheritDoc + */ + Span.prototype.startChild = function (spanContext) { + var childSpan = new Span(tslib_1.__assign(tslib_1.__assign({}, spanContext), { parentSpanId: this.spanId, sampled: this.sampled, traceId: this.traceId })); + childSpan.spanRecorder = this.spanRecorder; + if (childSpan.spanRecorder) { + childSpan.spanRecorder.add(childSpan); + } + childSpan.transaction = this.transaction; + return childSpan; + }; + /** + * @inheritDoc + */ + Span.prototype.setTag = function (key, value) { + var _a; + this.tags = tslib_1.__assign(tslib_1.__assign({}, this.tags), (_a = {}, _a[key] = value, _a)); + return this; + }; + /** + * @inheritDoc + */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/explicit-module-boundary-types + Span.prototype.setData = function (key, value) { + var _a; + this.data = tslib_1.__assign(tslib_1.__assign({}, this.data), (_a = {}, _a[key] = value, _a)); + return this; + }; + /** + * @inheritDoc + */ + Span.prototype.setStatus = function (value) { + this.status = value; + return this; + }; + /** + * @inheritDoc + */ + Span.prototype.setHttpStatus = function (httpStatus) { + this.setTag('http.status_code', String(httpStatus)); + var spanStatus = spanstatus_1.SpanStatus.fromHttpCode(httpStatus); + if (spanStatus !== spanstatus_1.SpanStatus.UnknownError) { + this.setStatus(spanStatus); + } + return this; + }; + /** + * @inheritDoc + */ + Span.prototype.isSuccess = function () { + return this.status === spanstatus_1.SpanStatus.Ok; + }; + /** + * @inheritDoc + */ + Span.prototype.finish = function (endTimestamp) { + this.endTimestamp = typeof endTimestamp === 'number' ? endTimestamp : utils_1.timestampWithMs(); + }; + /** + * @inheritDoc + */ + Span.prototype.toTraceparent = function () { + var sampledString = ''; + if (this.sampled !== undefined) { + sampledString = this.sampled ? '-1' : '-0'; + } + return this.traceId + "-" + this.spanId + sampledString; + }; + /** + * @inheritDoc + */ + Span.prototype.toContext = function () { + return utils_1.dropUndefinedKeys({ + data: this.data, + description: this.description, + endTimestamp: this.endTimestamp, + op: this.op, + parentSpanId: this.parentSpanId, + sampled: this.sampled, + spanId: this.spanId, + startTimestamp: this.startTimestamp, + status: this.status, + tags: this.tags, + traceId: this.traceId, + }); + }; + /** + * @inheritDoc + */ + Span.prototype.updateWithContext = function (spanContext) { + var _a, _b, _c, _d, _e; + this.data = (_a = spanContext.data, (_a !== null && _a !== void 0 ? _a : {})); + this.description = spanContext.description; + this.endTimestamp = spanContext.endTimestamp; + this.op = spanContext.op; + this.parentSpanId = spanContext.parentSpanId; + this.sampled = spanContext.sampled; + this.spanId = (_b = spanContext.spanId, (_b !== null && _b !== void 0 ? _b : this.spanId)); + this.startTimestamp = (_c = spanContext.startTimestamp, (_c !== null && _c !== void 0 ? _c : this.startTimestamp)); + this.status = spanContext.status; + this.tags = (_d = spanContext.tags, (_d !== null && _d !== void 0 ? _d : {})); + this.traceId = (_e = spanContext.traceId, (_e !== null && _e !== void 0 ? _e : this.traceId)); + return this; + }; + /** + * @inheritDoc + */ + Span.prototype.getTraceContext = function () { + return utils_1.dropUndefinedKeys({ + data: Object.keys(this.data).length > 0 ? this.data : undefined, + description: this.description, + op: this.op, + parent_span_id: this.parentSpanId, + span_id: this.spanId, + status: this.status, + tags: Object.keys(this.tags).length > 0 ? this.tags : undefined, + trace_id: this.traceId, + }); + }; + /** + * @inheritDoc + */ + Span.prototype.toJSON = function () { + return utils_1.dropUndefinedKeys({ + data: Object.keys(this.data).length > 0 ? this.data : undefined, + description: this.description, + op: this.op, + parent_span_id: this.parentSpanId, + span_id: this.spanId, + start_timestamp: this.startTimestamp, + status: this.status, + tags: Object.keys(this.tags).length > 0 ? this.tags : undefined, + timestamp: this.endTimestamp, + trace_id: this.traceId, + }); + }; + return Span; +}()); +exports.Span = Span; +//# sourceMappingURL=span.js.map - while (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, function(error, result) - { - if (error) - { - callback(error, result); - return; - } +/***/ }), - // looks like it's the last one - if (Object.keys(state.jobs).length === 0) - { - callback(null, state.results); - return; - } - }); +/***/ 58522: +/***/ ((__unused_webpack_module, exports) => { - state.index++; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** The status of an Span. */ +// eslint-disable-next-line import/export +var SpanStatus; +(function (SpanStatus) { + /** The operation completed successfully. */ + SpanStatus["Ok"] = "ok"; + /** Deadline expired before operation could complete. */ + SpanStatus["DeadlineExceeded"] = "deadline_exceeded"; + /** 401 Unauthorized (actually does mean unauthenticated according to RFC 7235) */ + SpanStatus["Unauthenticated"] = "unauthenticated"; + /** 403 Forbidden */ + SpanStatus["PermissionDenied"] = "permission_denied"; + /** 404 Not Found. Some requested entity (file or directory) was not found. */ + SpanStatus["NotFound"] = "not_found"; + /** 429 Too Many Requests */ + SpanStatus["ResourceExhausted"] = "resource_exhausted"; + /** Client specified an invalid argument. 4xx. */ + SpanStatus["InvalidArgument"] = "invalid_argument"; + /** 501 Not Implemented */ + SpanStatus["Unimplemented"] = "unimplemented"; + /** 503 Service Unavailable */ + SpanStatus["Unavailable"] = "unavailable"; + /** Other/generic 5xx. */ + SpanStatus["InternalError"] = "internal_error"; + /** Unknown. Any non-standard HTTP status code. */ + SpanStatus["UnknownError"] = "unknown_error"; + /** The operation was cancelled (typically by the user). */ + SpanStatus["Cancelled"] = "cancelled"; + /** Already exists (409) */ + SpanStatus["AlreadyExists"] = "already_exists"; + /** Operation was rejected because the system is not in a state required for the operation's */ + SpanStatus["FailedPrecondition"] = "failed_precondition"; + /** The operation was aborted, typically due to a concurrency issue. */ + SpanStatus["Aborted"] = "aborted"; + /** Operation was attempted past the valid range. */ + SpanStatus["OutOfRange"] = "out_of_range"; + /** Unrecoverable data loss or corruption */ + SpanStatus["DataLoss"] = "data_loss"; +})(SpanStatus = exports.SpanStatus || (exports.SpanStatus = {})); +// eslint-disable-next-line @typescript-eslint/no-namespace, import/export +(function (SpanStatus) { + /** + * Converts a HTTP status code into a {@link SpanStatus}. + * + * @param httpStatus The HTTP response status code. + * @returns The span status or {@link SpanStatus.UnknownError}. + */ + function fromHttpCode(httpStatus) { + if (httpStatus < 400) { + return SpanStatus.Ok; + } + if (httpStatus >= 400 && httpStatus < 500) { + switch (httpStatus) { + case 401: + return SpanStatus.Unauthenticated; + case 403: + return SpanStatus.PermissionDenied; + case 404: + return SpanStatus.NotFound; + case 409: + return SpanStatus.AlreadyExists; + case 413: + return SpanStatus.FailedPrecondition; + case 429: + return SpanStatus.ResourceExhausted; + default: + return SpanStatus.InvalidArgument; + } + } + if (httpStatus >= 500 && httpStatus < 600) { + switch (httpStatus) { + case 501: + return SpanStatus.Unimplemented; + case 503: + return SpanStatus.Unavailable; + case 504: + return SpanStatus.DeadlineExceeded; + default: + return SpanStatus.InternalError; + } + } + return SpanStatus.UnknownError; + } + SpanStatus.fromHttpCode = fromHttpCode; +})(SpanStatus = exports.SpanStatus || (exports.SpanStatus = {})); +//# sourceMappingURL=spanstatus.js.map - return terminator.bind(state, callback); -} +/***/ }), +/***/ 8186: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var hub_1 = __nccwpck_require__(6393); +var utils_1 = __nccwpck_require__(1620); +var span_1 = __nccwpck_require__(64655); +/** JSDoc */ +var Transaction = /** @class */ (function (_super) { + tslib_1.__extends(Transaction, _super); + /** + * This constructor should never be called manually. Those instrumenting tracing should use + * `Sentry.startTransaction()`, and internal methods should use `hub.startTransaction()`. + * @internal + * @hideconstructor + * @hidden + */ + function Transaction(transactionContext, hub) { + var _this = _super.call(this, transactionContext) || this; + _this._measurements = {}; + /** + * The reference to the current hub. + */ + _this._hub = hub_1.getCurrentHub(); + if (utils_1.isInstanceOf(hub, hub_1.Hub)) { + _this._hub = hub; + } + _this.name = transactionContext.name || ''; + _this.metadata = transactionContext.metadata || {}; + _this._trimEnd = transactionContext.trimEnd; + // this is because transactions are also spans, and spans have a transaction pointer + _this.transaction = _this; + return _this; + } + /** + * JSDoc + */ + Transaction.prototype.setName = function (name) { + this.name = name; + }; + /** + * Attaches SpanRecorder to the span itself + * @param maxlen maximum number of spans that can be recorded + */ + Transaction.prototype.initSpanRecorder = function (maxlen) { + if (maxlen === void 0) { maxlen = 1000; } + if (!this.spanRecorder) { + this.spanRecorder = new span_1.SpanRecorder(maxlen); + } + this.spanRecorder.add(this); + }; + /** + * Set observed measurements for this transaction. + * @hidden + */ + Transaction.prototype.setMeasurements = function (measurements) { + this._measurements = tslib_1.__assign({}, measurements); + }; + /** + * Set metadata for this transaction. + * @hidden + */ + Transaction.prototype.setMetadata = function (newMetadata) { + this.metadata = tslib_1.__assign(tslib_1.__assign({}, this.metadata), newMetadata); + }; + /** + * @inheritDoc + */ + Transaction.prototype.finish = function (endTimestamp) { + var _this = this; + // This transaction is already finished, so we should not flush it again. + if (this.endTimestamp !== undefined) { + return undefined; + } + if (!this.name) { + utils_1.logger.warn('Transaction has no name, falling back to ``.'); + this.name = ''; + } + // just sets the end timestamp + _super.prototype.finish.call(this, endTimestamp); + if (this.sampled !== true) { + // At this point if `sampled !== true` we want to discard the transaction. + utils_1.logger.log('[Tracing] Discarding transaction because its trace was not chosen to be sampled.'); + return undefined; + } + var finishedSpans = this.spanRecorder ? this.spanRecorder.spans.filter(function (s) { return s !== _this && s.endTimestamp; }) : []; + if (this._trimEnd && finishedSpans.length > 0) { + this.endTimestamp = finishedSpans.reduce(function (prev, current) { + if (prev.endTimestamp && current.endTimestamp) { + return prev.endTimestamp > current.endTimestamp ? prev : current; + } + return prev; + }).endTimestamp; + } + var transaction = { + contexts: { + trace: this.getTraceContext(), + }, + spans: finishedSpans, + start_timestamp: this.startTimestamp, + tags: this.tags, + timestamp: this.endTimestamp, + transaction: this.name, + type: 'transaction', + debug_meta: this.metadata, + }; + var hasMeasurements = Object.keys(this._measurements).length > 0; + if (hasMeasurements) { + utils_1.logger.log('[Measurements] Adding measurements to transaction', JSON.stringify(this._measurements, undefined, 2)); + transaction.measurements = this._measurements; + } + utils_1.logger.log("[Tracing] Finishing " + this.op + " transaction: " + this.name + "."); + return this._hub.captureEvent(transaction); + }; + /** + * @inheritDoc + */ + Transaction.prototype.toContext = function () { + var spanContext = _super.prototype.toContext.call(this); + return utils_1.dropUndefinedKeys(tslib_1.__assign(tslib_1.__assign({}, spanContext), { name: this.name, trimEnd: this._trimEnd })); + }; + /** + * @inheritDoc + */ + Transaction.prototype.updateWithContext = function (transactionContext) { + var _a; + _super.prototype.updateWithContext.call(this, transactionContext); + this.name = (_a = transactionContext.name, (_a !== null && _a !== void 0 ? _a : '')); + this._trimEnd = transactionContext.trimEnd; + return this; + }; + return Transaction; +}(span_1.Span)); +exports.Transaction = Transaction; +//# sourceMappingURL=transaction.js.map /***/ }), -/***/ 50445: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var serialOrdered = __nccwpck_require__(3578); - -// Public API -module.exports = serial; +/***/ 31386: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var hub_1 = __nccwpck_require__(6393); +exports.TRACEPARENT_REGEXP = new RegExp('^[ \\t]*' + // whitespace + '([0-9a-f]{32})?' + // trace_id + '-?([0-9a-f]{16})?' + // span_id + '-?([01])?' + // sampled + '[ \\t]*$'); /** - * Runs iterator over provided array elements in series + * Determines if tracing is currently enabled. * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator + * Tracing is enabled when at least one of `tracesSampleRate` and `tracesSampler` is defined in the SDK config. */ -function serial(list, iterator, callback) -{ - return serialOrdered(list, iterator, null, callback); +function hasTracingEnabled(options) { + if (options === void 0) { options = (_a = hub_1.getCurrentHub() + .getClient()) === null || _a === void 0 ? void 0 : _a.getOptions(); } + var _a; + if (!options) { + return false; + } + return 'tracesSampleRate' in options || 'tracesSampler' in options; } - - -/***/ }), - -/***/ 3578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var iterate = __nccwpck_require__(9023) - , initState = __nccwpck_require__(42474) - , terminator = __nccwpck_require__(37942) - ; - -// Public API -module.exports = serialOrdered; -// sorting helpers -module.exports.ascending = ascending; -module.exports.descending = descending; - +exports.hasTracingEnabled = hasTracingEnabled; /** - * Runs iterator over provided sorted array elements in series + * Extract transaction context data from a `sentry-trace` header. * - * @param {array|object} list - array or object (named list) to iterate over - * @param {function} iterator - iterator to run - * @param {function} sortMethod - custom sort function - * @param {function} callback - invoked when all elements processed - * @returns {function} - jobs terminator + * @param traceparent Traceparent string + * + * @returns Object containing data from the header, or undefined if traceparent string is malformed */ -function serialOrdered(list, iterator, sortMethod, callback) -{ - var state = initState(list, sortMethod); - - iterate(list, iterator, state, function iteratorHandler(error, result) - { - if (error) - { - callback(error, result); - return; - } - - state.index++; - - // are we there yet? - if (state.index < (state['keyedList'] || list).length) - { - iterate(list, iterator, state, iteratorHandler); - return; +function extractTraceparentData(traceparent) { + var matches = traceparent.match(exports.TRACEPARENT_REGEXP); + if (matches) { + var parentSampled = void 0; + if (matches[3] === '1') { + parentSampled = true; + } + else if (matches[3] === '0') { + parentSampled = false; + } + return { + traceId: matches[1], + parentSampled: parentSampled, + parentSpanId: matches[2], + }; } - - // done here - callback(null, state.results); - }); - - return terminator.bind(state, callback); + return undefined; } - -/* - * -- Sort methods - */ - +exports.extractTraceparentData = extractTraceparentData; +/** Grabs active transaction off scope, if any */ +function getActiveTransaction(hub) { + if (hub === void 0) { hub = hub_1.getCurrentHub(); } + var _a, _b; + return (_b = (_a = hub) === null || _a === void 0 ? void 0 : _a.getScope()) === null || _b === void 0 ? void 0 : _b.getTransaction(); +} +exports.getActiveTransaction = getActiveTransaction; /** - * sort helper to sort array elements in ascending order - * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result + * Converts from milliseconds to seconds + * @param time time in ms */ -function ascending(a, b) -{ - return a < b ? -1 : a > b ? 1 : 0; +function msToSec(time) { + return time / 1000; } - +exports.msToSec = msToSec; /** - * sort helper to sort array elements in descending order - * - * @param {mixed} a - an item to compare - * @param {mixed} b - an item to compare - * @returns {number} - comparison result + * Converts from seconds to milliseconds + * @param time time in seconds */ -function descending(a, b) -{ - return -1 * ascending(a, b); +function secToMs(time) { + return time * 1000; } - +exports.secToMs = secToMs; +// so it can be used in manual instrumentation without necessitating a hard dependency on @sentry/utils +var utils_1 = __nccwpck_require__(1620); +exports.stripUrlQueryAndFragment = utils_1.stripUrlQueryAndFragment; +//# sourceMappingURL=utils.js.map /***/ }), -/***/ 86950: -/***/ ((module) => { +/***/ 83789: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var loglevel_1 = __nccwpck_require__(6853); +exports.LogLevel = loglevel_1.LogLevel; +var session_1 = __nccwpck_require__(84954); +exports.SessionStatus = session_1.SessionStatus; +exports.RequestSessionStatus = session_1.RequestSessionStatus; +var severity_1 = __nccwpck_require__(94124); +exports.Severity = severity_1.Severity; +var status_1 = __nccwpck_require__(61277); +exports.Status = status_1.Status; +var transaction_1 = __nccwpck_require__(47540); +exports.TransactionSamplingMethod = transaction_1.TransactionSamplingMethod; +//# sourceMappingURL=index.js.map +/***/ }), -/* global SharedArrayBuffer, Atomics */ +/***/ 6853: +/***/ ((__unused_webpack_module, exports) => { -if (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') { - const nil = new Int32Array(new SharedArrayBuffer(4)) +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** Console logging verbosity for the SDK. */ +var LogLevel; +(function (LogLevel) { + /** No logs will be generated. */ + LogLevel[LogLevel["None"] = 0] = "None"; + /** Only SDK internal errors will be logged. */ + LogLevel[LogLevel["Error"] = 1] = "Error"; + /** Information useful for debugging the SDK will be logged. */ + LogLevel[LogLevel["Debug"] = 2] = "Debug"; + /** All SDK actions will be logged. */ + LogLevel[LogLevel["Verbose"] = 3] = "Verbose"; +})(LogLevel = exports.LogLevel || (exports.LogLevel = {})); +//# sourceMappingURL=loglevel.js.map - function sleep (ms) { - // also filters out NaN, non-number types, including empty strings, but allows bigints - const valid = ms > 0 && ms < Infinity - if (valid === false) { - if (typeof ms !== 'number' && typeof ms !== 'bigint') { - throw TypeError('sleep: ms must be a number') - } - throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') - } +/***/ }), - Atomics.wait(nil, 0, 0, Number(ms)) - } - module.exports = sleep -} else { +/***/ 84954: +/***/ ((__unused_webpack_module, exports) => { - function sleep (ms) { - // also filters out NaN, non-number types, including empty strings, but allows bigints - const valid = ms > 0 && ms < Infinity - if (valid === false) { - if (typeof ms !== 'number' && typeof ms !== 'bigint') { - throw TypeError('sleep: ms must be a number') - } - throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') - } - const target = Date.now() + Number(ms) - while (target > Date.now()){} - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Session Status + */ +var SessionStatus; +(function (SessionStatus) { + /** JSDoc */ + SessionStatus["Ok"] = "ok"; + /** JSDoc */ + SessionStatus["Exited"] = "exited"; + /** JSDoc */ + SessionStatus["Crashed"] = "crashed"; + /** JSDoc */ + SessionStatus["Abnormal"] = "abnormal"; +})(SessionStatus = exports.SessionStatus || (exports.SessionStatus = {})); +var RequestSessionStatus; +(function (RequestSessionStatus) { + /** JSDoc */ + RequestSessionStatus["Ok"] = "ok"; + /** JSDoc */ + RequestSessionStatus["Errored"] = "errored"; + /** JSDoc */ + RequestSessionStatus["Crashed"] = "crashed"; +})(RequestSessionStatus = exports.RequestSessionStatus || (exports.RequestSessionStatus = {})); +//# sourceMappingURL=session.js.map - module.exports = sleep +/***/ }), -} +/***/ 94124: +/***/ ((__unused_webpack_module, exports) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** JSDoc */ +// eslint-disable-next-line import/export +var Severity; +(function (Severity) { + /** JSDoc */ + Severity["Fatal"] = "fatal"; + /** JSDoc */ + Severity["Error"] = "error"; + /** JSDoc */ + Severity["Warning"] = "warning"; + /** JSDoc */ + Severity["Log"] = "log"; + /** JSDoc */ + Severity["Info"] = "info"; + /** JSDoc */ + Severity["Debug"] = "debug"; + /** JSDoc */ + Severity["Critical"] = "critical"; +})(Severity = exports.Severity || (exports.Severity = {})); +// eslint-disable-next-line @typescript-eslint/no-namespace, import/export +(function (Severity) { + /** + * Converts a string-based level into a {@link Severity}. + * + * @param level string representation of Severity + * @returns Severity + */ + function fromString(level) { + switch (level) { + case 'debug': + return Severity.Debug; + case 'info': + return Severity.Info; + case 'warn': + case 'warning': + return Severity.Warning; + case 'error': + return Severity.Error; + case 'fatal': + return Severity.Fatal; + case 'critical': + return Severity.Critical; + case 'log': + default: + return Severity.Log; + } + } + Severity.fromString = fromString; +})(Severity = exports.Severity || (exports.Severity = {})); +//# sourceMappingURL=severity.js.map /***/ }), -/***/ 83682: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var register = __nccwpck_require__(44670) -var addHook = __nccwpck_require__(5549) -var removeHook = __nccwpck_require__(6819) - -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind -var bindable = bind.bind(bind) +/***/ 61277: +/***/ ((__unused_webpack_module, exports) => { -function bindApi (hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) - hook.api = { remove: removeHookRef } - hook.remove = removeHookRef +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** The status of an event. */ +// eslint-disable-next-line import/export +var Status; +(function (Status) { + /** The status could not be determined. */ + Status["Unknown"] = "unknown"; + /** The event was skipped due to configuration or callbacks. */ + Status["Skipped"] = "skipped"; + /** The event was sent to Sentry successfully. */ + Status["Success"] = "success"; + /** The client is currently rate limited and will try again later. */ + Status["RateLimit"] = "rate_limit"; + /** The event could not be processed. */ + Status["Invalid"] = "invalid"; + /** A server-side error ocurred during submission. */ + Status["Failed"] = "failed"; +})(Status = exports.Status || (exports.Status = {})); +// eslint-disable-next-line @typescript-eslint/no-namespace, import/export +(function (Status) { + /** + * Converts a HTTP status code into a {@link Status}. + * + * @param code The HTTP response status code. + * @returns The send status or {@link Status.Unknown}. + */ + function fromHttpCode(code) { + if (code >= 200 && code < 300) { + return Status.Success; + } + if (code === 429) { + return Status.RateLimit; + } + if (code >= 400 && code < 500) { + return Status.Invalid; + } + if (code >= 500) { + return Status.Failed; + } + return Status.Unknown; + } + Status.fromHttpCode = fromHttpCode; +})(Status = exports.Status || (exports.Status = {})); +//# sourceMappingURL=status.js.map - ;['before', 'error', 'after', 'wrap'].forEach(function (kind) { - var args = name ? [state, kind, name] : [state, kind] - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args) - }) -} +/***/ }), -function HookSingular () { - var singularHookName = 'h' - var singularHookState = { - registry: {} - } - var singularHook = register.bind(null, singularHookState, singularHookName) - bindApi(singularHook, singularHookState, singularHookName) - return singularHook -} +/***/ 47540: +/***/ ((__unused_webpack_module, exports) => { -function HookCollection () { - var state = { - registry: {} - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +var TransactionSamplingMethod; +(function (TransactionSamplingMethod) { + TransactionSamplingMethod["Explicit"] = "explicitly_set"; + TransactionSamplingMethod["Sampler"] = "client_sampler"; + TransactionSamplingMethod["Rate"] = "client_rate"; + TransactionSamplingMethod["Inheritance"] = "inheritance"; +})(TransactionSamplingMethod = exports.TransactionSamplingMethod || (exports.TransactionSamplingMethod = {})); +//# sourceMappingURL=transaction.js.map - var hook = register.bind(null, state) - bindApi(hook, state) +/***/ }), - return hook -} +/***/ 58343: +/***/ ((__unused_webpack_module, exports) => { -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() +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Consumes the promise and logs the error when it rejects. + * @param promise A promise to forget. + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function forget(promise) { + void promise.then(null, function (e) { + // TODO: Use a better logging mechanism + // eslint-disable-next-line no-console + console.error(e); + }); } - -Hook.Singular = HookSingular.bind() -Hook.Collection = HookCollection.bind() - -module.exports = Hook -// expose constructors as a named property for TypeScript -module.exports.Hook = Hook -module.exports.Singular = Hook.Singular -module.exports.Collection = Hook.Collection - +exports.forget = forget; +//# sourceMappingURL=async.js.map /***/ }), -/***/ 5549: -/***/ ((module) => { - -module.exports = addHook - -function addHook (state, kind, name, hook) { - var orig = hook - if (!state.registry[name]) { - state.registry[name] = [] - } +/***/ 30597: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (kind === 'before') { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)) +Object.defineProperty(exports, "__esModule", ({ value: true })); +var is_1 = __nccwpck_require__(92757); +/** + * Given a child DOM element, returns a query-selector statement describing that + * and its ancestors + * e.g. [HTMLElement] => body > div > input#foo.btn[name=baz] + * @returns generated DOM path + */ +function htmlTreeAsString(elem, keyAttrs) { + // try/catch both: + // - accessing event.target (see getsentry/raven-js#838, #768) + // - `htmlTreeAsString` because it's complex, and just accessing the DOM incorrectly + // - can throw an exception in some circumstances. + try { + var currentElem = elem; + var MAX_TRAVERSE_HEIGHT = 5; + var MAX_OUTPUT_LEN = 80; + var out = []; + var height = 0; + var len = 0; + var separator = ' > '; + var sepLength = separator.length; + var nextStr = void 0; + // eslint-disable-next-line no-plusplus + while (currentElem && height++ < MAX_TRAVERSE_HEIGHT) { + nextStr = _htmlElementAsString(currentElem, keyAttrs); + // bail out if + // - nextStr is the 'html' element + // - the length of the string that would be created exceeds MAX_OUTPUT_LEN + // (ignore this limit if we are on the first iteration) + if (nextStr === 'html' || (height > 1 && len + out.length * sepLength + nextStr.length >= MAX_OUTPUT_LEN)) { + break; + } + out.push(nextStr); + len += nextStr.length; + currentElem = currentElem.parentNode; + } + return out.reverse().join(separator); } - } - - 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 - }) + catch (_oO) { + return ''; } - } - - if (kind === 'error') { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options) - }) +} +exports.htmlTreeAsString = htmlTreeAsString; +/** + * Returns a simple, query-selector representation of a DOM element + * e.g. [HTMLElement] => input#foo.btn[name=baz] + * @returns generated DOM path + */ +function _htmlElementAsString(el, keyAttrs) { + var _a, _b; + var elem = el; + var out = []; + var className; + var classes; + var key; + var attr; + var i; + if (!elem || !elem.tagName) { + return ''; + } + out.push(elem.tagName.toLowerCase()); + // Pairs of attribute keys defined in `serializeAttribute` and their values on element. + var keyAttrPairs = ((_a = keyAttrs) === null || _a === void 0 ? void 0 : _a.length) ? keyAttrs.filter(function (keyAttr) { return elem.getAttribute(keyAttr); }).map(function (keyAttr) { return [keyAttr, elem.getAttribute(keyAttr)]; }) + : null; + if ((_b = keyAttrPairs) === null || _b === void 0 ? void 0 : _b.length) { + keyAttrPairs.forEach(function (keyAttrPair) { + out.push("[" + keyAttrPair[0] + "=\"" + keyAttrPair[1] + "\"]"); + }); + } + else { + if (elem.id) { + out.push("#" + elem.id); + } + // eslint-disable-next-line prefer-const + className = elem.className; + if (className && is_1.isString(className)) { + classes = className.split(/\s+/); + for (i = 0; i < classes.length; i++) { + out.push("." + classes[i]); + } + } + } + var allowedAttrs = ['type', 'name', 'title', 'alt']; + for (i = 0; i < allowedAttrs.length; i++) { + key = allowedAttrs[i]; + attr = elem.getAttribute(key); + if (attr) { + out.push("[" + key + "=\"" + attr + "\"]"); + } } - } - - state.registry[name].push({ - hook: hook, - orig: orig - }) + return out.join(''); } - +//# sourceMappingURL=browser.js.map /***/ }), -/***/ 44670: -/***/ ((module) => { - -module.exports = register - -function register (state, name, method, options) { - if (typeof method !== 'function') { - throw new Error('method for before hook must be a function') - } - - if (!options) { - options = {} - } - - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options) - }, method)() - } - - 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)() - }) -} +/***/ 3275: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var error_1 = __nccwpck_require__(66238); +/** Regular expression used to parse a Dsn. */ +var DSN_REGEX = /^(?:(\w+):)\/\/(?:(\w+)(?::(\w+))?@)([\w.-]+)(?::(\d+))?\/(.+)/; +/** Error message */ +var ERROR_MESSAGE = 'Invalid Dsn'; +/** The Sentry Dsn, identifying a Sentry instance and project. */ +var Dsn = /** @class */ (function () { + /** Creates a new Dsn component */ + function Dsn(from) { + if (typeof from === 'string') { + this._fromString(from); + } + else { + this._fromComponents(from); + } + this._validate(); + } + /** + * Renders the string representation of this Dsn. + * + * By default, this will render the public representation without the password + * component. To get the deprecated private representation, set `withPassword` + * to true. + * + * @param withPassword When set to true, the password will be included. + */ + Dsn.prototype.toString = function (withPassword) { + if (withPassword === void 0) { withPassword = false; } + var _a = this, host = _a.host, path = _a.path, pass = _a.pass, port = _a.port, projectId = _a.projectId, protocol = _a.protocol, publicKey = _a.publicKey; + return (protocol + "://" + publicKey + (withPassword && pass ? ":" + pass : '') + + ("@" + host + (port ? ":" + port : '') + "/" + (path ? path + "/" : path) + projectId)); + }; + /** Parses a string into this Dsn. */ + Dsn.prototype._fromString = function (str) { + var match = DSN_REGEX.exec(str); + if (!match) { + throw new error_1.SentryError(ERROR_MESSAGE); + } + var _a = tslib_1.__read(match.slice(1), 6), protocol = _a[0], publicKey = _a[1], _b = _a[2], pass = _b === void 0 ? '' : _b, host = _a[3], _c = _a[4], port = _c === void 0 ? '' : _c, lastPath = _a[5]; + var path = ''; + var projectId = lastPath; + var split = projectId.split('/'); + if (split.length > 1) { + path = split.slice(0, -1).join('/'); + projectId = split.pop(); + } + if (projectId) { + var projectMatch = projectId.match(/^\d+/); + if (projectMatch) { + projectId = projectMatch[0]; + } + } + this._fromComponents({ host: host, pass: pass, path: path, projectId: projectId, port: port, protocol: protocol, publicKey: publicKey }); + }; + /** Maps Dsn components into this instance. */ + Dsn.prototype._fromComponents = function (components) { + // TODO this is for backwards compatibility, and can be removed in a future version + if ('user' in components && !('publicKey' in components)) { + components.publicKey = components.user; + } + this.user = components.publicKey || ''; + this.protocol = components.protocol; + this.publicKey = components.publicKey || ''; + this.pass = components.pass || ''; + this.host = components.host; + this.port = components.port || ''; + this.path = components.path || ''; + this.projectId = components.projectId; + }; + /** Validates this Dsn and throws on error. */ + Dsn.prototype._validate = function () { + var _this = this; + ['protocol', 'publicKey', 'host', 'projectId'].forEach(function (component) { + if (!_this[component]) { + throw new error_1.SentryError(ERROR_MESSAGE + ": " + component + " missing"); + } + }); + if (!this.projectId.match(/^\d+$/)) { + throw new error_1.SentryError(ERROR_MESSAGE + ": Invalid projectId " + this.projectId); + } + if (this.protocol !== 'http' && this.protocol !== 'https') { + throw new error_1.SentryError(ERROR_MESSAGE + ": Invalid protocol " + this.protocol); + } + if (this.port && isNaN(parseInt(this.port, 10))) { + throw new error_1.SentryError(ERROR_MESSAGE + ": Invalid port " + this.port); + } + }; + return Dsn; +}()); +exports.Dsn = Dsn; +//# sourceMappingURL=dsn.js.map /***/ }), -/***/ 6819: -/***/ ((module) => { - -module.exports = removeHook - -function removeHook (state, name, method) { - if (!state.registry[name]) { - return - } - - var index = state.registry[name] - .map(function (registered) { return registered.orig }) - .indexOf(method) - - if (index === -1) { - return - } - - state.registry[name].splice(index, 1) -} +/***/ 66238: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var polyfill_1 = __nccwpck_require__(1243); +/** An error emitted by Sentry SDKs and related utilities. */ +var SentryError = /** @class */ (function (_super) { + tslib_1.__extends(SentryError, _super); + function SentryError(message) { + var _newTarget = this.constructor; + var _this = _super.call(this, message) || this; + _this.message = message; + _this.name = _newTarget.prototype.constructor.name; + polyfill_1.setPrototypeOf(_this, _newTarget.prototype); + return _this; + } + return SentryError; +}(Error)); +exports.SentryError = SentryError; +//# sourceMappingURL=error.js.map /***/ }), -/***/ 97076: -/***/ ((module, exports, __nccwpck_require__) => { - -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - * @private - */ - -var deprecate = __nccwpck_require__(18883)('body-parser') - -/** - * Cache of loaded parsers. - * @private - */ - -var parsers = Object.create(null) - -/** - * @typedef Parsers - * @type {function} - * @property {function} json - * @property {function} raw - * @property {function} text - * @property {function} urlencoded - */ - -/** - * Module exports. - * @type {Parsers} - */ - -exports = module.exports = deprecate.function(bodyParser, - 'bodyParser: use individual json/urlencoded middlewares') - -/** - * JSON parser. - * @public - */ +/***/ 1620: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Object.defineProperty(exports, "json", ({ - configurable: true, - enumerable: true, - get: createParserGetter('json') -})) +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +tslib_1.__exportStar(__nccwpck_require__(58343), exports); +tslib_1.__exportStar(__nccwpck_require__(30597), exports); +tslib_1.__exportStar(__nccwpck_require__(3275), exports); +tslib_1.__exportStar(__nccwpck_require__(66238), exports); +tslib_1.__exportStar(__nccwpck_require__(65474), exports); +tslib_1.__exportStar(__nccwpck_require__(92757), exports); +tslib_1.__exportStar(__nccwpck_require__(15577), exports); +tslib_1.__exportStar(__nccwpck_require__(49515), exports); +tslib_1.__exportStar(__nccwpck_require__(32154), exports); +tslib_1.__exportStar(__nccwpck_require__(16411), exports); +tslib_1.__exportStar(__nccwpck_require__(69249), exports); +tslib_1.__exportStar(__nccwpck_require__(39188), exports); +tslib_1.__exportStar(__nccwpck_require__(31811), exports); +tslib_1.__exportStar(__nccwpck_require__(5986), exports); +tslib_1.__exportStar(__nccwpck_require__(66538), exports); +tslib_1.__exportStar(__nccwpck_require__(88714), exports); +tslib_1.__exportStar(__nccwpck_require__(87833), exports); +tslib_1.__exportStar(__nccwpck_require__(1735), exports); +//# sourceMappingURL=index.js.map -/** - * Raw parser. - * @public - */ +/***/ }), -Object.defineProperty(exports, "raw", ({ - configurable: true, - enumerable: true, - get: createParserGetter('raw') -})) +/***/ 65474: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var is_1 = __nccwpck_require__(92757); +var logger_1 = __nccwpck_require__(15577); +var misc_1 = __nccwpck_require__(32154); +var object_1 = __nccwpck_require__(69249); +var stacktrace_1 = __nccwpck_require__(5986); +var supports_1 = __nccwpck_require__(88714); +var global = misc_1.getGlobalObject(); /** - * Text parser. - * @public + * Instrument native APIs to call handlers that can be used to create breadcrumbs, APM spans etc. + * - Console API + * - Fetch API + * - XHR API + * - History API + * - DOM API (click/typing) + * - Error API + * - UnhandledRejection API */ - -Object.defineProperty(exports, "text", ({ - configurable: true, - enumerable: true, - get: createParserGetter('text') -})) - +var handlers = {}; +var instrumented = {}; +/** Instruments given API */ +function instrument(type) { + if (instrumented[type]) { + return; + } + instrumented[type] = true; + switch (type) { + case 'console': + instrumentConsole(); + break; + case 'dom': + instrumentDOM(); + break; + case 'xhr': + instrumentXHR(); + break; + case 'fetch': + instrumentFetch(); + break; + case 'history': + instrumentHistory(); + break; + case 'error': + instrumentError(); + break; + case 'unhandledrejection': + instrumentUnhandledRejection(); + break; + default: + logger_1.logger.warn('unknown instrumentation type:', type); + } +} /** - * URL-encoded parser. - * @public + * Add handler that will be called when given type of instrumentation triggers. + * Use at your own risk, this might break without changelog notice, only used internally. + * @hidden */ - -Object.defineProperty(exports, "urlencoded", ({ - configurable: true, - enumerable: true, - get: createParserGetter('urlencoded') -})) - +function addInstrumentationHandler(handler) { + if (!handler || typeof handler.type !== 'string' || typeof handler.callback !== 'function') { + return; + } + handlers[handler.type] = handlers[handler.type] || []; + handlers[handler.type].push(handler.callback); + instrument(handler.type); +} +exports.addInstrumentationHandler = addInstrumentationHandler; +/** JSDoc */ +function triggerHandlers(type, data) { + var e_1, _a; + if (!type || !handlers[type]) { + return; + } + try { + for (var _b = tslib_1.__values(handlers[type] || []), _c = _b.next(); !_c.done; _c = _b.next()) { + var handler = _c.value; + try { + handler(data); + } + catch (e) { + logger_1.logger.error("Error while triggering instrumentation handler.\nType: " + type + "\nName: " + stacktrace_1.getFunctionName(handler) + "\nError: " + e); + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } +} +/** JSDoc */ +function instrumentConsole() { + if (!('console' in global)) { + return; + } + ['debug', 'info', 'warn', 'error', 'log', 'assert'].forEach(function (level) { + if (!(level in global.console)) { + return; + } + object_1.fill(global.console, level, function (originalConsoleLevel) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + triggerHandlers('console', { args: args, level: level }); + // this fails for some browsers. :( + if (originalConsoleLevel) { + Function.prototype.apply.call(originalConsoleLevel, global.console, args); + } + }; + }); + }); +} +/** JSDoc */ +function instrumentFetch() { + if (!supports_1.supportsNativeFetch()) { + return; + } + object_1.fill(global, 'fetch', function (originalFetch) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var handlerData = { + args: args, + fetchData: { + method: getFetchMethod(args), + url: getFetchUrl(args), + }, + startTimestamp: Date.now(), + }; + triggerHandlers('fetch', tslib_1.__assign({}, handlerData)); + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return originalFetch.apply(global, args).then(function (response) { + triggerHandlers('fetch', tslib_1.__assign(tslib_1.__assign({}, handlerData), { endTimestamp: Date.now(), response: response })); + return response; + }, function (error) { + triggerHandlers('fetch', tslib_1.__assign(tslib_1.__assign({}, handlerData), { endTimestamp: Date.now(), error: error })); + // NOTE: If you are a Sentry user, and you are seeing this stack frame, + // it means the sentry.javascript SDK caught an error invoking your application code. + // This is expected behavior and NOT indicative of a bug with sentry.javascript. + throw error; + }); + }; + }); +} +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/** Extract `method` from fetch call arguments */ +function getFetchMethod(fetchArgs) { + if (fetchArgs === void 0) { fetchArgs = []; } + if ('Request' in global && is_1.isInstanceOf(fetchArgs[0], Request) && fetchArgs[0].method) { + return String(fetchArgs[0].method).toUpperCase(); + } + if (fetchArgs[1] && fetchArgs[1].method) { + return String(fetchArgs[1].method).toUpperCase(); + } + return 'GET'; +} +/** Extract `url` from fetch call arguments */ +function getFetchUrl(fetchArgs) { + if (fetchArgs === void 0) { fetchArgs = []; } + if (typeof fetchArgs[0] === 'string') { + return fetchArgs[0]; + } + if ('Request' in global && is_1.isInstanceOf(fetchArgs[0], Request)) { + return fetchArgs[0].url; + } + return String(fetchArgs[0]); +} +/* eslint-enable @typescript-eslint/no-unsafe-member-access */ +/** JSDoc */ +function instrumentXHR() { + if (!('XMLHttpRequest' in global)) { + return; + } + // Poor man's implementation of ES6 `Map`, tracking and keeping in sync key and value separately. + var requestKeys = []; + var requestValues = []; + var xhrproto = XMLHttpRequest.prototype; + object_1.fill(xhrproto, 'open', function (originalOpen) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + // eslint-disable-next-line @typescript-eslint/no-this-alias + var xhr = this; + var url = args[1]; + xhr.__sentry_xhr__ = { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + method: is_1.isString(args[0]) ? args[0].toUpperCase() : args[0], + url: args[1], + }; + // if Sentry key appears in URL, don't capture it as a request + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (is_1.isString(url) && xhr.__sentry_xhr__.method === 'POST' && url.match(/sentry_key/)) { + xhr.__sentry_own_request__ = true; + } + var onreadystatechangeHandler = function () { + if (xhr.readyState === 4) { + try { + // touching statusCode in some platforms throws + // an exception + if (xhr.__sentry_xhr__) { + xhr.__sentry_xhr__.status_code = xhr.status; + } + } + catch (e) { + /* do nothing */ + } + try { + var requestPos = requestKeys.indexOf(xhr); + if (requestPos !== -1) { + // Make sure to pop both key and value to keep it in sync. + requestKeys.splice(requestPos); + var args_1 = requestValues.splice(requestPos)[0]; + if (xhr.__sentry_xhr__ && args_1[0] !== undefined) { + xhr.__sentry_xhr__.body = args_1[0]; + } + } + } + catch (e) { + /* do nothing */ + } + triggerHandlers('xhr', { + args: args, + endTimestamp: Date.now(), + startTimestamp: Date.now(), + xhr: xhr, + }); + } + }; + if ('onreadystatechange' in xhr && typeof xhr.onreadystatechange === 'function') { + object_1.fill(xhr, 'onreadystatechange', function (original) { + return function () { + var readyStateArgs = []; + for (var _i = 0; _i < arguments.length; _i++) { + readyStateArgs[_i] = arguments[_i]; + } + onreadystatechangeHandler(); + return original.apply(xhr, readyStateArgs); + }; + }); + } + else { + xhr.addEventListener('readystatechange', onreadystatechangeHandler); + } + return originalOpen.apply(xhr, args); + }; + }); + object_1.fill(xhrproto, 'send', function (originalSend) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + requestKeys.push(this); + requestValues.push(args); + triggerHandlers('xhr', { + args: args, + startTimestamp: Date.now(), + xhr: this, + }); + return originalSend.apply(this, args); + }; + }); +} +var lastHref; +/** JSDoc */ +function instrumentHistory() { + if (!supports_1.supportsHistory()) { + return; + } + var oldOnPopState = global.onpopstate; + global.onpopstate = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var to = global.location.href; + // keep track of the current URL state, as we always receive only the updated state + var from = lastHref; + lastHref = to; + triggerHandlers('history', { + from: from, + to: to, + }); + if (oldOnPopState) { + // Apparently this can throw in Firefox when incorrectly implemented plugin is installed. + // https://github.com/getsentry/sentry-javascript/issues/3344 + // https://github.com/bugsnag/bugsnag-js/issues/469 + try { + return oldOnPopState.apply(this, args); + } + catch (_oO) { + // no-empty + } + } + }; + /** @hidden */ + function historyReplacementFunction(originalHistoryFunction) { + return function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var url = args.length > 2 ? args[2] : undefined; + if (url) { + // coerce to string (this is what pushState does) + var from = lastHref; + var to = String(url); + // keep track of the current URL state, as we always receive only the updated state + lastHref = to; + triggerHandlers('history', { + from: from, + to: to, + }); + } + return originalHistoryFunction.apply(this, args); + }; + } + object_1.fill(global.history, 'pushState', historyReplacementFunction); + object_1.fill(global.history, 'replaceState', historyReplacementFunction); +} +var debounceDuration = 1000; +var debounceTimerID; +var lastCapturedEvent; /** - * Create a middleware to parse json and urlencoded bodies. - * - * @param {object} [options] - * @return {function} - * @deprecated - * @public + * Decide whether the current event should finish the debounce of previously captured one. + * @param previous previously captured event + * @param current event to be captured */ - -function bodyParser (options) { - var opts = {} - - // exclude type option - if (options) { - for (var prop in options) { - if (prop !== 'type') { - opts[prop] = options[prop] - } +function shouldShortcircuitPreviousDebounce(previous, current) { + // If there was no previous event, it should always be swapped for the new one. + if (!previous) { + return true; } - } - - var _urlencoded = exports.urlencoded(opts) - var _json = exports.json(opts) - - return function bodyParser (req, res, next) { - _json(req, res, function (err) { - if (err) return next(err) - _urlencoded(req, res, next) - }) - } + // If both events have different type, then user definitely performed two separate actions. e.g. click + keypress. + if (previous.type !== current.type) { + return true; + } + try { + // If both events have the same type, it's still possible that actions were performed on different targets. + // e.g. 2 clicks on different buttons. + if (previous.target !== current.target) { + return true; + } + } + catch (e) { + // just accessing `target` property can throw an exception in some rare circumstances + // see: https://github.com/getsentry/sentry-javascript/issues/838 + } + // If both events have the same type _and_ same `target` (an element which triggered an event, _not necessarily_ + // to which an event listener was attached), we treat them as the same action, as we want to capture + // only one breadcrumb. e.g. multiple clicks on the same button, or typing inside a user input box. + return false; } - /** - * Create a getter for loading a parser. - * @private + * Decide whether an event should be captured. + * @param event event to be captured */ - -function createParserGetter (name) { - return function get () { - return loadParser(name) - } +function shouldSkipDOMEvent(event) { + // We are only interested in filtering `keypress` events for now. + if (event.type !== 'keypress') { + return false; + } + try { + var target = event.target; + if (!target || !target.tagName) { + return true; + } + // Only consider keypress events on actual input elements. This will disregard keypresses targeting body + // e.g.tabbing through elements, hotkeys, etc. + if (target.tagName === 'INPUT' || target.tagName === 'TEXTAREA' || target.isContentEditable) { + return false; + } + } + catch (e) { + // just accessing `target` property can throw an exception in some rare circumstances + // see: https://github.com/getsentry/sentry-javascript/issues/838 + } + return true; } - /** - * Load a parser module. - * @private + * Wraps addEventListener to capture UI breadcrumbs + * @param handler function that will be triggered + * @param globalListener indicates whether event was captured by the global event listener + * @returns wrapped breadcrumb events handler + * @hidden */ - -function loadParser (parserName) { - var parser = parsers[parserName] - - if (parser !== undefined) { - return parser - } - - // this uses a switch for static require analysis - switch (parserName) { - case 'json': - parser = __nccwpck_require__(20859) - break - case 'raw': - parser = __nccwpck_require__(49609) - break - case 'text': - parser = __nccwpck_require__(26382) - break - case 'urlencoded': - parser = __nccwpck_require__(76100) - break - } - - // store to prevent invoking require() - return (parsers[parserName] = parser) +function makeDOMEventHandler(handler, globalListener) { + if (globalListener === void 0) { globalListener = false; } + return function (event) { + // It's possible this handler might trigger multiple times for the same + // event (e.g. event propagation through node ancestors). + // Ignore if we've already captured that event. + if (!event || lastCapturedEvent === event) { + return; + } + // We always want to skip _some_ events. + if (shouldSkipDOMEvent(event)) { + return; + } + var name = event.type === 'keypress' ? 'input' : event.type; + // If there is no debounce timer, it means that we can safely capture the new event and store it for future comparisons. + if (debounceTimerID === undefined) { + handler({ + event: event, + name: name, + global: globalListener, + }); + lastCapturedEvent = event; + } + // If there is a debounce awaiting, see if the new event is different enough to treat it as a unique one. + // If that's the case, emit the previous event and store locally the newly-captured DOM event. + else if (shouldShortcircuitPreviousDebounce(lastCapturedEvent, event)) { + handler({ + event: event, + name: name, + global: globalListener, + }); + lastCapturedEvent = event; + } + // Start a new debounce timer that will prevent us from capturing multiple events that should be grouped together. + clearTimeout(debounceTimerID); + debounceTimerID = global.setTimeout(function () { + debounceTimerID = undefined; + }, debounceDuration); + }; } - +/** JSDoc */ +function instrumentDOM() { + if (!('document' in global)) { + return; + } + // Make it so that any click or keypress that is unhandled / bubbled up all the way to the document triggers our dom + // handlers. (Normally we have only one, which captures a breadcrumb for each click or keypress.) Do this before + // we instrument `addEventListener` so that we don't end up attaching this handler twice. + var triggerDOMHandler = triggerHandlers.bind(null, 'dom'); + var globalDOMEventHandler = makeDOMEventHandler(triggerDOMHandler, true); + global.document.addEventListener('click', globalDOMEventHandler, false); + global.document.addEventListener('keypress', globalDOMEventHandler, false); + // After hooking into click and keypress events bubbled up to `document`, we also hook into user-handled + // clicks & keypresses, by adding an event listener of our own to any element to which they add a listener. That + // way, whenever one of their handlers is triggered, ours will be, too. (This is needed because their handler + // could potentially prevent the event from bubbling up to our global listeners. This way, our handler are still + // guaranteed to fire at least once.) + ['EventTarget', 'Node'].forEach(function (target) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + var proto = global[target] && global[target].prototype; + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access, no-prototype-builtins + if (!proto || !proto.hasOwnProperty || !proto.hasOwnProperty('addEventListener')) { + return; + } + object_1.fill(proto, 'addEventListener', function (originalAddEventListener) { + return function (type, listener, options) { + if (type === 'click' || type == 'keypress') { + try { + var el = this; + var handlers_1 = (el.__sentry_instrumentation_handlers__ = el.__sentry_instrumentation_handlers__ || {}); + var handlerForType = (handlers_1[type] = handlers_1[type] || { refCount: 0 }); + if (!handlerForType.handler) { + var handler = makeDOMEventHandler(triggerDOMHandler); + handlerForType.handler = handler; + originalAddEventListener.call(this, type, handler, options); + } + handlerForType.refCount += 1; + } + catch (e) { + // Accessing dom properties is always fragile. + // Also allows us to skip `addEventListenrs` calls with no proper `this` context. + } + } + return originalAddEventListener.call(this, type, listener, options); + }; + }); + object_1.fill(proto, 'removeEventListener', function (originalRemoveEventListener) { + return function (type, listener, options) { + if (type === 'click' || type == 'keypress') { + try { + var el = this; + var handlers_2 = el.__sentry_instrumentation_handlers__ || {}; + var handlerForType = handlers_2[type]; + if (handlerForType) { + handlerForType.refCount -= 1; + // If there are no longer any custom handlers of the current type on this element, we can remove ours, too. + if (handlerForType.refCount <= 0) { + originalRemoveEventListener.call(this, type, handlerForType.handler, options); + handlerForType.handler = undefined; + delete handlers_2[type]; // eslint-disable-line @typescript-eslint/no-dynamic-delete + } + // If there are no longer any custom handlers of any type on this element, cleanup everything. + if (Object.keys(handlers_2).length === 0) { + delete el.__sentry_instrumentation_handlers__; + } + } + } + catch (e) { + // Accessing dom properties is always fragile. + // Also allows us to skip `addEventListenrs` calls with no proper `this` context. + } + } + return originalRemoveEventListener.call(this, type, listener, options); + }; + }); + }); +} +var _oldOnErrorHandler = null; +/** JSDoc */ +function instrumentError() { + _oldOnErrorHandler = global.onerror; + global.onerror = function (msg, url, line, column, error) { + triggerHandlers('error', { + column: column, + error: error, + line: line, + msg: msg, + url: url, + }); + if (_oldOnErrorHandler) { + // eslint-disable-next-line prefer-rest-params + return _oldOnErrorHandler.apply(this, arguments); + } + return false; + }; +} +var _oldOnUnhandledRejectionHandler = null; +/** JSDoc */ +function instrumentUnhandledRejection() { + _oldOnUnhandledRejectionHandler = global.onunhandledrejection; + global.onunhandledrejection = function (e) { + triggerHandlers('unhandledrejection', e); + if (_oldOnUnhandledRejectionHandler) { + // eslint-disable-next-line prefer-rest-params + return _oldOnUnhandledRejectionHandler.apply(this, arguments); + } + return true; + }; +} +//# sourceMappingURL=instrument.js.map /***/ }), -/***/ 88862: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module dependencies. - * @private - */ - -var createError = __nccwpck_require__(95193) -var getBody = __nccwpck_require__(47742) -var iconv = __nccwpck_require__(19032) -var onFinished = __nccwpck_require__(92098) -var zlib = __nccwpck_require__(78761) - -/** - * Module exports. - */ - -module.exports = read +/***/ 92757: +/***/ ((__unused_webpack_module, exports) => { +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +Object.defineProperty(exports, "__esModule", ({ value: true })); /** - * Read a request into a buffer and parse. + * Checks whether given value's type is one of a few Error or Error-like + * {@link isError}. * - * @param {object} req - * @param {object} res - * @param {function} next - * @param {function} parse - * @param {function} debug - * @param {object} options - * @private + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -function read (req, res, next, parse, debug, options) { - var length - var opts = options - var stream - - // flag as parsed - req._body = true - - // read options - var encoding = opts.encoding !== null - ? opts.encoding - : null - var verify = opts.verify - - try { - // get the content stream - stream = contentstream(req, debug, opts.inflate) - length = stream.length - stream.length = undefined - } catch (err) { - return next(err) - } - - // set raw-body options - opts.length = length - opts.encoding = verify - ? null - : encoding - - // assert charset is supported - if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { - return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { - charset: encoding.toLowerCase(), - type: 'charset.unsupported' - })) - } - - // read body - debug('read body') - getBody(stream, opts, function (error, body) { - if (error) { - var _error - - if (error.type === 'encoding.unsupported') { - // echo back charset - _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { - charset: encoding.toLowerCase(), - type: 'charset.unsupported' - }) - } else { - // set status code on error - _error = createError(400, error) - } - - // read off entire request - stream.resume() - onFinished(req, function onfinished () { - next(createError(400, _error)) - }) - return - } - - // verify - if (verify) { - try { - debug('verify body') - verify(req, res, body, encoding) - } catch (err) { - next(createError(403, err, { - body: body, - type: err.type || 'entity.verify.failed' - })) - return - } - } - - // parse - var str = body - try { - debug('parse body') - str = typeof body !== 'string' && encoding !== null - ? iconv.decode(body, encoding) - : body - req.body = parse(str) - } catch (err) { - next(createError(400, err, { - body: str, - type: err.type || 'entity.parse.failed' - })) - return +function isError(wat) { + switch (Object.prototype.toString.call(wat)) { + case '[object Error]': + return true; + case '[object Exception]': + return true; + case '[object DOMException]': + return true; + default: + return isInstanceOf(wat, Error); } - - next() - }) } - +exports.isError = isError; /** - * Get the content stream of the request. + * Checks whether given value's type is ErrorEvent + * {@link isErrorEvent}. * - * @param {object} req - * @param {function} debug - * @param {boolean} [inflate=true] - * @return {object} - * @api private + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -function contentstream (req, debug, inflate) { - var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() - var length = req.headers['content-length'] - var stream - - debug('content-encoding "%s"', encoding) - - if (inflate === false && encoding !== 'identity') { - throw createError(415, 'content encoding unsupported', { - encoding: encoding, - type: 'encoding.unsupported' - }) - } - - switch (encoding) { - case 'deflate': - stream = zlib.createInflate() - debug('inflate body') - req.pipe(stream) - break - case 'gzip': - stream = zlib.createGunzip() - debug('gunzip body') - req.pipe(stream) - break - case 'identity': - stream = req - stream.length = length - break - default: - throw createError(415, 'unsupported content encoding "' + encoding + '"', { - encoding: encoding, - type: 'encoding.unsupported' - }) - } - - return stream +function isErrorEvent(wat) { + return Object.prototype.toString.call(wat) === '[object ErrorEvent]'; } - - -/***/ }), - -/***/ 20859: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * body-parser - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - +exports.isErrorEvent = isErrorEvent; /** - * Module dependencies. - * @private + * Checks whether given value's type is DOMError + * {@link isDOMError}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -var bytes = __nccwpck_require__(86966) -var contentType = __nccwpck_require__(99915) -var createError = __nccwpck_require__(95193) -var debug = __nccwpck_require__(7471)('body-parser:json') -var read = __nccwpck_require__(88862) -var typeis = __nccwpck_require__(71159) - +function isDOMError(wat) { + return Object.prototype.toString.call(wat) === '[object DOMError]'; +} +exports.isDOMError = isDOMError; /** - * Module exports. + * Checks whether given value's type is DOMException + * {@link isDOMException}. + * + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -module.exports = json - +function isDOMException(wat) { + return Object.prototype.toString.call(wat) === '[object DOMException]'; +} +exports.isDOMException = isDOMException; /** - * RegExp to match the first non-space in a string. + * Checks whether given value's type is a string + * {@link isString}. * - * Allowed whitespace is defined in RFC 7159: + * @param wat A value to be checked. + * @returns A boolean representing the result. + */ +function isString(wat) { + return Object.prototype.toString.call(wat) === '[object String]'; +} +exports.isString = isString; +/** + * Checks whether given value's is a primitive (undefined, null, number, boolean, string, bigint, symbol) + * {@link isPrimitive}. * - * ws = *( - * %x20 / ; Space - * %x09 / ; Horizontal tab - * %x0A / ; Line feed or New line - * %x0D ) ; Carriage return + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex - +function isPrimitive(wat) { + return wat === null || (typeof wat !== 'object' && typeof wat !== 'function'); +} +exports.isPrimitive = isPrimitive; /** - * Create a middleware to parse JSON bodies. + * Checks whether given value's type is an object literal + * {@link isPlainObject}. * - * @param {object} [options] - * @return {function} - * @public + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -function json (options) { - var opts = options || {} - - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var inflate = opts.inflate !== false - var reviver = opts.reviver - var strict = opts.strict !== false - var type = opts.type || 'application/json' - var verify = opts.verify || false - - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } - - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type - - function parse (body) { - if (body.length === 0) { - // special-case empty json body, as it's a common client-side mistake - // TODO: maybe make this configurable or part of "strict" option - return {} - } - - if (strict) { - var first = firstchar(body) - - if (first !== '{' && first !== '[') { - debug('strict violation') - throw createStrictSyntaxError(body, first) - } - } - - try { - debug('parse json') - return JSON.parse(body, reviver) - } catch (e) { - throw normalizeJsonSyntaxError(e, { - message: e.message, - stack: e.stack - }) - } - } - - return function jsonParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return - } - - req.body = req.body || {} - - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return - } - - debug('content-type %j', req.headers['content-type']) - - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return - } - - // assert charset per RFC 7159 sec 8.1 - var charset = getCharset(req) || 'utf-8' - if (charset.substr(0, 4) !== 'utf-') { - debug('invalid charset') - next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { - charset: charset, - type: 'charset.unsupported' - })) - return - } - - // read - read(req, res, next, parse, debug, { - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } +function isPlainObject(wat) { + return Object.prototype.toString.call(wat) === '[object Object]'; } - +exports.isPlainObject = isPlainObject; /** - * Create strict violation syntax error matching native error. + * Checks whether given value's type is an Event instance + * {@link isEvent}. * - * @param {string} str - * @param {string} char - * @return {Error} - * @private + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -function createStrictSyntaxError (str, char) { - var index = str.indexOf(char) - var partial = str.substring(0, index) + '#' - - try { - JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') - } catch (e) { - return normalizeJsonSyntaxError(e, { - message: e.message.replace('#', char), - stack: e.stack - }) - } +function isEvent(wat) { + return typeof Event !== 'undefined' && isInstanceOf(wat, Event); } - +exports.isEvent = isEvent; /** - * Get the first non-whitespace character in a string. + * Checks whether given value's type is an Element instance + * {@link isElement}. * - * @param {string} str - * @return {function} - * @private + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -function firstchar (str) { - return FIRST_CHAR_REGEXP.exec(str)[1] +function isElement(wat) { + return typeof Element !== 'undefined' && isInstanceOf(wat, Element); } - +exports.isElement = isElement; /** - * Get the charset of a request. + * Checks whether given value's type is an regexp + * {@link isRegExp}. * - * @param {object} req - * @api private + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } +function isRegExp(wat) { + return Object.prototype.toString.call(wat) === '[object RegExp]'; } - +exports.isRegExp = isRegExp; /** - * Normalize a SyntaxError for JSON.parse. + * Checks whether given value has a then function. + * @param wat A value to be checked. + */ +function isThenable(wat) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return Boolean(wat && wat.then && typeof wat.then === 'function'); +} +exports.isThenable = isThenable; +/** + * Checks whether given value's type is a SyntheticEvent + * {@link isSyntheticEvent}. * - * @param {SyntaxError} error - * @param {object} obj - * @return {SyntaxError} + * @param wat A value to be checked. + * @returns A boolean representing the result. */ - -function normalizeJsonSyntaxError (error, obj) { - var keys = Object.getOwnPropertyNames(error) - - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - if (key !== 'stack' && key !== 'message') { - delete error[key] - } - } - - // replace stack before message for Node.js 0.10 and below - error.stack = obj.stack.replace(error.message, obj.message) - error.message = obj.message - - return error +function isSyntheticEvent(wat) { + return isPlainObject(wat) && 'nativeEvent' in wat && 'preventDefault' in wat && 'stopPropagation' in wat; } - +exports.isSyntheticEvent = isSyntheticEvent; /** - * Get the simple type checker. + * Checks whether given value's type is an instance of provided constructor. + * {@link isInstanceOf}. * - * @param {string} type - * @return {function} + * @param wat A value to be checked. + * @param base A constructor to be used in a check. + * @returns A boolean representing the result. */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } +function isInstanceOf(wat, base) { + try { + return wat instanceof base; + } + catch (_e) { + return false; + } } - +exports.isInstanceOf = isInstanceOf; +//# sourceMappingURL=is.js.map /***/ }), -/***/ 49609: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 15577: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +/* eslint-disable @typescript-eslint/no-explicit-any */ +var misc_1 = __nccwpck_require__(32154); +// TODO: Implement different loggers for different environments +var global = misc_1.getGlobalObject(); +/** Prefix for logging strings */ +var PREFIX = 'Sentry Logger '; +/** JSDoc */ +var Logger = /** @class */ (function () { + /** JSDoc */ + function Logger() { + this._enabled = false; + } + /** JSDoc */ + Logger.prototype.disable = function () { + this._enabled = false; + }; + /** JSDoc */ + Logger.prototype.enable = function () { + this._enabled = true; + }; + /** JSDoc */ + Logger.prototype.log = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (!this._enabled) { + return; + } + misc_1.consoleSandbox(function () { + global.console.log(PREFIX + "[Log]: " + args.join(' ')); + }); + }; + /** JSDoc */ + Logger.prototype.warn = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (!this._enabled) { + return; + } + misc_1.consoleSandbox(function () { + global.console.warn(PREFIX + "[Warn]: " + args.join(' ')); + }); + }; + /** JSDoc */ + Logger.prototype.error = function () { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + if (!this._enabled) { + return; + } + misc_1.consoleSandbox(function () { + global.console.error(PREFIX + "[Error]: " + args.join(' ')); + }); + }; + return Logger; +}()); +// Ensure we only have a single logger instance, even if multiple versions of @sentry/utils are being used +global.__SENTRY__ = global.__SENTRY__ || {}; +var logger = global.__SENTRY__.logger || (global.__SENTRY__.logger = new Logger()); +exports.logger = logger; +//# sourceMappingURL=logger.js.map +/***/ }), +/***/ 49515: +/***/ ((__unused_webpack_module, exports) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +/* eslint-disable @typescript-eslint/no-unsafe-member-access */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ /** - * Module dependencies. + * Memo class used for decycle json objects. Uses WeakSet if available otherwise array. */ +var Memo = /** @class */ (function () { + function Memo() { + this._hasWeakSet = typeof WeakSet === 'function'; + this._inner = this._hasWeakSet ? new WeakSet() : []; + } + /** + * Sets obj to remember. + * @param obj Object to remember + */ + Memo.prototype.memoize = function (obj) { + if (this._hasWeakSet) { + if (this._inner.has(obj)) { + return true; + } + this._inner.add(obj); + return false; + } + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (var i = 0; i < this._inner.length; i++) { + var value = this._inner[i]; + if (value === obj) { + return true; + } + } + this._inner.push(obj); + return false; + }; + /** + * Removes object from internal storage. + * @param obj Object to forget + */ + Memo.prototype.unmemoize = function (obj) { + if (this._hasWeakSet) { + this._inner.delete(obj); + } + else { + for (var i = 0; i < this._inner.length; i++) { + if (this._inner[i] === obj) { + this._inner.splice(i, 1); + break; + } + } + } + }; + return Memo; +}()); +exports.Memo = Memo; +//# sourceMappingURL=memo.js.map -var bytes = __nccwpck_require__(86966) -var debug = __nccwpck_require__(7471)('body-parser:raw') -var read = __nccwpck_require__(88862) -var typeis = __nccwpck_require__(71159) +/***/ }), + +/***/ 32154: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var node_1 = __nccwpck_require__(16411); +var string_1 = __nccwpck_require__(66538); +var fallbackGlobalObject = {}; /** - * Module exports. + * Safely get global scope object + * + * @returns Global scope object */ - -module.exports = raw - +function getGlobalObject() { + return (node_1.isNodeEnv() + ? global + : typeof window !== 'undefined' + ? window + : typeof self !== 'undefined' + ? self + : fallbackGlobalObject); +} +exports.getGlobalObject = getGlobalObject; /** - * Create a middleware to parse raw bodies. + * UUID4 generator * - * @param {object} [options] - * @return {function} - * @api public + * @returns string Generated UUID4. */ - -function raw (options) { - var opts = options || {} - - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'application/octet-stream' - var verify = opts.verify || false - - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } - - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type - - function parse (buf) { - return buf - } - - return function rawParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return +function uuid4() { + var global = getGlobalObject(); + var crypto = global.crypto || global.msCrypto; + if (!(crypto === void 0) && crypto.getRandomValues) { + // Use window.crypto API if available + var arr = new Uint16Array(8); + crypto.getRandomValues(arr); + // set 4 in byte 7 + // eslint-disable-next-line no-bitwise + arr[3] = (arr[3] & 0xfff) | 0x4000; + // set 2 most significant bits of byte 9 to '10' + // eslint-disable-next-line no-bitwise + arr[4] = (arr[4] & 0x3fff) | 0x8000; + var pad = function (num) { + var v = num.toString(16); + while (v.length < 4) { + v = "0" + v; + } + return v; + }; + return (pad(arr[0]) + pad(arr[1]) + pad(arr[2]) + pad(arr[3]) + pad(arr[4]) + pad(arr[5]) + pad(arr[6]) + pad(arr[7])); } - - req.body = req.body || {} - - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return + // http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#2117523 + return 'xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx'.replace(/[xy]/g, function (c) { + // eslint-disable-next-line no-bitwise + var r = (Math.random() * 16) | 0; + // eslint-disable-next-line no-bitwise + var v = c === 'x' ? r : (r & 0x3) | 0x8; + return v.toString(16); + }); +} +exports.uuid4 = uuid4; +/** + * Parses string form of URL into an object + * // borrowed from https://tools.ietf.org/html/rfc3986#appendix-B + * // intentionally using regex and not href parsing trick because React Native and other + * // environments where DOM might not be available + * @returns parsed URL object + */ +function parseUrl(url) { + if (!url) { + return {}; } - - debug('content-type %j', req.headers['content-type']) - - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return + var match = url.match(/^(([^:/?#]+):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?$/); + if (!match) { + return {}; + } + // coerce to undefined values to empty string so we don't get 'undefined' + var query = match[6] || ''; + var fragment = match[8] || ''; + return { + host: match[4], + path: match[5], + protocol: match[2], + relative: match[5] + query + fragment, + }; +} +exports.parseUrl = parseUrl; +/** + * Extracts either message or type+value from an event that can be used for user-facing logs + * @returns event's description + */ +function getEventDescription(event) { + if (event.message) { + return event.message; + } + if (event.exception && event.exception.values && event.exception.values[0]) { + var exception = event.exception.values[0]; + if (exception.type && exception.value) { + return exception.type + ": " + exception.value; + } + return exception.type || exception.value || event.event_id || ''; + } + return event.event_id || ''; +} +exports.getEventDescription = getEventDescription; +/** JSDoc */ +function consoleSandbox(callback) { + var global = getGlobalObject(); + var levels = ['debug', 'info', 'warn', 'error', 'log', 'assert']; + if (!('console' in global)) { + return callback(); } - - // read - read(req, res, next, parse, debug, { - encoding: null, - inflate: inflate, - limit: limit, - verify: verify - }) - } + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + var originalConsole = global.console; + var wrappedLevels = {}; + // Restore all wrapped console methods + levels.forEach(function (level) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + if (level in global.console && originalConsole[level].__sentry_original__) { + wrappedLevels[level] = originalConsole[level]; + originalConsole[level] = originalConsole[level].__sentry_original__; + } + }); + // Perform callback manipulations + var result = callback(); + // Revert restoration to wrapped state + Object.keys(wrappedLevels).forEach(function (level) { + originalConsole[level] = wrappedLevels[level]; + }); + return result; } - +exports.consoleSandbox = consoleSandbox; /** - * Get the simple type checker. - * - * @param {string} type - * @return {function} + * Adds exception values, type and value to an synthetic Exception. + * @param event The event to modify. + * @param value Value of the exception. + * @param type Type of the exception. + * @hidden */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } +function addExceptionTypeValue(event, value, type) { + event.exception = event.exception || {}; + event.exception.values = event.exception.values || []; + event.exception.values[0] = event.exception.values[0] || {}; + event.exception.values[0].value = event.exception.values[0].value || value || ''; + event.exception.values[0].type = event.exception.values[0].type || type || 'Error'; } - - -/***/ }), - -/***/ 26382: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * body-parser - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed +exports.addExceptionTypeValue = addExceptionTypeValue; +/** + * Adds exception mechanism to a given event. + * @param event The event to modify. + * @param mechanism Mechanism of the mechanism. + * @hidden */ - - - +function addExceptionMechanism(event, mechanism) { + if (mechanism === void 0) { mechanism = {}; } + // TODO: Use real type with `keyof Mechanism` thingy and maybe make it better? + try { + // @ts-ignore Type 'Mechanism | {}' is not assignable to type 'Mechanism | undefined' + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + event.exception.values[0].mechanism = event.exception.values[0].mechanism || {}; + Object.keys(mechanism).forEach(function (key) { + // @ts-ignore Mechanism has no index signature + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + event.exception.values[0].mechanism[key] = mechanism[key]; + }); + } + catch (_oO) { + // no-empty + } +} +exports.addExceptionMechanism = addExceptionMechanism; /** - * Module dependencies. + * A safe form of location.href */ - -var bytes = __nccwpck_require__(86966) -var contentType = __nccwpck_require__(99915) -var debug = __nccwpck_require__(7471)('body-parser:text') -var read = __nccwpck_require__(88862) -var typeis = __nccwpck_require__(71159) - +function getLocationHref() { + try { + return document.location.href; + } + catch (oO) { + return ''; + } +} +exports.getLocationHref = getLocationHref; +// https://semver.org/#is-there-a-suggested-regular-expression-regex-to-check-a-semver-string +var SEMVER_REGEXP = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*)(?:\.(?:0|[1-9]\d*|\d*[a-zA-Z-][0-9a-zA-Z-]*))*))?(?:\+([0-9a-zA-Z-]+(?:\.[0-9a-zA-Z-]+)*))?$/; /** - * Module exports. + * Parses input into a SemVer interface + * @param input string representation of a semver version */ - -module.exports = text - +function parseSemver(input) { + var match = input.match(SEMVER_REGEXP) || []; + var major = parseInt(match[1], 10); + var minor = parseInt(match[2], 10); + var patch = parseInt(match[3], 10); + return { + buildmetadata: match[5], + major: isNaN(major) ? undefined : major, + minor: isNaN(minor) ? undefined : minor, + patch: isNaN(patch) ? undefined : patch, + prerelease: match[4], + }; +} +exports.parseSemver = parseSemver; +var defaultRetryAfter = 60 * 1000; // 60 seconds /** - * Create a middleware to parse text bodies. - * - * @param {object} [options] - * @return {function} - * @api public + * Extracts Retry-After value from the request header or returns default value + * @param now current unix timestamp + * @param header string representation of 'Retry-After' header */ - -function text (options) { - var opts = options || {} - - var defaultCharset = opts.defaultCharset || 'utf-8' - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'text/plain' - var verify = opts.verify || false - - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } - - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type - - function parse (buf) { - return buf - } - - return function textParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return +function parseRetryAfterHeader(now, header) { + if (!header) { + return defaultRetryAfter; } - - req.body = req.body || {} - - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return + var headerDelay = parseInt("" + header, 10); + if (!isNaN(headerDelay)) { + return headerDelay * 1000; } - - debug('content-type %j', req.headers['content-type']) - - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return + var headerDate = Date.parse("" + header); + if (!isNaN(headerDate)) { + return headerDate - now; } - - // get charset - var charset = getCharset(req) || defaultCharset - - // read - read(req, res, next, parse, debug, { - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } + return defaultRetryAfter; } - +exports.parseRetryAfterHeader = parseRetryAfterHeader; /** - * Get the charset of a request. + * This function adds context (pre/post/line) lines to the provided frame * - * @param {object} req - * @api private + * @param lines string[] containing all lines + * @param frame StackFrame that will be mutated + * @param linesOfContext number of context lines we want to add pre/post */ - -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } +function addContextToFrame(lines, frame, linesOfContext) { + if (linesOfContext === void 0) { linesOfContext = 5; } + var lineno = frame.lineno || 0; + var maxLines = lines.length; + var sourceLine = Math.max(Math.min(maxLines, lineno - 1), 0); + frame.pre_context = lines + .slice(Math.max(0, sourceLine - linesOfContext), sourceLine) + .map(function (line) { return string_1.snipLine(line, 0); }); + frame.context_line = string_1.snipLine(lines[Math.min(maxLines - 1, sourceLine)], frame.colno || 0); + frame.post_context = lines + .slice(Math.min(sourceLine + 1, maxLines), sourceLine + 1 + linesOfContext) + .map(function (line) { return string_1.snipLine(line, 0); }); } - +exports.addContextToFrame = addContextToFrame; /** - * Get the simple type checker. + * Strip the query string and fragment off of a given URL or path (if present) * - * @param {string} type - * @return {function} + * @param urlPath Full URL or path, including possible query string and/or fragment + * @returns URL or path without query string or fragment */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } +function stripUrlQueryAndFragment(urlPath) { + // eslint-disable-next-line no-useless-escape + return urlPath.split(/[\?#]/, 1)[0]; } - +exports.stripUrlQueryAndFragment = stripUrlQueryAndFragment; +//# sourceMappingURL=misc.js.map /***/ }), -/***/ 76100: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * body-parser - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ - - +/***/ 16411: +/***/ ((module, exports, __nccwpck_require__) => { +/* module decorator */ module = __nccwpck_require__.nmd(module); +Object.defineProperty(exports, "__esModule", ({ value: true })); /** - * Module dependencies. - * @private + * Checks whether we're in the Node.js or Browser environment + * + * @returns Answer to given question */ - -var bytes = __nccwpck_require__(86966) -var contentType = __nccwpck_require__(99915) -var createError = __nccwpck_require__(95193) -var debug = __nccwpck_require__(7471)('body-parser:urlencoded') -var deprecate = __nccwpck_require__(18883)('body-parser') -var read = __nccwpck_require__(88862) -var typeis = __nccwpck_require__(71159) - +function isNodeEnv() { + return Object.prototype.toString.call(typeof process !== 'undefined' ? process : 0) === '[object process]'; +} +exports.isNodeEnv = isNodeEnv; /** - * Module exports. + * Requires a module which is protected against bundler minification. + * + * @param request The module path to resolve */ - -module.exports = urlencoded - +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, @typescript-eslint/no-explicit-any +function dynamicRequire(mod, request) { + // eslint-disable-next-line @typescript-eslint/no-unsafe-member-access + return mod.require(request); +} +exports.dynamicRequire = dynamicRequire; /** - * Cache of parser modules. + * Helper for dynamically loading module that should work with linked dependencies. + * The problem is that we _should_ be using `require(require.resolve(moduleName, { paths: [cwd()] }))` + * However it's _not possible_ to do that with Webpack, as it has to know all the dependencies during + * build time. `require.resolve` is also not available in any other way, so we cannot create, + * a fake helper like we do with `dynamicRequire`. + * + * We always prefer to use local package, thus the value is not returned early from each `try/catch` block. + * That is to mimic the behavior of `require.resolve` exactly. + * + * @param moduleName module name to require + * @returns possibly required module */ +function loadModule(moduleName) { + var mod; + try { + mod = dynamicRequire(module, moduleName); + } + catch (e) { + // no-empty + } + try { + var cwd = dynamicRequire(module, 'process').cwd; + mod = dynamicRequire(module, cwd() + "/node_modules/" + moduleName); + } + catch (e) { + // no-empty + } + return mod; +} +exports.loadModule = loadModule; +//# sourceMappingURL=node.js.map -var parsers = Object.create(null) +/***/ }), + +/***/ 69249: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var tslib_1 = __nccwpck_require__(4351); +var browser_1 = __nccwpck_require__(30597); +var is_1 = __nccwpck_require__(92757); +var memo_1 = __nccwpck_require__(49515); +var stacktrace_1 = __nccwpck_require__(5986); +var string_1 = __nccwpck_require__(66538); /** - * Create a middleware to parse urlencoded bodies. + * Replace a method in an object with a wrapped version of itself. * - * @param {object} [options] - * @return {function} - * @public + * @param source An object that contains a method to be wrapped. + * @param name The name of the method to be wrapped. + * @param replacementFactory A higher-order function that takes the original version of the given method and returns a + * wrapped version. Note: The function returned by `replacementFactory` needs to be a non-arrow function, in order to + * preserve the correct value of `this`, and the original method must be called using `origMethod.call(this, )` or `origMethod.apply(this, [])` (rather than being called directly), again to preserve `this`. + * @returns void */ - -function urlencoded (options) { - var opts = options || {} - - // notice because option default will flip in next major - if (opts.extended === undefined) { - deprecate('undefined extended: provide extended option') - } - - var extended = opts.extended !== false - var inflate = opts.inflate !== false - var limit = typeof opts.limit !== 'number' - ? bytes.parse(opts.limit || '100kb') - : opts.limit - var type = opts.type || 'application/x-www-form-urlencoded' - var verify = opts.verify || false - - if (verify !== false && typeof verify !== 'function') { - throw new TypeError('option verify must be function') - } - - // create the appropriate query parser - var queryparse = extended - ? extendedparser(opts) - : simpleparser(opts) - - // create the appropriate type checking function - var shouldParse = typeof type !== 'function' - ? typeChecker(type) - : type - - function parse (body) { - return body.length - ? queryparse(body) - : {} - } - - return function urlencodedParser (req, res, next) { - if (req._body) { - debug('body already parsed') - next() - return +function fill(source, name, replacementFactory) { + if (!(name in source)) { + return; } - - req.body = req.body || {} - - // skip requests without bodies - if (!typeis.hasBody(req)) { - debug('skip empty body') - next() - return + var original = source[name]; + var wrapped = replacementFactory(original); + // Make sure it's a function first, as we need to attach an empty prototype for `defineProperties` to work + // otherwise it'll throw "TypeError: Object.defineProperties called on non-object" + if (typeof wrapped === 'function') { + try { + wrapped.prototype = wrapped.prototype || {}; + Object.defineProperties(wrapped, { + __sentry_original__: { + enumerable: false, + value: original, + }, + }); + } + catch (_Oo) { + // This can throw if multiple fill happens on a global object like XMLHttpRequest + // Fixes https://github.com/getsentry/sentry-javascript/issues/2043 + } } - - debug('content-type %j', req.headers['content-type']) - - // determine if request should be parsed - if (!shouldParse(req)) { - debug('skip parsing') - next() - return + source[name] = wrapped; +} +exports.fill = fill; +/** + * Encodes given object into url-friendly format + * + * @param object An object that contains serializable values + * @returns string Encoded + */ +function urlEncode(object) { + return Object.keys(object) + .map(function (key) { return encodeURIComponent(key) + "=" + encodeURIComponent(object[key]); }) + .join('&'); +} +exports.urlEncode = urlEncode; +/** + * Transforms any object into an object literal with all its attributes + * attached to it. + * + * @param value Initial source that we have to transform in order for it to be usable by the serializer + */ +function getWalkSource(value) { + if (is_1.isError(value)) { + var error = value; + var err = { + message: error.message, + name: error.name, + stack: error.stack, + }; + for (var i in error) { + if (Object.prototype.hasOwnProperty.call(error, i)) { + err[i] = error[i]; + } + } + return err; } - - // assert charset - var charset = getCharset(req) || 'utf-8' - if (charset !== 'utf-8') { - debug('invalid charset') - next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { - charset: charset, - type: 'charset.unsupported' - })) - return + if (is_1.isEvent(value)) { + var event_1 = value; + var source = {}; + // Accessing event attributes can throw (see https://github.com/getsentry/sentry-javascript/issues/768 and + // https://github.com/getsentry/sentry-javascript/issues/838), but accessing `type` hasn't been wrapped in a + // try-catch in at least two years and no one's complained, so that's likely not an issue anymore + source.type = event_1.type; + try { + source.target = is_1.isElement(event_1.target) + ? browser_1.htmlTreeAsString(event_1.target) + : Object.prototype.toString.call(event_1.target); + } + catch (_oO) { + source.target = ''; + } + try { + source.currentTarget = is_1.isElement(event_1.currentTarget) + ? browser_1.htmlTreeAsString(event_1.currentTarget) + : Object.prototype.toString.call(event_1.currentTarget); + } + catch (_oO) { + source.currentTarget = ''; + } + if (typeof CustomEvent !== 'undefined' && is_1.isInstanceOf(value, CustomEvent)) { + source.detail = event_1.detail; + } + for (var attr in event_1) { + if (Object.prototype.hasOwnProperty.call(event_1, attr)) { + source[attr] = event_1[attr]; + } + } + return source; } - - // read - read(req, res, next, parse, debug, { - debug: debug, - encoding: charset, - inflate: inflate, - limit: limit, - verify: verify - }) - } + return value; +} +/** Calculates bytes size of input string */ +function utf8Length(value) { + // eslint-disable-next-line no-bitwise + return ~-encodeURI(value).split(/%..|./).length; +} +/** Calculates bytes size of input object */ +function jsonSize(value) { + return utf8Length(JSON.stringify(value)); +} +/** JSDoc */ +function normalizeToSize(object, +// Default Node.js REPL depth +depth, +// 100kB, as 200kB is max payload size, so half sounds reasonable +maxSize) { + if (depth === void 0) { depth = 3; } + if (maxSize === void 0) { maxSize = 100 * 1024; } + var serialized = normalize(object, depth); + if (jsonSize(serialized) > maxSize) { + return normalizeToSize(object, depth - 1, maxSize); + } + return serialized; } - +exports.normalizeToSize = normalizeToSize; /** - * Get the extended query parser. + * Transform any non-primitive, BigInt, or Symbol-type value into a string. Acts as a no-op on strings, numbers, + * booleans, null, and undefined. * - * @param {object} options + * @param value The value to stringify + * @returns For non-primitive, BigInt, and Symbol-type values, a string denoting the value's type, type and value, or + * type and `description` property, respectively. For non-BigInt, non-Symbol primitives, returns the original value, + * unchanged. */ - -function extendedparser (options) { - var parameterLimit = options.parameterLimit !== undefined - ? options.parameterLimit - : 1000 - var parse = parser('qs') - - if (isNaN(parameterLimit) || parameterLimit < 1) { - throw new TypeError('option parameterLimit must be a positive number') - } - - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 - } - - return function queryparse (body) { - var paramCount = parameterCount(body, parameterLimit) - - if (paramCount === undefined) { - debug('too many parameters') - throw createError(413, 'too many parameters', { - type: 'parameters.too.many' - }) +function serializeValue(value) { + var type = Object.prototype.toString.call(value); + // Node.js REPL notation + if (typeof value === 'string') { + return value; } - - var arrayLimit = Math.max(100, paramCount) - - debug('parse extended urlencoding') - return parse(body, { - allowPrototypes: true, - arrayLimit: arrayLimit, - depth: Infinity, - parameterLimit: parameterLimit - }) - } + if (type === '[object Object]') { + return '[Object]'; + } + if (type === '[object Array]') { + return '[Array]'; + } + var normalized = normalizeValue(value); + return is_1.isPrimitive(normalized) ? normalized : type; } - /** - * Get the charset of a request. + * normalizeValue() * - * @param {object} req - * @api private + * Takes unserializable input and make it serializable friendly + * + * - translates undefined/NaN values to "[undefined]"/"[NaN]" respectively, + * - serializes Error objects + * - filter global objects */ - -function getCharset (req) { - try { - return (contentType.parse(req).parameters.charset || '').toLowerCase() - } catch (e) { - return undefined - } +function normalizeValue(value, key) { + if (key === 'domain' && value && typeof value === 'object' && value._events) { + return '[Domain]'; + } + if (key === 'domainEmitter') { + return '[DomainEmitter]'; + } + if (typeof global !== 'undefined' && value === global) { + return '[Global]'; + } + if (typeof window !== 'undefined' && value === window) { + return '[Window]'; + } + if (typeof document !== 'undefined' && value === document) { + return '[Document]'; + } + // React's SyntheticEvent thingy + if (is_1.isSyntheticEvent(value)) { + return '[SyntheticEvent]'; + } + if (typeof value === 'number' && value !== value) { + return '[NaN]'; + } + if (value === void 0) { + return '[undefined]'; + } + if (typeof value === 'function') { + return "[Function: " + stacktrace_1.getFunctionName(value) + "]"; + } + // symbols and bigints are considered primitives by TS, but aren't natively JSON-serilaizable + if (typeof value === 'symbol') { + return "[" + String(value) + "]"; + } + if (typeof value === 'bigint') { + return "[BigInt: " + String(value) + "]"; + } + return value; } - /** - * Count the number of parameters, stopping once limit reached + * Walks an object to perform a normalization on it * - * @param {string} body - * @param {number} limit - * @api private + * @param key of object that's walked in current iteration + * @param value object to be walked + * @param depth Optional number indicating how deep should walking be performed + * @param memo Optional Memo class handling decycling */ - -function parameterCount (body, limit) { - var count = 0 - var index = 0 - - while ((index = body.indexOf('&', index)) !== -1) { - count++ - index++ - - if (count === limit) { - return undefined +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function walk(key, value, depth, memo) { + if (depth === void 0) { depth = +Infinity; } + if (memo === void 0) { memo = new memo_1.Memo(); } + // If we reach the maximum depth, serialize whatever has left + if (depth === 0) { + return serializeValue(value); } - } - - return count + /* eslint-disable @typescript-eslint/no-unsafe-member-access */ + // If value implements `toJSON` method, call it and return early + if (value !== null && value !== undefined && typeof value.toJSON === 'function') { + return value.toJSON(); + } + /* eslint-enable @typescript-eslint/no-unsafe-member-access */ + // If normalized value is a primitive, there are no branches left to walk, so we can just bail out, as theres no point in going down that branch any further + var normalized = normalizeValue(value, key); + if (is_1.isPrimitive(normalized)) { + return normalized; + } + // Create source that we will use for next itterations, either objectified error object (Error type with extracted keys:value pairs) or the input itself + var source = getWalkSource(value); + // Create an accumulator that will act as a parent for all future itterations of that branch + var acc = Array.isArray(value) ? [] : {}; + // If we already walked that branch, bail out, as it's circular reference + if (memo.memoize(value)) { + return '[Circular ~]'; + } + // Walk all keys of the source + for (var innerKey in source) { + // Avoid iterating over fields in the prototype if they've somehow been exposed to enumeration. + if (!Object.prototype.hasOwnProperty.call(source, innerKey)) { + continue; + } + // Recursively walk through all the child nodes + acc[innerKey] = walk(innerKey, source[innerKey], depth - 1, memo); + } + // Once walked through all the branches, remove the parent from memo storage + memo.unmemoize(value); + // Return accumulated values + return acc; } - +exports.walk = walk; /** - * Get parser for module name dynamically. + * normalize() * - * @param {string} name - * @return {function} - * @api private + * - Creates a copy to prevent original input mutation + * - Skip non-enumerablers + * - Calls `toJSON` if implemented + * - Removes circular references + * - Translates non-serializeable values (undefined/NaN/Functions) to serializable format + * - Translates known global objects/Classes to a string representations + * - Takes care of Error objects serialization + * - Optionally limit depth of final output */ - -function parser (name) { - var mod = parsers[name] - - if (mod !== undefined) { - return mod.parse - } - - // this uses a switch for static require analysis - switch (name) { - case 'qs': - mod = __nccwpck_require__(22760) - break - case 'querystring': - mod = __nccwpck_require__(71191) - break - } - - // store to prevent invoking require() - parsers[name] = mod - - return mod.parse +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function normalize(input, depth) { + try { + return JSON.parse(JSON.stringify(input, function (key, value) { return walk(key, value, depth); })); + } + catch (_oO) { + return '**non-serializable**'; + } } - +exports.normalize = normalize; /** - * Get the simple query parser. - * - * @param {object} options + * Given any captured exception, extract its keys and create a sorted + * and truncated list that will be used inside the event message. + * eg. `Non-error exception captured with keys: foo, bar, baz` */ - -function simpleparser (options) { - var parameterLimit = options.parameterLimit !== undefined - ? options.parameterLimit - : 1000 - var parse = parser('querystring') - - if (isNaN(parameterLimit) || parameterLimit < 1) { - throw new TypeError('option parameterLimit must be a positive number') - } - - if (isFinite(parameterLimit)) { - parameterLimit = parameterLimit | 0 - } - - return function queryparse (body) { - var paramCount = parameterCount(body, parameterLimit) - - if (paramCount === undefined) { - debug('too many parameters') - throw createError(413, 'too many parameters', { - type: 'parameters.too.many' - }) +// eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types +function extractExceptionKeysForMessage(exception, maxLength) { + if (maxLength === void 0) { maxLength = 40; } + var keys = Object.keys(getWalkSource(exception)); + keys.sort(); + if (!keys.length) { + return '[object has no keys]'; } - - debug('parse urlencoding') - return parse(body, undefined, undefined, { maxKeys: parameterLimit }) - } + if (keys[0].length >= maxLength) { + return string_1.truncate(keys[0], maxLength); + } + for (var includedKeys = keys.length; includedKeys > 0; includedKeys--) { + var serialized = keys.slice(0, includedKeys).join(', '); + if (serialized.length > maxLength) { + continue; + } + if (includedKeys === keys.length) { + return serialized; + } + return string_1.truncate(serialized, maxLength); + } + return ''; } - +exports.extractExceptionKeysForMessage = extractExceptionKeysForMessage; /** - * Get the simple type checker. - * - * @param {string} type - * @return {function} + * Given any object, return the new object with removed keys that value was `undefined`. + * Works recursively on objects and arrays. */ - -function typeChecker (type) { - return function checkType (req) { - return Boolean(typeis(req, type)) - } +function dropUndefinedKeys(val) { + var e_1, _a; + if (is_1.isPlainObject(val)) { + var obj = val; + var rv = {}; + try { + for (var _b = tslib_1.__values(Object.keys(obj)), _c = _b.next(); !_c.done; _c = _b.next()) { + var key = _c.value; + if (typeof obj[key] !== 'undefined') { + rv[key] = dropUndefinedKeys(obj[key]); + } + } + } + catch (e_1_1) { e_1 = { error: e_1_1 }; } + finally { + try { + if (_c && !_c.done && (_a = _b.return)) _a.call(_b); + } + finally { if (e_1) throw e_1.error; } + } + return rv; + } + if (Array.isArray(val)) { + return val.map(dropUndefinedKeys); + } + return val; } - +exports.dropUndefinedKeys = dropUndefinedKeys; +//# sourceMappingURL=object.js.map /***/ }), -/***/ 15377: -/***/ ((module, exports, __nccwpck_require__) => { - -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = __nccwpck_require__(22552); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); - -/** - * Colors. - */ - -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } +/***/ 39188: +/***/ ((__unused_webpack_module, exports) => { - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +// Slightly modified (no IE8 support, ES6) and transcribed to TypeScript +// https://raw.githubusercontent.com/calvinmetcalf/rollup-plugin-node-builtins/master/src/es6/path.js +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** JSDoc */ +function normalizeArray(parts, allowAboveRoot) { + // if the path tries to go above the root, `up` ends up > 0 + var up = 0; + for (var i = parts.length - 1; i >= 0; i--) { + var last = parts[i]; + if (last === '.') { + parts.splice(i, 1); + } + else if (last === '..') { + parts.splice(i, 1); + // eslint-disable-next-line no-plusplus + up++; + } + else if (up) { + parts.splice(i, 1); + // eslint-disable-next-line no-plusplus + up--; + } + } + // if the path is allowed to go above the root, restore leading ..s + if (allowAboveRoot) { + // eslint-disable-next-line no-plusplus + for (; up--; up) { + parts.unshift('..'); + } + } + return parts; } - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; - - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return; - - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') - - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; +// Split a filename into [root, dir, basename, ext], unix version +// 'root' is just a slash, or nothing. +var splitPathRe = /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^/]+?|)(\.[^./]*|))(?:[/]*)$/; +/** JSDoc */ +function splitPath(filename) { + var parts = splitPathRe.exec(filename); + return parts ? parts.slice(1) : []; +} +// path.resolve([from ...], to) +// posix version +/** JSDoc */ +function resolve() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; + } + var resolvedPath = ''; + var resolvedAbsolute = false; + for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path = i >= 0 ? args[i] : '/'; + // Skip empty entries + if (!path) { + continue; + } + resolvedPath = path + "/" + resolvedPath; + resolvedAbsolute = path.charAt(0) === '/'; + } + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + // Normalize the path + resolvedPath = normalizeArray(resolvedPath.split('/').filter(function (p) { return !!p; }), !resolvedAbsolute).join('/'); + return (resolvedAbsolute ? '/' : '') + resolvedPath || '.'; +} +exports.resolve = resolve; +/** JSDoc */ +function trim(arr) { + var start = 0; + for (; start < arr.length; start++) { + if (arr[start] !== '') { + break; + } + } + var end = arr.length - 1; + for (; end >= 0; end--) { + if (arr[end] !== '') { + break; + } + } + if (start > end) { + return []; + } + return arr.slice(start, end - start + 1); +} +// path.relative(from, to) +// posix version +/** JSDoc */ +function relative(from, to) { + /* eslint-disable no-param-reassign */ + from = resolve(from).substr(1); + to = resolve(to).substr(1); + /* eslint-enable no-param-reassign */ + var fromParts = trim(from.split('/')); + var toParts = trim(to.split('/')); + var length = Math.min(fromParts.length, toParts.length); + var samePartsLength = length; + for (var i = 0; i < length; i++) { + if (fromParts[i] !== toParts[i]) { + samePartsLength = i; + break; + } } - }); - - args.splice(lastC, 0, c); + var outputParts = []; + for (var i = samePartsLength; i < fromParts.length; i++) { + outputParts.push('..'); + } + outputParts = outputParts.concat(toParts.slice(samePartsLength)); + return outputParts.join('/'); } - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); +exports.relative = relative; +// path.normalize(path) +// posix version +/** JSDoc */ +function normalizePath(path) { + var isPathAbsolute = isAbsolute(path); + var trailingSlash = path.substr(-1) === '/'; + // Normalize the path + var normalizedPath = normalizeArray(path.split('/').filter(function (p) { return !!p; }), !isPathAbsolute).join('/'); + if (!normalizedPath && !isPathAbsolute) { + normalizedPath = '.'; + } + if (normalizedPath && trailingSlash) { + normalizedPath += '/'; + } + return (isPathAbsolute ? '/' : '') + normalizedPath; } - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; +exports.normalizePath = normalizePath; +// posix version +/** JSDoc */ +function isAbsolute(path) { + return path.charAt(0) === '/'; +} +exports.isAbsolute = isAbsolute; +// posix version +/** JSDoc */ +function join() { + var args = []; + for (var _i = 0; _i < arguments.length; _i++) { + args[_i] = arguments[_i]; } - } catch(e) {} + return normalizePath(args.join('/')); } - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; +exports.join = join; +/** JSDoc */ +function dirname(path) { + var result = splitPath(path); + var root = result[0]; + var dir = result[1]; + if (!root && !dir) { + // No dirname whatsoever + return '.'; + } + if (dir) { + // It has a dirname, strip trailing slash + dir = dir.substr(0, dir.length - 1); + } + return root + dir; } - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ - -exports.enable(load()); - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - return window.localStorage; - } catch (e) {} +exports.dirname = dirname; +/** JSDoc */ +function basename(path, ext) { + var f = splitPath(path)[2]; + if (ext && f.substr(ext.length * -1) === ext) { + f = f.substr(0, f.length - ext.length); + } + return f; } - +exports.basename = basename; +//# sourceMappingURL=path.js.map /***/ }), -/***/ 22552: -/***/ ((module, exports, __nccwpck_require__) => { - - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = __nccwpck_require__(73233); - -/** - * The currently active debug mode names, and names to skip. - */ - -exports.names = []; -exports.skips = []; +/***/ 1243: +/***/ ((__unused_webpack_module, exports) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.setPrototypeOf = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array ? setProtoOf : mixinProperties); /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + * setPrototypeOf polyfill using __proto__ */ - -exports.formatters = {}; - +// eslint-disable-next-line @typescript-eslint/ban-types +function setProtoOf(obj, proto) { + // @ts-ignore __proto__ does not exist on obj + obj.__proto__ = proto; + return obj; +} /** - * Previous log timestamp. + * setPrototypeOf polyfill using mixin */ +// eslint-disable-next-line @typescript-eslint/ban-types +function mixinProperties(obj, proto) { + for (var prop in proto) { + // eslint-disable-next-line no-prototype-builtins + if (!obj.hasOwnProperty(prop)) { + // @ts-ignore typescript complains about indexing so we remove + obj[prop] = proto[prop]; + } + } + return obj; +} +//# sourceMappingURL=polyfill.js.map -var prevTime; +/***/ }), -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ +/***/ 31811: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function selectColor(namespace) { - var hash = 0, i; +Object.defineProperty(exports, "__esModule", ({ value: true })); +var error_1 = __nccwpck_require__(66238); +var syncpromise_1 = __nccwpck_require__(87833); +/** A simple queue that holds promises. */ +var PromiseBuffer = /** @class */ (function () { + function PromiseBuffer(_limit) { + this._limit = _limit; + /** Internal set of queued Promises */ + this._buffer = []; + } + /** + * Says if the buffer is ready to take more requests + */ + PromiseBuffer.prototype.isReady = function () { + return this._limit === undefined || this.length() < this._limit; + }; + /** + * Add a promise (representing an in-flight action) to the queue, and set it to remove itself on fulfillment. + * + * @param taskProducer A function producing any PromiseLike; In previous versions this used to be `task: + * PromiseLike`, but under that model, Promises were instantly created on the call-site and their executor + * functions therefore ran immediately. Thus, even if the buffer was full, the action still happened. By + * requiring the promise to be wrapped in a function, we can defer promise creation until after the buffer + * limit check. + * @returns The original promise. + */ + PromiseBuffer.prototype.add = function (taskProducer) { + var _this = this; + if (!this.isReady()) { + return syncpromise_1.SyncPromise.reject(new error_1.SentryError('Not adding Promise due to buffer limit reached.')); + } + // start the task and add its promise to the queue + var task = taskProducer(); + if (this._buffer.indexOf(task) === -1) { + this._buffer.push(task); + } + void task + .then(function () { return _this.remove(task); }) + // Use `then(null, rejectionHandler)` rather than `catch(rejectionHandler)` so that we can use `PromiseLike` + // rather than `Promise`. `PromiseLike` doesn't have a `.catch` method, making its polyfill smaller. (ES5 didn't + // have promises, so TS has to polyfill when down-compiling.) + .then(null, function () { + return _this.remove(task).then(null, function () { + // We have to add another catch here because `this.remove()` starts a new promise chain. + }); + }); + return task; + }; + /** + * Remove a promise from the queue. + * + * @param task Can be any PromiseLike + * @returns Removed promise. + */ + PromiseBuffer.prototype.remove = function (task) { + var removedTask = this._buffer.splice(this._buffer.indexOf(task), 1)[0]; + return removedTask; + }; + /** + * This function returns the number of unresolved promises in the queue. + */ + PromiseBuffer.prototype.length = function () { + return this._buffer.length; + }; + /** + * Wait for all promises in the queue to resolve or for timeout to expire, whichever comes first. + * + * @param timeout The time, in ms, after which to resolve to `false` if the queue is still non-empty. Passing `0` (or + * not passing anything) will make the promise wait as long as it takes for the queue to drain before resolving to + * `true`. + * @returns A promise which will resolve to `true` if the queue is already empty or drains before the timeout, and + * `false` otherwise + */ + PromiseBuffer.prototype.drain = function (timeout) { + var _this = this; + return new syncpromise_1.SyncPromise(function (resolve) { + // wait for `timeout` ms and then resolve to `false` (if not cancelled first) + var capturedSetTimeout = setTimeout(function () { + if (timeout && timeout > 0) { + resolve(false); + } + }, timeout); + // if all promises resolve in time, cancel the timer and resolve to `true` + void syncpromise_1.SyncPromise.all(_this._buffer) + .then(function () { + clearTimeout(capturedSetTimeout); + resolve(true); + }) + .then(null, function () { + resolve(true); + }); + }); + }; + return PromiseBuffer; +}()); +exports.PromiseBuffer = PromiseBuffer; +//# sourceMappingURL=promisebuffer.js.map - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } +/***/ }), - return exports.colors[Math.abs(hash) % exports.colors.length]; -} +/***/ 5986: +/***/ ((__unused_webpack_module, exports) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var defaultFunctionName = ''; /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public + * Safely extract function name from itself */ - -function createDebug(namespace) { - - function debug() { - // disabled? - if (!debug.enabled) return; - - var self = debug; - - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; +function getFunctionName(fn) { + try { + if (!fn || typeof fn !== 'function') { + return defaultFunctionName; + } + return fn.name || defaultFunctionName; } - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); + catch (e) { + // Just accessing custom props in some Selenium environments + // can cause a "Permission denied" exception (see raven-js#495). + return defaultFunctionName; } - - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); - - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } - - return debug; } +exports.getFunctionName = getFunctionName; +//# sourceMappingURL=stacktrace.js.map -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; - - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; +/***/ }), - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } -} +/***/ 66538: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var is_1 = __nccwpck_require__(92757); /** - * Disable debug output. + * Truncates given string to the maximum characters count * - * @api public + * @param str An object that contains serializable values + * @param max Maximum number of characters in truncated string (0 = unlimited) + * @returns string Encoded */ - -function disable() { - exports.enable(''); +function truncate(str, max) { + if (max === void 0) { max = 0; } + if (typeof str !== 'string' || max === 0) { + return str; + } + return str.length <= max ? str : str.substr(0, max) + "..."; } - +exports.truncate = truncate; /** - * Returns true if the given mode name is enabled, false otherwise. + * This is basically just `trim_line` from + * https://github.com/getsentry/sentry/blob/master/src/sentry/lang/javascript/processor.py#L67 * - * @param {String} name - * @return {Boolean} - * @api public + * @param str An object that contains serializable values + * @param max Maximum number of characters in truncated string + * @returns string Encoded */ - -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; +function snipLine(line, colno) { + var newLine = line; + var ll = newLine.length; + if (ll <= 150) { + return newLine; } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; + if (colno > ll) { + // eslint-disable-next-line no-param-reassign + colno = ll; } - } - return false; + var start = Math.max(colno - 60, 0); + if (start < 5) { + start = 0; + } + var end = Math.min(start + 140, ll); + if (end > ll - 5) { + end = ll; + } + if (end === ll) { + start = Math.max(end - 140, 0); + } + newLine = newLine.slice(start, end); + if (start > 0) { + newLine = "'{snip} " + newLine; + } + if (end < ll) { + newLine += ' {snip}'; + } + return newLine; } - +exports.snipLine = snipLine; /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private + * Join values in array + * @param input array of values to be joined together + * @param delimiter string to be placed in-between values + * @returns Joined values */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function safeJoin(input, delimiter) { + if (!Array.isArray(input)) { + return ''; + } + var output = []; + // eslint-disable-next-line @typescript-eslint/prefer-for-of + for (var i = 0; i < input.length; i++) { + var value = input[i]; + try { + output.push(String(value)); + } + catch (e) { + output.push('[value cannot be serialized]'); + } + } + return output.join(delimiter); } - - -/***/ }), - -/***/ 7471: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - +exports.safeJoin = safeJoin; /** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. + * Checks if the value matches a regex or includes the string + * @param value The string value to be checked against + * @param pattern Either a regex or a string that must be contained in value */ - -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(15377); -} else { - module.exports = __nccwpck_require__(74117); +function isMatchingPattern(value, pattern) { + if (!is_1.isString(value)) { + return false; + } + if (is_1.isRegExp(pattern)) { + return pattern.test(value); + } + if (typeof pattern === 'string') { + return value.indexOf(pattern) !== -1; + } + return false; } - +exports.isMatchingPattern = isMatchingPattern; +//# sourceMappingURL=string.js.map /***/ }), -/***/ 74117: -/***/ ((module, exports, __nccwpck_require__) => { - -/** - * Module dependencies. - */ - -var tty = __nccwpck_require__(33867); -var util = __nccwpck_require__(31669); +/***/ 88714: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +var logger_1 = __nccwpck_require__(15577); +var misc_1 = __nccwpck_require__(32154); /** - * This is the Node.js implementation of `debug()`. + * Tells whether current environment supports ErrorEvent objects + * {@link supportsErrorEvent}. * - * Expose `debug()` as the module. - */ - -exports = module.exports = __nccwpck_require__(22552); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; - -/** - * Colors. + * @returns Answer to the given question. */ - -exports.colors = [6, 2, 3, 4, 5, 1]; - +function supportsErrorEvent() { + try { + new ErrorEvent(''); + return true; + } + catch (e) { + return false; + } +} +exports.supportsErrorEvent = supportsErrorEvent; /** - * Build up the default `inspectOpts` object from the environment variables. + * Tells whether current environment supports DOMError objects + * {@link supportsDOMError}. * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * @returns Answer to the given question. */ - -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); - - obj[prop] = val; - return obj; -}, {}); - +function supportsDOMError() { + try { + // Chrome: VM89:1 Uncaught TypeError: Failed to construct 'DOMError': + // 1 argument required, but only 0 present. + // @ts-ignore It really needs 1 argument, not 0. + new DOMError(''); + return true; + } + catch (e) { + return false; + } +} +exports.supportsDOMError = supportsDOMError; /** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * Tells whether current environment supports DOMException objects + * {@link supportsDOMException}. * - * $ DEBUG_FD=3 node script.js 3>debug.log + * @returns Answer to the given question. */ - -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - -if (1 !== fd && 2 !== fd) { - util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +function supportsDOMException() { + try { + new DOMException(''); + return true; + } + catch (e) { + return false; + } } - -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); - +exports.supportsDOMException = supportsDOMException; /** - * Is stdout a TTY? Colored output is enabled when `true`. + * Tells whether current environment supports Fetch API + * {@link supportsFetch}. + * + * @returns Answer to the given question. */ - -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); +function supportsFetch() { + if (!('fetch' in misc_1.getGlobalObject())) { + return false; + } + try { + new Headers(); + new Request(''); + new Response(); + return true; + } + catch (e) { + return false; + } } - +exports.supportsFetch = supportsFetch; /** - * Map %o to `util.inspect()`, all on a single line. + * isNativeFetch checks if the given function is a native implementation of fetch() */ - -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; - +// eslint-disable-next-line @typescript-eslint/ban-types +function isNativeFetch(func) { + return func && /^function fetch\(\)\s+\{\s+\[native code\]\s+\}$/.test(func.toString()); +} +exports.isNativeFetch = isNativeFetch; /** - * Map %o to `util.inspect()`, allowing multiple lines if needed. + * Tells whether current environment supports Fetch API natively + * {@link supportsNativeFetch}. + * + * @returns true if `window.fetch` is natively implemented, false otherwise */ - -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - +function supportsNativeFetch() { + if (!supportsFetch()) { + return false; + } + var global = misc_1.getGlobalObject(); + // Fast path to avoid DOM I/O + // eslint-disable-next-line @typescript-eslint/unbound-method + if (isNativeFetch(global.fetch)) { + return true; + } + // window.fetch is implemented, but is polyfilled or already wrapped (e.g: by a chrome extension) + // so create a "pure" iframe to see if that has native fetch + var result = false; + var doc = global.document; + // eslint-disable-next-line deprecation/deprecation + if (doc && typeof doc.createElement === "function") { + try { + var sandbox = doc.createElement('iframe'); + sandbox.hidden = true; + doc.head.appendChild(sandbox); + if (sandbox.contentWindow && sandbox.contentWindow.fetch) { + // eslint-disable-next-line @typescript-eslint/unbound-method + result = isNativeFetch(sandbox.contentWindow.fetch); + } + doc.head.removeChild(sandbox); + } + catch (err) { + logger_1.logger.warn('Could not create sandbox iframe for pure fetch check, bailing to window.fetch: ', err); + } + } + return result; +} +exports.supportsNativeFetch = supportsNativeFetch; /** - * Adds ANSI color escape codes if enabled. + * Tells whether current environment supports ReportingObserver API + * {@link supportsReportingObserver}. * - * @api public + * @returns Answer to the given question. */ - -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; - - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; - } +function supportsReportingObserver() { + return 'ReportingObserver' in misc_1.getGlobalObject(); } - +exports.supportsReportingObserver = supportsReportingObserver; /** - * Invokes `util.format()` with the specified arguments and writes to `stream`. + * Tells whether current environment supports Referrer Policy API + * {@link supportsReferrerPolicy}. + * + * @returns Answer to the given question. */ - -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); +function supportsReferrerPolicy() { + // Despite all stars in the sky saying that Edge supports old draft syntax, aka 'never', 'always', 'origin' and 'default + // https://caniuse.com/#feat=referrer-policy + // It doesn't. And it throw exception instead of ignoring this parameter... + // REF: https://github.com/getsentry/raven-js/issues/1233 + if (!supportsFetch()) { + return false; + } + try { + new Request('_', { + referrerPolicy: 'origin', + }); + return true; + } + catch (e) { + return false; + } } - +exports.supportsReferrerPolicy = supportsReferrerPolicy; /** - * Save `namespaces`. + * Tells whether current environment supports History API + * {@link supportsHistory}. * - * @param {String} namespaces - * @api private + * @returns Answer to the given question. */ - -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } +function supportsHistory() { + // NOTE: in Chrome App environment, touching history.pushState, *even inside + // a try/catch block*, will cause Chrome to output an error to console.error + // borrowed from: https://github.com/angular/angular.js/pull/13945/files + var global = misc_1.getGlobalObject(); + /* eslint-disable @typescript-eslint/no-unsafe-member-access */ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + var chrome = global.chrome; + var isChromePackagedApp = chrome && chrome.app && chrome.app.runtime; + /* eslint-enable @typescript-eslint/no-unsafe-member-access */ + var hasHistoryApi = 'history' in global && !!global.history.pushState && !!global.history.replaceState; + return !isChromePackagedApp && hasHistoryApi; } +exports.supportsHistory = supportsHistory; +//# sourceMappingURL=supports.js.map + +/***/ }), + +/***/ 87833: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +Object.defineProperty(exports, "__esModule", ({ value: true })); +/* eslint-disable @typescript-eslint/explicit-function-return-type */ +/* eslint-disable @typescript-eslint/typedef */ +/* eslint-disable @typescript-eslint/explicit-module-boundary-types */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +var is_1 = __nccwpck_require__(92757); +/** SyncPromise internal states */ +var States; +(function (States) { + /** Pending */ + States["PENDING"] = "PENDING"; + /** Resolved / OK */ + States["RESOLVED"] = "RESOLVED"; + /** Rejected / Error */ + States["REJECTED"] = "REJECTED"; +})(States || (States = {})); /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private + * Thenable class that behaves like a Promise and follows it's interface + * but is not async internally */ +var SyncPromise = /** @class */ (function () { + function SyncPromise(executor) { + var _this = this; + this._state = States.PENDING; + this._handlers = []; + /** JSDoc */ + this._resolve = function (value) { + _this._setResult(States.RESOLVED, value); + }; + /** JSDoc */ + this._reject = function (reason) { + _this._setResult(States.REJECTED, reason); + }; + /** JSDoc */ + this._setResult = function (state, value) { + if (_this._state !== States.PENDING) { + return; + } + if (is_1.isThenable(value)) { + void value.then(_this._resolve, _this._reject); + return; + } + _this._state = state; + _this._value = value; + _this._executeHandlers(); + }; + // TODO: FIXME + /** JSDoc */ + this._attachHandler = function (handler) { + _this._handlers = _this._handlers.concat(handler); + _this._executeHandlers(); + }; + /** JSDoc */ + this._executeHandlers = function () { + if (_this._state === States.PENDING) { + return; + } + var cachedHandlers = _this._handlers.slice(); + _this._handlers = []; + cachedHandlers.forEach(function (handler) { + if (handler.done) { + return; + } + if (_this._state === States.RESOLVED) { + if (handler.onfulfilled) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + handler.onfulfilled(_this._value); + } + } + if (_this._state === States.REJECTED) { + if (handler.onrejected) { + handler.onrejected(_this._value); + } + } + handler.done = true; + }); + }; + try { + executor(this._resolve, this._reject); + } + catch (e) { + this._reject(e); + } + } + /** JSDoc */ + SyncPromise.resolve = function (value) { + return new SyncPromise(function (resolve) { + resolve(value); + }); + }; + /** JSDoc */ + SyncPromise.reject = function (reason) { + return new SyncPromise(function (_, reject) { + reject(reason); + }); + }; + /** JSDoc */ + SyncPromise.all = function (collection) { + return new SyncPromise(function (resolve, reject) { + if (!Array.isArray(collection)) { + reject(new TypeError("Promise.all requires an array as input.")); + return; + } + if (collection.length === 0) { + resolve([]); + return; + } + var counter = collection.length; + var resolvedCollection = []; + collection.forEach(function (item, index) { + void SyncPromise.resolve(item) + .then(function (value) { + resolvedCollection[index] = value; + counter -= 1; + if (counter !== 0) { + return; + } + resolve(resolvedCollection); + }) + .then(null, reject); + }); + }); + }; + /** JSDoc */ + SyncPromise.prototype.then = function (onfulfilled, onrejected) { + var _this = this; + return new SyncPromise(function (resolve, reject) { + _this._attachHandler({ + done: false, + onfulfilled: function (result) { + if (!onfulfilled) { + // TODO: ¯\_(ツ)_/¯ + // TODO: FIXME + resolve(result); + return; + } + try { + resolve(onfulfilled(result)); + return; + } + catch (e) { + reject(e); + return; + } + }, + onrejected: function (reason) { + if (!onrejected) { + reject(reason); + return; + } + try { + resolve(onrejected(reason)); + return; + } + catch (e) { + reject(e); + return; + } + }, + }); + }); + }; + /** JSDoc */ + SyncPromise.prototype.catch = function (onrejected) { + return this.then(function (val) { return val; }, onrejected); + }; + /** JSDoc */ + SyncPromise.prototype.finally = function (onfinally) { + var _this = this; + return new SyncPromise(function (resolve, reject) { + var val; + var isRejected; + return _this.then(function (value) { + isRejected = false; + val = value; + if (onfinally) { + onfinally(); + } + }, function (reason) { + isRejected = true; + val = reason; + if (onfinally) { + onfinally(); + } + }).then(function () { + if (isRejected) { + reject(val); + return; + } + resolve(val); + }); + }); + }; + /** JSDoc */ + SyncPromise.prototype.toString = function () { + return '[object SyncPromise]'; + }; + return SyncPromise; +}()); +exports.SyncPromise = SyncPromise; +//# sourceMappingURL=syncpromise.js.map -function load() { - return process.env.DEBUG; -} +/***/ }), + +/***/ 1735: +/***/ ((module, exports, __nccwpck_require__) => { +/* module decorator */ module = __nccwpck_require__.nmd(module); +Object.defineProperty(exports, "__esModule", ({ value: true })); +var misc_1 = __nccwpck_require__(32154); +var node_1 = __nccwpck_require__(16411); /** - * Copied from `node/src/node.js`. + * A TimestampSource implementation for environments that do not support the Performance Web API natively. * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + * Note that this TimestampSource does not use a monotonic clock. A call to `nowSeconds` may return a timestamp earlier + * than a previously returned value. We do not try to emulate a monotonic behavior in order to facilitate debugging. It + * is more obvious to explain "why does my span have negative duration" than "why my spans have zero duration". */ - -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); - - // Note stream._type is used for test-module-load-list.js - - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; - - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; - - case 'FILE': - var fs = __nccwpck_require__(35747); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; - - case 'PIPE': - case 'TCP': - var net = __nccwpck_require__(11631); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); - - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; - - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; - - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } - - // For supporting legacy API we put the FD here. - stream.fd = fd; - - stream._isStdio = true; - - return stream; -} - +var dateTimestampSource = { + nowSeconds: function () { return Date.now() / 1000; }, +}; /** - * Init logic for `debug` instances. + * Returns a wrapper around the native Performance API browser implementation, or undefined for browsers that do not + * support the API. * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * Wrapping the native API works around differences in behavior from different browsers. */ - -function init (debug) { - debug.inspectOpts = {}; - - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } +function getBrowserPerformance() { + var performance = misc_1.getGlobalObject().performance; + if (!performance || !performance.now) { + return undefined; + } + // Replace performance.timeOrigin with our own timeOrigin based on Date.now(). + // + // This is a partial workaround for browsers reporting performance.timeOrigin such that performance.timeOrigin + + // performance.now() gives a date arbitrarily in the past. + // + // Additionally, computing timeOrigin in this way fills the gap for browsers where performance.timeOrigin is + // undefined. + // + // The assumption that performance.timeOrigin + performance.now() ~= Date.now() is flawed, but we depend on it to + // interact with data coming out of performance entries. + // + // Note that despite recommendations against it in the spec, browsers implement the Performance API with a clock that + // might stop when the computer is asleep (and perhaps under other circumstances). Such behavior causes + // performance.timeOrigin + performance.now() to have an arbitrary skew over Date.now(). In laptop computers, we have + // observed skews that can be as long as days, weeks or months. + // + // See https://github.com/getsentry/sentry-javascript/issues/2590. + // + // BUG: despite our best intentions, this workaround has its limitations. It mostly addresses timings of pageload + // transactions, but ignores the skew built up over time that can aversely affect timestamps of navigation + // transactions of long-lived web pages. + var timeOrigin = Date.now() - performance.now(); + return { + now: function () { return performance.now(); }, + timeOrigin: timeOrigin, + }; } - /** - * Enable namespaces listed in `process.env.DEBUG` initially. + * Returns the native Performance API implementation from Node.js. Returns undefined in old Node.js versions that don't + * implement the API. */ - -exports.enable(load()); - - -/***/ }), - -/***/ 73233: -/***/ ((module) => { - +function getNodePerformance() { + try { + var perfHooks = node_1.dynamicRequire(module, 'perf_hooks'); + return perfHooks.performance; + } + catch (_) { + return undefined; + } +} /** - * Helpers. + * The Performance API implementation for the current platform, if available. */ - -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; - +var platformPerformance = node_1.isNodeEnv() ? getNodePerformance() : getBrowserPerformance(); +var timestampSource = platformPerformance === undefined + ? dateTimestampSource + : { + nowSeconds: function () { return (platformPerformance.timeOrigin + platformPerformance.now()) / 1000; }, + }; /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public + * Returns a timestamp in seconds since the UNIX epoch using the Date API. */ - -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; - +exports.dateTimestampInSeconds = dateTimestampSource.nowSeconds.bind(dateTimestampSource); /** - * Parse the given `str` and return milliseconds. + * Returns a timestamp in seconds since the UNIX epoch using either the Performance or Date APIs, depending on the + * availability of the Performance API. * - * @param {String} str - * @return {Number} - * @api private - */ - -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} - -/** - * Short format for `ms`. + * See `usingPerformanceAPI` to test whether the Performance API is used. * - * @param {Number} ms - * @return {String} - * @api private + * BUG: Note that because of how browsers implement the Performance API, the clock might stop when the computer is + * asleep. This creates a skew between `dateTimestampInSeconds` and `timestampInSeconds`. The + * skew can grow to arbitrary amounts like days, weeks or months. + * See https://github.com/getsentry/sentry-javascript/issues/2590. */ - -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} - +exports.timestampInSeconds = timestampSource.nowSeconds.bind(timestampSource); +// Re-exported with an old name for backwards-compatibility. +exports.timestampWithMs = exports.timestampInSeconds; /** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private + * A boolean that is true when timestampInSeconds uses the Performance API to produce monotonic timestamps. */ - -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} - +exports.usingPerformanceAPI = platformPerformance !== undefined; /** - * Pluralization helper. + * The number of milliseconds since the UNIX epoch. This value is only usable in a browser, and only when the + * performance API is available. */ - -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; - } - return Math.ceil(ms / n) + ' ' + name + 's'; -} - - -/***/ }), - -/***/ 85442: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Batcher, Events, parser; -parser = __nccwpck_require__(67823); -Events = __nccwpck_require__(107); - -Batcher = function () { - class Batcher { - constructor(options = {}) { - this.options = options; - parser.load(this.options, this.defaults, this); - this.Events = new Events(this); - this._arr = []; - - this._resetPromise(); - - this._lastFlush = Date.now(); - } - - _resetPromise() { - return this._promise = new this.Promise((res, rej) => { - return this._resolve = res; - }); - } - - _flush() { - clearTimeout(this._timeout); - this._lastFlush = Date.now(); - - this._resolve(); - - this.Events.trigger("batch", this._arr); - this._arr = []; - return this._resetPromise(); - } - - add(data) { - var ret; - - this._arr.push(data); - - ret = this._promise; - - if (this._arr.length === this.maxSize) { - this._flush(); - } else if (this.maxTime != null && this._arr.length === 1) { - this._timeout = setTimeout(() => { - return this._flush(); - }, this.maxTime); - } - - return ret; +exports.browserPerformanceTimeOrigin = (function () { + // Unfortunately browsers may report an inaccurate time origin data, through either performance.timeOrigin or + // performance.timing.navigationStart, which results in poor results in performance data. We only treat time origin + // data as reliable if they are within a reasonable threshold of the current time. + var performance = misc_1.getGlobalObject().performance; + if (!performance || !performance.now) { + exports._browserPerformanceTimeOriginMode = 'none'; + return undefined; } - - } - - ; - Batcher.prototype.defaults = { - maxTime: null, - maxSize: null, - Promise: Promise - }; - return Batcher; -}.call(void 0); - -module.exports = Batcher; - -/***/ }), - -/***/ 83911: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } - -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } - -function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } - -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } - -function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } - -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - -var Bottleneck, - DEFAULT_PRIORITY, - Events, - LocalDatastore, - NUM_PRIORITIES, - Queues, - RedisDatastore, - States, - Sync, - parser, - splice = [].splice; -NUM_PRIORITIES = 10; -DEFAULT_PRIORITY = 5; -parser = __nccwpck_require__(67823); -Queues = __nccwpck_require__(65893); -LocalDatastore = __nccwpck_require__(38979); -RedisDatastore = __nccwpck_require__(4946); -Events = __nccwpck_require__(107); -States = __nccwpck_require__(2527); -Sync = __nccwpck_require__(56029); - -Bottleneck = function () { - class Bottleneck { - constructor(options = {}, ...invalid) { - var storeInstanceOptions, storeOptions; - this._drainOne = this._drainOne.bind(this); - this.submit = this.submit.bind(this); - this.schedule = this.schedule.bind(this); - this.updateSettings = this.updateSettings.bind(this); - this.incrementReservoir = this.incrementReservoir.bind(this); - - this._validateOptions(options, invalid); - - parser.load(options, this.instanceDefaults, this); - this._queues = new Queues(NUM_PRIORITIES); - this._scheduled = {}; - this._states = new States(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); - this._limiter = null; - this.Events = new Events(this); - this._submitLock = new Sync("submit", this.Promise); - this._registerLock = new Sync("register", this.Promise); - storeOptions = parser.load(options, this.storeDefaults, {}); - - this._store = function () { - if (this.datastore === "redis" || this.datastore === "ioredis" || this.connection != null) { - storeInstanceOptions = parser.load(options, this.redisStoreDefaults, {}); - return new RedisDatastore(this, storeOptions, storeInstanceOptions); - } else if (this.datastore === "local") { - storeInstanceOptions = parser.load(options, this.localStoreDefaults, {}); - return new LocalDatastore(this, storeOptions, storeInstanceOptions); - } else { - throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); + var threshold = 3600 * 1000; + var performanceNow = performance.now(); + var dateNow = Date.now(); + // if timeOrigin isn't available set delta to threshold so it isn't used + var timeOriginDelta = performance.timeOrigin + ? Math.abs(performance.timeOrigin + performanceNow - dateNow) + : threshold; + var timeOriginIsReliable = timeOriginDelta < threshold; + // While performance.timing.navigationStart is deprecated in favor of performance.timeOrigin, performance.timeOrigin + // is not as widely supported. Namely, performance.timeOrigin is undefined in Safari as of writing. + // Also as of writing, performance.timing is not available in Web Workers in mainstream browsers, so it is not always + // a valid fallback. In the absence of an initial time provided by the browser, fallback to the current time from the + // Date API. + // eslint-disable-next-line deprecation/deprecation + var navigationStart = performance.timing && performance.timing.navigationStart; + var hasNavigationStart = typeof navigationStart === 'number'; + // if navigationStart isn't available set delta to threshold so it isn't used + var navigationStartDelta = hasNavigationStart ? Math.abs(navigationStart + performanceNow - dateNow) : threshold; + var navigationStartIsReliable = navigationStartDelta < threshold; + if (timeOriginIsReliable || navigationStartIsReliable) { + // Use the more reliable time origin + if (timeOriginDelta <= navigationStartDelta) { + exports._browserPerformanceTimeOriginMode = 'timeOrigin'; + return performance.timeOrigin; + } + else { + exports._browserPerformanceTimeOriginMode = 'navigationStart'; + return navigationStart; } - }.call(this); - - this._queues.on("leftzero", () => { - var base; - return typeof (base = this._store.heartbeat).ref === "function" ? base.ref() : void 0; - }); - - this._queues.on("zero", () => { - var base; - return typeof (base = this._store.heartbeat).unref === "function" ? base.unref() : void 0; - }); - } - - _validateOptions(options, invalid) { - if (!(options != null && typeof options === "object" && invalid.length === 0)) { - throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); - } - } - - ready() { - return this._store.ready; - } - - clients() { - return this._store.clients; - } - - channel() { - return `b_${this.id}`; - } - - channel_client() { - return `b_${this.id}_${this._store.clientId}`; - } - - publish(message) { - return this._store.__publish__(message); - } - - disconnect(flush = true) { - return this._store.__disconnect__(flush); - } - - chain(_limiter) { - this._limiter = _limiter; - return this; } + // Either both timeOrigin and navigationStart are skewed or neither is available, fallback to Date. + exports._browserPerformanceTimeOriginMode = 'dateNow'; + return dateNow; +})(); +//# sourceMappingURL=time.js.map - queued(priority) { - return this._queues.queued(priority); - } +/***/ }), - clusterQueued() { - return this._store.__queued__(); - } +/***/ 83633: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - empty() { - return this.queued() === 0 && this._submitLock.isEmpty(); - } +"use strict"; +/*! + * accepts + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ - running() { - return this._store.__running__(); - } - done() { - return this._store.__done__(); - } - jobStatus(id) { - return this._states.jobStatus(id); - } +/** + * Module dependencies. + * @private + */ - jobs(status) { - return this._states.statusJobs(status); - } +var Negotiator = __nccwpck_require__(95385) +var mime = __nccwpck_require__(43583) - counts() { - return this._states.statusCounts(); - } +/** + * Module exports. + * @public + */ - _sanitizePriority(priority) { - var sProperty; - sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; +module.exports = Accepts - if (sProperty < 0) { - return 0; - } else if (sProperty > NUM_PRIORITIES - 1) { - return NUM_PRIORITIES - 1; - } else { - return sProperty; - } - } +/** + * Create a new Accepts object for the given req. + * + * @param {object} req + * @public + */ - _randomIndex() { - return Math.random().toString(36).slice(2); - } +function Accepts (req) { + if (!(this instanceof Accepts)) { + return new Accepts(req) + } - check(weight = 1) { - return this._store.__check__(weight); - } + this.headers = req.headers + this.negotiator = new Negotiator(req) +} - _run(next, wait, index, retryCount) { - var _this = this; +/** + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single mime type string + * such as "application/json", the extension name + * such as "json" or an array `["json", "html", "text/plain"]`. When a list + * or array is given the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * this.types('html'); + * // => "html" + * + * // Accept: text/*, application/json + * this.types('html'); + * // => "html" + * this.types('text/html'); + * // => "text/html" + * this.types('json', 'text'); + * // => "json" + * this.types('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * this.types('image/png'); + * this.types('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * this.types(['html', 'json']); + * this.types('html', 'json'); + * // => "json" + * + * @param {String|Array} types... + * @return {String|Array|Boolean} + * @public + */ - var completed, done; - this.Events.trigger("debug", `Scheduling ${next.options.id}`, { - args: next.args, - options: next.options - }); - done = false; +Accepts.prototype.type = +Accepts.prototype.types = function (types_) { + var types = types_ - completed = - /*#__PURE__*/ - function () { - var _ref = _asyncToGenerator(function* (...args) { - var e, error, eventInfo, retry, retryAfter, running; + // support flattened arguments + if (types && !Array.isArray(types)) { + types = new Array(arguments.length) + for (var i = 0; i < types.length; i++) { + types[i] = arguments[i] + } + } - if (!done) { - try { - done = true; - clearTimeout(_this._scheduled[index].expiration); - delete _this._scheduled[index]; - eventInfo = { - args: next.args, - options: next.options, - retryCount - }; + // no types, return all requested types + if (!types || types.length === 0) { + return this.negotiator.mediaTypes() + } - if ((error = args[0]) != null) { - retry = yield _this.Events.trigger("failed", error, eventInfo); + // no accept header, return first given type + if (!this.headers.accept) { + return types[0] + } - if (retry != null) { - retryAfter = ~~retry; + var mimes = types.map(extToMime) + var accepts = this.negotiator.mediaTypes(mimes.filter(validMime)) + var first = accepts[0] - _this.Events.trigger("retry", `Retrying ${next.options.id} after ${retryAfter} ms`, eventInfo); + return first + ? types[mimes.indexOf(first)] + : false +} - return _this._run(next, retryAfter, index, retryCount + 1); - } - } +/** + * Return accepted encodings or best fit based on `encodings`. + * + * Given `Accept-Encoding: gzip, deflate` + * an array sorted by quality is returned: + * + * ['gzip', 'deflate'] + * + * @param {String|Array} encodings... + * @return {String|Array} + * @public + */ - _this._states.next(next.options.id); // DONE +Accepts.prototype.encoding = +Accepts.prototype.encodings = function (encodings_) { + var encodings = encodings_ + // support flattened arguments + if (encodings && !Array.isArray(encodings)) { + encodings = new Array(arguments.length) + for (var i = 0; i < encodings.length; i++) { + encodings[i] = arguments[i] + } + } - _this.Events.trigger("debug", `Completed ${next.options.id}`, eventInfo); + // no encodings, return all requested encodings + if (!encodings || encodings.length === 0) { + return this.negotiator.encodings() + } - _this.Events.trigger("done", `Completed ${next.options.id}`, eventInfo); + return this.negotiator.encodings(encodings)[0] || false +} - var _ref2 = yield _this._store.__free__(index, next.options.weight); +/** + * Return accepted charsets or best fit based on `charsets`. + * + * Given `Accept-Charset: utf-8, iso-8859-1;q=0.2, utf-7;q=0.5` + * an array sorted by quality is returned: + * + * ['utf-8', 'utf-7', 'iso-8859-1'] + * + * @param {String|Array} charsets... + * @return {String|Array} + * @public + */ - running = _ref2.running; +Accepts.prototype.charset = +Accepts.prototype.charsets = function (charsets_) { + var charsets = charsets_ - _this.Events.trigger("debug", `Freed ${next.options.id}`, eventInfo); + // support flattened arguments + if (charsets && !Array.isArray(charsets)) { + charsets = new Array(arguments.length) + for (var i = 0; i < charsets.length; i++) { + charsets[i] = arguments[i] + } + } - if (running === 0 && _this.empty()) { - _this.Events.trigger("idle"); - } + // no charsets, return all requested charsets + if (!charsets || charsets.length === 0) { + return this.negotiator.charsets() + } - return typeof next.cb === "function" ? next.cb(...args) : void 0; - } catch (error1) { - e = error1; - return _this.Events.trigger("error", e); - } - } - }); + return this.negotiator.charsets(charsets)[0] || false +} - return function completed() { - return _ref.apply(this, arguments); - }; - }(); +/** + * Return accepted languages or best fit based on `langs`. + * + * Given `Accept-Language: en;q=0.8, es, pt` + * an array sorted by quality is returned: + * + * ['es', 'pt', 'en'] + * + * @param {String|Array} langs... + * @return {Array|String} + * @public + */ - if (retryCount === 0) { - // RUNNING - this._states.next(next.options.id); - } +Accepts.prototype.lang = +Accepts.prototype.langs = +Accepts.prototype.language = +Accepts.prototype.languages = function (languages_) { + var languages = languages_ - return this._scheduled[index] = { - timeout: setTimeout(() => { - this.Events.trigger("debug", `Executing ${next.options.id}`, { - args: next.args, - options: next.options - }); + // support flattened arguments + if (languages && !Array.isArray(languages)) { + languages = new Array(arguments.length) + for (var i = 0; i < languages.length; i++) { + languages[i] = arguments[i] + } + } - if (retryCount === 0) { - // EXECUTING - this._states.next(next.options.id); - } + // no languages, return all requested languages + if (!languages || languages.length === 0) { + return this.negotiator.languages() + } - if (this._limiter != null) { - return this._limiter.submit(next.options, next.task, ...next.args, completed); - } else { - return next.task(...next.args, completed); - } - }, wait), - expiration: next.options.expiration != null ? setTimeout(() => { - return completed(new Bottleneck.prototype.BottleneckError(`This job timed out after ${next.options.expiration} ms.`)); - }, wait + next.options.expiration) : void 0, - job: next - }; - } + return this.negotiator.languages(languages)[0] || false +} - _drainOne(capacity) { - return this._registerLock.schedule(() => { - var args, index, next, options, queue; +/** + * Convert extnames to mime. + * + * @param {String} type + * @return {String} + * @private + */ - if (this.queued() === 0) { - return this.Promise.resolve(null); - } +function extToMime (type) { + return type.indexOf('/') === -1 + ? mime.lookup(type) + : type +} - queue = this._queues.getFirst(); +/** + * Check if mime is valid. + * + * @param {String} type + * @return {String} + * @private + */ - var _next2 = next = queue.first(); +function validMime (type) { + return typeof type === 'string' +} - options = _next2.options; - args = _next2.args; - if (capacity != null && options.weight > capacity) { - return this.Promise.resolve(null); - } +/***/ }), - this.Events.trigger("debug", `Draining ${options.id}`, { - args, - options - }); - index = this._randomIndex(); - return this._store.__register__(index, options.weight, options.expiration).then(({ - success, - wait, - reservoir - }) => { - var empty; - this.Events.trigger("debug", `Drained ${options.id}`, { - success, - args, - options - }); +/***/ 49690: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { - if (success) { - queue.shift(); - empty = this.empty(); +"use strict"; - if (empty) { - this.Events.trigger("empty"); +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const events_1 = __nccwpck_require__(28614); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const promisify_1 = __importDefault(__nccwpck_require__(66570)); +const debug = debug_1.default('agent-base'); +function isAgent(v) { + return Boolean(v) && typeof v.addRequest === 'function'; +} +function isSecureEndpoint() { + const { stack } = new Error(); + if (typeof stack !== 'string') + return false; + return stack.split('\n').some(l => l.indexOf('(https.js:') !== -1 || l.indexOf('node:https:') !== -1); +} +function createAgent(callback, opts) { + return new createAgent.Agent(callback, opts); +} +(function (createAgent) { + /** + * Base `http.Agent` implementation. + * No pooling/keep-alive is implemented by default. + * + * @param {Function} callback + * @api public + */ + class Agent extends events_1.EventEmitter { + constructor(callback, _opts) { + super(); + let opts = _opts; + if (typeof callback === 'function') { + this.callback = callback; } - - if (reservoir === 0) { - this.Events.trigger("depleted", empty); + else if (callback) { + opts = callback; + } + // Timeout for the socket to be returned from the callback + this.timeout = null; + if (opts && typeof opts.timeout === 'number') { + this.timeout = opts.timeout; + } + // These aren't actually used by `agent-base`, but are required + // for the TypeScript definition files in `@types/node` :/ + this.maxFreeSockets = 1; + this.maxSockets = 1; + this.maxTotalSockets = Infinity; + this.sockets = {}; + this.freeSockets = {}; + this.requests = {}; + this.options = {}; + } + get defaultPort() { + if (typeof this.explicitDefaultPort === 'number') { + return this.explicitDefaultPort; + } + return isSecureEndpoint() ? 443 : 80; + } + set defaultPort(v) { + this.explicitDefaultPort = v; + } + get protocol() { + if (typeof this.explicitProtocol === 'string') { + return this.explicitProtocol; + } + return isSecureEndpoint() ? 'https:' : 'http:'; + } + set protocol(v) { + this.explicitProtocol = v; + } + callback(req, opts, fn) { + throw new Error('"agent-base" has no default implementation, you must subclass and override `callback()`'); + } + /** + * Called by node-core's "_http_client.js" module when creating + * a new HTTP request with this Agent instance. + * + * @api public + */ + addRequest(req, _opts) { + const opts = Object.assign({}, _opts); + if (typeof opts.secureEndpoint !== 'boolean') { + opts.secureEndpoint = isSecureEndpoint(); + } + if (opts.host == null) { + opts.host = 'localhost'; + } + if (opts.port == null) { + opts.port = opts.secureEndpoint ? 443 : 80; + } + if (opts.protocol == null) { + opts.protocol = opts.secureEndpoint ? 'https:' : 'http:'; + } + if (opts.host && opts.path) { + // If both a `host` and `path` are specified then it's most + // likely the result of a `url.parse()` call... we need to + // remove the `path` portion so that `net.connect()` doesn't + // attempt to open that as a unix socket file. + delete opts.path; + } + delete opts.agent; + delete opts.hostname; + delete opts._defaultAgent; + delete opts.defaultPort; + delete opts.createConnection; + // Hint to use "Connection: close" + // XXX: non-documented `http` module API :( + req._last = true; + req.shouldKeepAlive = false; + let timedOut = false; + let timeoutId = null; + const timeoutMs = opts.timeout || this.timeout; + const onerror = (err) => { + if (req._hadError) + return; + req.emit('error', err); + // For Safety. Some additional errors might fire later on + // and we need to make sure we don't double-fire the error event. + req._hadError = true; + }; + const ontimeout = () => { + timeoutId = null; + timedOut = true; + const err = new Error(`A "socket" was not created for HTTP request before ${timeoutMs}ms`); + err.code = 'ETIMEOUT'; + onerror(err); + }; + const callbackError = (err) => { + if (timedOut) + return; + if (timeoutId !== null) { + clearTimeout(timeoutId); + timeoutId = null; + } + onerror(err); + }; + const onsocket = (socket) => { + if (timedOut) + return; + if (timeoutId != null) { + clearTimeout(timeoutId); + timeoutId = null; + } + if (isAgent(socket)) { + // `socket` is actually an `http.Agent` instance, so + // relinquish responsibility for this `req` to the Agent + // from here on + debug('Callback returned another Agent instance %o', socket.constructor.name); + socket.addRequest(req, opts); + return; + } + if (socket) { + socket.once('free', () => { + this.freeSocket(socket, opts); + }); + req.onSocket(socket); + return; + } + const err = new Error(`no Duplex stream was returned to agent-base for \`${req.method} ${req.path}\``); + onerror(err); + }; + if (typeof this.callback !== 'function') { + onerror(new Error('`callback` is not defined')); + return; + } + if (!this.promisifiedCallback) { + if (this.callback.length >= 3) { + debug('Converting legacy callback function to promise'); + this.promisifiedCallback = promisify_1.default(this.callback); + } + else { + this.promisifiedCallback = this.callback; + } + } + if (typeof timeoutMs === 'number' && timeoutMs > 0) { + timeoutId = setTimeout(ontimeout, timeoutMs); + } + if ('port' in opts && typeof opts.port !== 'number') { + opts.port = Number(opts.port); + } + try { + debug('Resolving socket for %o request: %o', opts.protocol, `${req.method} ${req.path}`); + Promise.resolve(this.promisifiedCallback(req, opts)).then(onsocket, callbackError); + } + catch (err) { + Promise.reject(err).catch(callbackError); } - - this._run(next, wait, index, 0); - - return this.Promise.resolve(options.weight); - } else { - return this.Promise.resolve(null); - } - }); - }); - } - - _drainAll(capacity, total = 0) { - return this._drainOne(capacity).then(drained => { - var newCapacity; - - if (drained != null) { - newCapacity = capacity != null ? capacity - drained : capacity; - return this._drainAll(newCapacity, total + drained); - } else { - return this.Promise.resolve(total); } - }).catch(e => { - return this.Events.trigger("error", e); - }); - } - - _drop(job, message = "This job has been dropped by Bottleneck") { - if (this._states.remove(job.options.id)) { - if (this.rejectOnDrop) { - if (typeof job.cb === "function") { - job.cb(new Bottleneck.prototype.BottleneckError(message)); - } + freeSocket(socket, opts) { + debug('Freeing socket %o %o', socket.constructor.name, opts); + socket.destroy(); + } + destroy() { + debug('Destroying agent %o', this.constructor.name); } - - return this.Events.trigger("dropped", job); - } - } - - _dropAllQueued(message) { - return this._queues.shiftAll(job => { - return this._drop(job, message); - }); } + createAgent.Agent = Agent; + // So that `instanceof` works correctly + createAgent.prototype = createAgent.Agent.prototype; +})(createAgent || (createAgent = {})); +module.exports = createAgent; +//# sourceMappingURL=index.js.map - stop(options = {}) { - var done, waitForExecuting; - options = parser.load(options, this.stopDefaults); +/***/ }), - waitForExecuting = at => { - var finished; +/***/ 66570: +/***/ ((__unused_webpack_module, exports) => { - finished = () => { - var counts; - counts = this._states.counts; - return counts[0] + counts[1] + counts[2] + counts[3] === at; - }; +"use strict"; - return new this.Promise((resolve, reject) => { - if (finished()) { - return resolve(); - } else { - return this.on("done", () => { - if (finished()) { - this.removeAllListeners("done"); - return resolve(); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +function promisify(fn) { + return function (req, opts) { + return new Promise((resolve, reject) => { + fn.call(this, req, opts, (err, rtn) => { + if (err) { + reject(err); + } + else { + resolve(rtn); + } }); - } }); - }; - - done = options.dropWaitingJobs ? (this._run = next => { - return this._drop(next, options.dropErrorMessage); - }, this._drainOne = () => { - return this.Promise.resolve(null); - }, this._registerLock.schedule(() => { - return this._submitLock.schedule(() => { - var k, ref, v; - ref = this._scheduled; - - for (k in ref) { - v = ref[k]; + }; +} +exports.default = promisify; +//# sourceMappingURL=promisify.js.map - if (this.jobStatus(v.job.options.id) === "RUNNING") { - clearTimeout(v.timeout); - clearTimeout(v.expiration); +/***/ }), - this._drop(v.job, options.dropErrorMessage); - } - } +/***/ 61231: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this._dropAllQueued(options.dropErrorMessage); +"use strict"; - return waitForExecuting(0); - }); - })) : this.schedule({ - priority: NUM_PRIORITIES - 1, - weight: 0 - }, () => { - return waitForExecuting(1); - }); +const indentString = __nccwpck_require__(98043); +const cleanStack = __nccwpck_require__(27972); - this.submit = (...args) => { - var _ref3, _ref4, _splice$call, _splice$call2; +const cleanInternalStack = stack => stack.replace(/\s+at .*aggregate-error\/index.js:\d+:\d+\)?/g, ''); - var cb, ref; - ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), args = _ref4.slice(0), _ref3), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call); - return typeof cb === "function" ? cb(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)) : void 0; - }; +class AggregateError extends Error { + constructor(errors) { + if (!Array.isArray(errors)) { + throw new TypeError(`Expected input to be an Array, got ${typeof errors}`); + } - this.stop = () => { - return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); - }; + errors = [...errors].map(error => { + if (error instanceof Error) { + return error; + } - return done; - } + if (error !== null && typeof error === 'object') { + // Handle plain error objects with message property and/or possibly other metadata + return Object.assign(new Error(error.message), error); + } - submit(...args) { - var _this2 = this; + return new Error(error); + }); - var cb, job, options, ref, ref1, task; + let message = errors + .map(error => { + // The `stack` property is not standardized, so we can't assume it exists + return typeof error.stack === 'string' ? cleanInternalStack(cleanStack(error.stack)) : String(error); + }) + .join('\n'); + message = '\n' + indentString(message, 4); + super(message); - if (typeof args[0] === "function") { - var _ref5, _ref6, _splice$call3, _splice$call4; + this.name = 'AggregateError'; - ref = args, (_ref5 = ref, _ref6 = _toArray(_ref5), task = _ref6[0], args = _ref6.slice(1), _ref5), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3); - options = parser.load({}, this.jobDefaults, {}); - } else { - var _ref7, _ref8, _splice$call5, _splice$call6; + Object.defineProperty(this, '_errors', {value: errors}); + } - ref1 = args, (_ref7 = ref1, _ref8 = _toArray(_ref7), options = _ref8[0], task = _ref8[1], args = _ref8.slice(2), _ref7), (_splice$call5 = splice.call(args, -1), _splice$call6 = _slicedToArray(_splice$call5, 1), cb = _splice$call6[0], _splice$call5); - options = parser.load(options, this.jobDefaults); - } + * [Symbol.iterator]() { + for (const error of this._errors) { + yield error; + } + } +} - job = { - options, - task, - args, - cb - }; - options.priority = this._sanitizePriority(options.priority); +module.exports = AggregateError; - if (options.id === this.jobDefaults.id) { - options.id = `${options.id}-${this._randomIndex()}`; - } - if (this.jobStatus(options.id) != null) { - if (typeof job.cb === "function") { - job.cb(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${options.id})`)); - } +/***/ }), - return false; - } +/***/ 62003: +/***/ ((module) => { - this._states.start(options.id); // RECEIVED +"use strict"; - this.Events.trigger("debug", `Queueing ${options.id}`, { - args, - options - }); - return this._submitLock.schedule( - /*#__PURE__*/ - _asyncToGenerator(function* () { - var blocked, e, reachedHWM, shifted, strategy; +/** + * Expose `arrayFlatten`. + */ +module.exports = arrayFlatten - try { - var _ref10 = yield _this2._store.__submit__(_this2.queued(), options.weight); +/** + * Recursive flatten function with depth. + * + * @param {Array} array + * @param {Array} result + * @param {Number} depth + * @return {Array} + */ +function flattenWithDepth (array, result, depth) { + for (var i = 0; i < array.length; i++) { + var value = array[i] - reachedHWM = _ref10.reachedHWM; - blocked = _ref10.blocked; - strategy = _ref10.strategy; + if (depth > 0 && Array.isArray(value)) { + flattenWithDepth(value, result, depth - 1) + } else { + result.push(value) + } + } - _this2.Events.trigger("debug", `Queued ${options.id}`, { - args, - options, - reachedHWM, - blocked - }); - } catch (error1) { - e = error1; + return result +} - _this2._states.remove(options.id); +/** + * Recursive flatten function. Omitting depth is slightly faster. + * + * @param {Array} array + * @param {Array} result + * @return {Array} + */ +function flattenForever (array, result) { + for (var i = 0; i < array.length; i++) { + var value = array[i] - _this2.Events.trigger("debug", `Could not queue ${options.id}`, { - args, - options, - error: e - }); + if (Array.isArray(value)) { + flattenForever(value, result) + } else { + result.push(value) + } + } - if (typeof job.cb === "function") { - job.cb(e); - } + return result +} - return false; - } +/** + * Flatten an array, with the ability to define a depth. + * + * @param {Array} array + * @param {Number} depth + * @return {Array} + */ +function arrayFlatten (array, depth) { + if (depth == null) { + return flattenForever(array, []) + } - if (blocked) { - _this2._drop(job); + return flattenWithDepth(array, [], depth) +} - return true; - } else if (reachedHWM) { - shifted = strategy === Bottleneck.prototype.strategy.LEAK ? _this2._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? _this2._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; - if (shifted != null) { - _this2._drop(shifted); - } +/***/ }), - if (shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW) { - if (shifted == null) { - _this2._drop(job); - } +/***/ 14812: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return reachedHWM; - } - } +module.exports = +{ + parallel : __nccwpck_require__(8210), + serial : __nccwpck_require__(50445), + serialOrdered : __nccwpck_require__(3578) +}; - _this2._states.next(job.options.id); // QUEUED +/***/ }), - _this2._queues.push(options.priority, job); +/***/ 1700: +/***/ ((module) => { - yield _this2._drainAll(); - return reachedHWM; - })); - } +// API +module.exports = abort; - schedule(...args) { - var options, task, wrapped; +/** + * Aborts leftover active jobs + * + * @param {object} state - current state object + */ +function abort(state) +{ + Object.keys(state.jobs).forEach(clean.bind(state)); - if (typeof args[0] === "function") { - var _args = args; + // reset leftover jobs + state.jobs = {}; +} - var _args2 = _toArray(_args); +/** + * Cleans up leftover job by invoking abort function for the provided job id + * + * @this state + * @param {string|number} key - job id to abort + */ +function clean(key) +{ + if (typeof this.jobs[key] == 'function') + { + this.jobs[key](); + } +} - task = _args2[0]; - args = _args2.slice(1); - options = parser.load({}, this.jobDefaults, {}); - } else { - var _args3 = args; - var _args4 = _toArray(_args3); +/***/ }), - options = _args4[0]; - task = _args4[1]; - args = _args4.slice(2); - options = parser.load(options, this.jobDefaults); - } +/***/ 72794: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - wrapped = (...args) => { - var _ref11, _ref12, _splice$call7, _splice$call8; +var defer = __nccwpck_require__(15295); - var cb, e, ref, returned; - ref = args, (_ref11 = ref, _ref12 = _toArray(_ref11), args = _ref12.slice(0), _ref11), (_splice$call7 = splice.call(args, -1), _splice$call8 = _slicedToArray(_splice$call7, 1), cb = _splice$call8[0], _splice$call7); +// API +module.exports = async; - returned = function () { - try { - return task(...args); - } catch (error1) { - e = error1; - return this.Promise.reject(e); - } - }.call(this); +/** + * Runs provided callback asynchronously + * even if callback itself is not + * + * @param {function} callback - callback to invoke + * @returns {function} - augmented callback + */ +function async(callback) +{ + var isAsync = false; - return (!((returned != null ? returned.then : void 0) != null && typeof returned.then === "function") ? this.Promise.resolve(returned) : returned).then(function (...args) { - return cb(null, ...args); - }).catch(function (...args) { - return cb(...args); - }); - }; + // check if async happened + defer(function() { isAsync = true; }); - return new this.Promise((resolve, reject) => { - return this.submit(options, wrapped, ...args, function (...args) { - return (args[0] != null ? reject : (args.shift(), resolve))(...args); - }).catch(e => { - return this.Events.trigger("error", e); - }); + return function async_callback(err, result) + { + if (isAsync) + { + callback(err, result); + } + else + { + defer(function nextTick_callback() + { + callback(err, result); }); } + }; +} - wrap(fn) { - var schedule, wrapped; - schedule = this.schedule; - wrapped = function wrapped(...args) { - return schedule(fn.bind(this), ...args); - }; +/***/ }), - wrapped.withOptions = (options, ...args) => { - return schedule(options, fn, ...args); - }; +/***/ 15295: +/***/ ((module) => { - return wrapped; - } +module.exports = defer; - updateSettings(options = {}) { - var _this3 = this; +/** + * Runs provided function on next iteration of the event loop + * + * @param {function} fn - function to run + */ +function defer(fn) +{ + var nextTick = typeof setImmediate == 'function' + ? setImmediate + : ( + typeof process == 'object' && typeof process.nextTick == 'function' + ? process.nextTick + : null + ); - return _asyncToGenerator(function* () { - yield _this3._store.__updateSettings__(parser.overwrite(options, _this3.storeDefaults)); - parser.overwrite(options, _this3.instanceDefaults, _this3); - return _this3; - })(); - } + if (nextTick) + { + nextTick(fn); + } + else + { + setTimeout(fn, 0); + } +} - currentReservoir() { - return this._store.__currentReservoir__(); - } - incrementReservoir(incr = 0) { - return this._store.__incrementReservoir__(incr); - } +/***/ }), - } +/***/ 9023: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var async = __nccwpck_require__(72794) + , abort = __nccwpck_require__(1700) ; - Bottleneck.default = Bottleneck; - Bottleneck.Events = Events; - Bottleneck.version = Bottleneck.prototype.version = __nccwpck_require__(18372)/* .version */ .i; - Bottleneck.strategy = Bottleneck.prototype.strategy = { - LEAK: 1, - OVERFLOW: 2, - OVERFLOW_PRIORITY: 4, - BLOCK: 3 - }; - Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = __nccwpck_require__(93529); - Bottleneck.Group = Bottleneck.prototype.Group = __nccwpck_require__(53068); - Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = __nccwpck_require__(29992); - Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = __nccwpck_require__(47710); - Bottleneck.Batcher = Bottleneck.prototype.Batcher = __nccwpck_require__(85442); - Bottleneck.prototype.jobDefaults = { - priority: DEFAULT_PRIORITY, - weight: 1, - expiration: null, - id: "" - }; - Bottleneck.prototype.storeDefaults = { - maxConcurrent: null, - minTime: 0, - highWater: null, - strategy: Bottleneck.prototype.strategy.LEAK, - penalty: null, - reservoir: null, - reservoirRefreshInterval: null, - reservoirRefreshAmount: null - }; - Bottleneck.prototype.localStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 250 - }; - Bottleneck.prototype.redisStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 5000, - clientTimeout: 10000, - clientOptions: {}, - clusterNodes: null, - clearDatastore: false, - connection: null - }; - Bottleneck.prototype.instanceDefaults = { - datastore: "local", - connection: null, - id: "", - rejectOnDrop: true, - trackDoneStatus: false, - Promise: Promise - }; - Bottleneck.prototype.stopDefaults = { - enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", - dropWaitingJobs: true, - dropErrorMessage: "This limiter has been stopped." - }; - return Bottleneck; -}.call(void 0); -module.exports = Bottleneck; +// API +module.exports = iterate; -/***/ }), +/** + * Iterates over each job object + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {object} state - current job status + * @param {function} callback - invoked when all elements processed + */ +function iterate(list, iterator, state, callback) +{ + // store current index + var key = state['keyedList'] ? state['keyedList'][state.index] : state.index; -/***/ 93529: -/***/ ((module) => { + state.jobs[key] = runJob(iterator, key, list[key], function(error, output) + { + // don't repeat yourself + // skip secondary callbacks + if (!(key in state.jobs)) + { + return; + } -"use strict"; + // clean up jobs + delete state.jobs[key]; + + if (error) + { + // don't process rest of the results + // stop still active jobs + // and reset the list + abort(state); + } + else + { + state.results[key] = output; + } + + // return salvaged results + callback(error, state.results); + }); +} + +/** + * Runs iterator over provided job element + * + * @param {function} iterator - iterator to invoke + * @param {string|number} key - key/index of the element in the list of jobs + * @param {mixed} item - job description + * @param {function} callback - invoked after iterator is done with the job + * @returns {function|mixed} - job abort function or something else + */ +function runJob(iterator, key, item, callback) +{ + var aborter; + + // allow shortcut if iterator expects only two arguments + if (iterator.length == 2) + { + aborter = iterator(item, async(callback)); + } + // otherwise go with full three arguments + else + { + aborter = iterator(item, key, async(callback)); + } + return aborter; +} -var BottleneckError; -BottleneckError = class BottleneckError extends Error {}; -module.exports = BottleneckError; /***/ }), -/***/ 38579: +/***/ 42474: /***/ ((module) => { -"use strict"; +// API +module.exports = state; +/** + * Creates initial state object + * for iteration over list + * + * @param {array|object} list - list to iterate over + * @param {function|null} sortMethod - function to use for keys sort, + * or `null` to keep them as is + * @returns {object} - initial state object + */ +function state(list, sortMethod) +{ + var isNamedList = !Array.isArray(list) + , initState = + { + index : 0, + keyedList: isNamedList || sortMethod ? Object.keys(list) : null, + jobs : {}, + results : isNamedList ? {} : [], + size : isNamedList ? Object.keys(list).length : list.length + } + ; -var DLList; -DLList = class DLList { - constructor(_queues) { - this._queues = _queues; - this._first = null; - this._last = null; - this.length = 0; + if (sortMethod) + { + // sort array keys based on it's values + // sort object's keys just on own merit + initState.keyedList.sort(isNamedList ? sortMethod : function(a, b) + { + return sortMethod(list[a], list[b]); + }); } - push(value) { - var node, ref1; - this.length++; + return initState; +} - if ((ref1 = this._queues) != null) { - ref1.incr(); - } - node = { - value, - next: null - }; +/***/ }), - if (this._last != null) { - this._last.next = node; - this._last = node; - } else { - this._first = this._last = node; - } +/***/ 37942: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return void 0; +var abort = __nccwpck_require__(1700) + , async = __nccwpck_require__(72794) + ; + +// API +module.exports = terminator; + +/** + * Terminates jobs in the attached state context + * + * @this AsyncKitState# + * @param {function} callback - final callback to invoke after termination + */ +function terminator(callback) +{ + if (!Object.keys(this.jobs).length) + { + return; } - shift() { - var ref1, ref2, value; + // fast forward iteration index + this.index = this.size; - if (this._first == null) { - return void 0; - } else { - this.length--; + // abort jobs + abort(this); - if ((ref1 = this._queues) != null) { - ref1.decr(); - } - } + // send back results we have so far + async(callback)(null, this.results); +} - value = this._first.value; - this._first = (ref2 = this._first.next) != null ? ref2 : this._last = null; - return value; - } - first() { - if (this._first != null) { - return this._first.value; - } - } +/***/ }), - getArray() { - var node, ref, results; - node = this._first; - results = []; +/***/ 8210: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - while (node != null) { - results.push((ref = node, node = node.next, ref.value)); - } +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(42474) + , terminator = __nccwpck_require__(37942) + ; - return results; - } +// Public API +module.exports = parallel; - forEachShift(cb) { - var node; - node = this.shift(); +/** + * Runs iterator over provided array elements in parallel + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function parallel(list, iterator, callback) +{ + var state = initState(list); - while (node != null) { - cb(node), node = this.shift(); - } + while (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, function(error, result) + { + if (error) + { + callback(error, result); + return; + } - return void 0; + // looks like it's the last one + if (Object.keys(state.jobs).length === 0) + { + callback(null, state.results); + return; + } + }); + + state.index++; } -}; -module.exports = DLList; + return terminator.bind(state, callback); +} -/***/ }), -/***/ 107: -/***/ ((module) => { +/***/ }), -"use strict"; +/***/ 50445: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var serialOrdered = __nccwpck_require__(3578); -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +// Public API +module.exports = serial; -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +/** + * Runs iterator over provided array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serial(list, iterator, callback) +{ + return serialOrdered(list, iterator, null, callback); +} -var Events; -Events = class Events { - constructor(instance) { - this.instance = instance; - this._events = {}; - if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) { - throw new Error("An Emitter already exists for this object"); - } +/***/ }), - this.instance.on = (name, cb) => { - return this._addListener(name, "many", cb); - }; +/***/ 3578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - this.instance.once = (name, cb) => { - return this._addListener(name, "once", cb); - }; +var iterate = __nccwpck_require__(9023) + , initState = __nccwpck_require__(42474) + , terminator = __nccwpck_require__(37942) + ; - this.instance.removeAllListeners = (name = null) => { - if (name != null) { - return delete this._events[name]; - } else { - return this._events = {}; - } - }; - } +// Public API +module.exports = serialOrdered; +// sorting helpers +module.exports.ascending = ascending; +module.exports.descending = descending; - _addListener(name, status, cb) { - var base; +/** + * Runs iterator over provided sorted array elements in series + * + * @param {array|object} list - array or object (named list) to iterate over + * @param {function} iterator - iterator to run + * @param {function} sortMethod - custom sort function + * @param {function} callback - invoked when all elements processed + * @returns {function} - jobs terminator + */ +function serialOrdered(list, iterator, sortMethod, callback) +{ + var state = initState(list, sortMethod); - if ((base = this._events)[name] == null) { - base[name] = []; + iterate(list, iterator, state, function iteratorHandler(error, result) + { + if (error) + { + callback(error, result); + return; } - this._events[name].push({ - cb, - status - }); - - return this.instance; - } + state.index++; - listenerCount(name) { - if (this._events[name] != null) { - return this._events[name].length; - } else { - return 0; + // are we there yet? + if (state.index < (state['keyedList'] || list).length) + { + iterate(list, iterator, state, iteratorHandler); + return; } - } - trigger(name, ...args) { - var _this = this; + // done here + callback(null, state.results); + }); - return _asyncToGenerator(function* () { - var e, promises; + return terminator.bind(state, callback); +} - try { - if (name !== "debug") { - _this.trigger("debug", `Event triggered: ${name}`, args); - } +/* + * -- Sort methods + */ - if (_this._events[name] == null) { - return; - } +/** + * sort helper to sort array elements in ascending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function ascending(a, b) +{ + return a < b ? -1 : a > b ? 1 : 0; +} - _this._events[name] = _this._events[name].filter(function (listener) { - return listener.status !== "none"; - }); - promises = _this._events[name].map( - /*#__PURE__*/ - function () { - var _ref = _asyncToGenerator(function* (listener) { - var e, returned; +/** + * sort helper to sort array elements in descending order + * + * @param {mixed} a - an item to compare + * @param {mixed} b - an item to compare + * @returns {number} - comparison result + */ +function descending(a, b) +{ + return -1 * ascending(a, b); +} - if (listener.status === "none") { - return; - } - if (listener.status === "once") { - listener.status = "none"; - } +/***/ }), - try { - returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; +/***/ 86950: +/***/ ((module) => { - if (typeof (returned != null ? returned.then : void 0) === "function") { - return yield returned; - } else { - return returned; - } - } catch (error) { - e = error; +"use strict"; - if (true) { - _this.trigger("error", e); - } - return null; - } - }); +/* global SharedArrayBuffer, Atomics */ - return function (_x) { - return _ref.apply(this, arguments); - }; - }()); - return (yield Promise.all(promises)).find(function (x) { - return x != null; - }); - } catch (error) { - e = error; +if (typeof SharedArrayBuffer !== 'undefined' && typeof Atomics !== 'undefined') { + const nil = new Int32Array(new SharedArrayBuffer(4)) - if (true) { - _this.trigger("error", e); - } + function sleep (ms) { + // also filters out NaN, non-number types, including empty strings, but allows bigints + const valid = ms > 0 && ms < Infinity + if (valid === false) { + if (typeof ms !== 'number' && typeof ms !== 'bigint') { + throw TypeError('sleep: ms must be a number') + } + throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') + } - return null; + Atomics.wait(nil, 0, 0, Number(ms)) + } + module.exports = sleep +} else { + + function sleep (ms) { + // also filters out NaN, non-number types, including empty strings, but allows bigints + const valid = ms > 0 && ms < Infinity + if (valid === false) { + if (typeof ms !== 'number' && typeof ms !== 'bigint') { + throw TypeError('sleep: ms must be a number') } - })(); + throw RangeError('sleep: ms must be a number that is greater than 0 but less than Infinity') + } + const target = Date.now() + Number(ms) + while (target > Date.now()){} } -}; -module.exports = Events; + module.exports = sleep + +} + /***/ }), -/***/ 53068: +/***/ 83682: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +var register = __nccwpck_require__(44670) +var addHook = __nccwpck_require__(5549) +var removeHook = __nccwpck_require__(6819) +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind +var bindable = bind.bind(bind) -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } +function bindApi (hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply(null, name ? [state, name] : [state]) + hook.api = { remove: removeHookRef } + hook.remove = removeHookRef -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } + ;['before', 'error', 'after', 'wrap'].forEach(function (kind) { + var args = name ? [state, kind, name] : [state, kind] + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args) + }) +} -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } +function HookSingular () { + var singularHookName = 'h' + var singularHookState = { + registry: {} + } + var singularHook = register.bind(null, singularHookState, singularHookName) + bindApi(singularHook, singularHookState, singularHookName) + return singularHook +} -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function HookCollection () { + var state = { + registry: {} + } -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + var hook = register.bind(null, state) + bindApi(hook, state) -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + return hook +} -var Events, Group, IORedisConnection, RedisConnection, Scripts, parser; -parser = __nccwpck_require__(67823); -Events = __nccwpck_require__(107); -RedisConnection = __nccwpck_require__(29992); -IORedisConnection = __nccwpck_require__(47710); -Scripts = __nccwpck_require__(4169); +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() +} -Group = function () { - class Group { - constructor(limiterOptions = {}) { - this.deleteKey = this.deleteKey.bind(this); - this.updateSettings = this.updateSettings.bind(this); - this.limiterOptions = limiterOptions; - parser.load(this.limiterOptions, this.defaults, this); - this.Events = new Events(this); - this.instances = {}; - this.Bottleneck = __nccwpck_require__(83911); +Hook.Singular = HookSingular.bind() +Hook.Collection = HookCollection.bind() - this._startAutoCleanup(); +module.exports = Hook +// expose constructors as a named property for TypeScript +module.exports.Hook = Hook +module.exports.Singular = Hook.Singular +module.exports.Collection = Hook.Collection - this.sharedConnection = this.connection != null; - if (this.connection == null) { - if (this.limiterOptions.datastore === "redis") { - this.connection = new RedisConnection(Object.assign({}, this.limiterOptions, { - Events: this.Events - })); - } else if (this.limiterOptions.datastore === "ioredis") { - this.connection = new IORedisConnection(Object.assign({}, this.limiterOptions, { - Events: this.Events - })); - } - } - } +/***/ }), - key(key = "") { - var ref; - return (ref = this.instances[key]) != null ? ref : (() => { - var limiter; - limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { - id: `${this.id}-${key}`, - timeout: this.timeout, - connection: this.connection - })); - this.Events.trigger("created", limiter, key); - return limiter; - })(); - } +/***/ 5549: +/***/ ((module) => { - deleteKey(key = "") { - var _this = this; +module.exports = addHook; - return _asyncToGenerator(function* () { - var deleted, instance; - instance = _this.instances[key]; +function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } - if (_this.connection) { - deleted = yield _this.connection.__runCommand__(['del', ...Scripts.allKeys(`${_this.id}-${key}`)]); - } + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; + } - if (instance != null) { - delete _this.instances[key]; - yield instance.disconnect(); - } + 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; + }); + }; + } - return instance != null || deleted > 0; - })(); - } + if (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); + }; + } - limiters() { - var k, ref, results, v; - ref = this.instances; - results = []; + state.registry[name].push({ + hook: hook, + orig: orig, + }); +} - for (k in ref) { - v = ref[k]; - results.push({ - key: k, - limiter: v - }); - } - return results; - } +/***/ }), - keys() { - return Object.keys(this.instances); - } +/***/ 44670: +/***/ ((module) => { - clusterKeys() { - var _this2 = this; +module.exports = register; - return _asyncToGenerator(function* () { - var cursor, end, found, i, k, keys, len, next, start; +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } - if (_this2.connection == null) { - return _this2.Promise.resolve(_this2.keys()); - } + if (!options) { + options = {}; + } - keys = []; - cursor = null; - start = `b_${_this2.id}-`.length; - end = "_settings".length; + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options); + }, method)(); + } - while (cursor !== 0) { - var _ref = yield _this2.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${_this2.id}-*_settings`, "count", 10000]); + return Promise.resolve().then(function () { + if (!state.registry[name]) { + return method(options); + } - var _ref2 = _slicedToArray(_ref, 2); + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); +} - next = _ref2[0]; - found = _ref2[1]; - cursor = ~~next; - for (i = 0, len = found.length; i < len; i++) { - k = found[i]; - keys.push(k.slice(start, -end)); - } - } +/***/ }), - return keys; - })(); - } +/***/ 6819: +/***/ ((module) => { - _startAutoCleanup() { - var _this3 = this; +module.exports = removeHook; - var base; - clearInterval(this.interval); - return typeof (base = this.interval = setInterval( - /*#__PURE__*/ - _asyncToGenerator(function* () { - var e, k, ref, results, time, v; - time = Date.now(); - ref = _this3.instances; - results = []; +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } - for (k in ref) { - v = ref[k]; + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); - try { - if (yield v._store.__groupCheck__(time)) { - results.push(_this3.deleteKey(k)); - } else { - results.push(void 0); - } - } catch (error) { - e = error; - results.push(v.Events.trigger("error", e)); - } - } + if (index === -1) { + return; + } - return results; - }), this.timeout / 2)).unref === "function" ? base.unref() : void 0; - } + state.registry[name].splice(index, 1); +} - updateSettings(options = {}) { - parser.overwrite(options, this.defaults, this); - parser.overwrite(options, options, this.limiterOptions); - if (options.timeout != null) { - return this._startAutoCleanup(); - } - } +/***/ }), - disconnect(flush = true) { - var ref; +/***/ 97076: +/***/ ((module, exports, __nccwpck_require__) => { - if (!this.sharedConnection) { - return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; - } - } +"use strict"; +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - } - ; - Group.prototype.defaults = { - timeout: 1000 * 60 * 5, - connection: null, - Promise: Promise, - id: "group-key" - }; - return Group; -}.call(void 0); -module.exports = Group; +/** + * Module dependencies. + * @private + */ -/***/ }), +var deprecate = __nccwpck_require__(18883)('body-parser') -/***/ 47710: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Cache of loaded parsers. + * @private + */ -"use strict"; +var parsers = Object.create(null) +/** + * @typedef Parsers + * @type {function} + * @property {function} json + * @property {function} raw + * @property {function} text + * @property {function} urlencoded + */ -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } +/** + * Module exports. + * @type {Parsers} + */ -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } +exports = module.exports = deprecate.function(bodyParser, + 'bodyParser: use individual json/urlencoded middlewares') -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } +/** + * JSON parser. + * @public + */ -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +Object.defineProperty(exports, "json", ({ + configurable: true, + enumerable: true, + get: createParserGetter('json') +})) -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +/** + * Raw parser. + * @public + */ -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +Object.defineProperty(exports, "raw", ({ + configurable: true, + enumerable: true, + get: createParserGetter('raw') +})) -var Events, IORedisConnection, Scripts, parser; -parser = __nccwpck_require__(67823); -Events = __nccwpck_require__(107); -Scripts = __nccwpck_require__(4169); +/** + * Text parser. + * @public + */ -IORedisConnection = function () { - class IORedisConnection { - constructor(options = {}) { - var Redis; - Redis = eval("require")("ioredis"); // Obfuscated or else Webpack/Angular will try to inline the optional ioredis module +Object.defineProperty(exports, "text", ({ + configurable: true, + enumerable: true, + get: createParserGetter('text') +})) - parser.load(options, this.defaults, this); +/** + * URL-encoded parser. + * @public + */ - if (this.Events == null) { - this.Events = new Events(this); - } +Object.defineProperty(exports, "urlencoded", ({ + configurable: true, + enumerable: true, + get: createParserGetter('urlencoded') +})) - this.terminated = false; +/** + * Create a middleware to parse json and urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @deprecated + * @public + */ - if (this.clusterNodes != null) { - this.client = new Redis.Cluster(this.clusterNodes, this.clientOptions); - this.subscriber = new Redis.Cluster(this.clusterNodes, this.clientOptions); - } else { - if (this.client == null) { - this.client = new Redis(this.clientOptions); - } +function bodyParser (options) { + var opts = {} - this.subscriber = this.client.duplicate(); + // exclude type option + if (options) { + for (var prop in options) { + if (prop !== 'type') { + opts[prop] = options[prop] } + } + } - this.limiters = {}; - this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => { - this._loadScripts(); + var _urlencoded = exports.urlencoded(opts) + var _json = exports.json(opts) - return { - client: this.client, - subscriber: this.subscriber - }; - }); - } + return function bodyParser (req, res, next) { + _json(req, res, function (err) { + if (err) return next(err) + _urlencoded(req, res, next) + }) + } +} - _setup(client, sub) { - client.setMaxListeners(0); - return new this.Promise((resolve, reject) => { - client.on("error", e => { - return this.Events.trigger("error", e); - }); +/** + * Create a getter for loading a parser. + * @private + */ - if (sub) { - client.on("message", (channel, message) => { - var ref; - return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; - }); - } +function createParserGetter (name) { + return function get () { + return loadParser(name) + } +} - if (client.status === "ready") { - return resolve(); - } else { - return client.once("ready", resolve); - } - }); - } +/** + * Load a parser module. + * @private + */ - _loadScripts() { - return Scripts.names.forEach(name => { - return this.client.defineCommand(name, { - lua: Scripts.payload(name) - }); - }); - } +function loadParser (parserName) { + var parser = parsers[parserName] - __runCommand__(cmd) { - var _this = this; + if (parser !== undefined) { + return parser + } - return _asyncToGenerator(function* () { - var _, deleted; + // this uses a switch for static require analysis + switch (parserName) { + case 'json': + parser = __nccwpck_require__(20859) + break + case 'raw': + parser = __nccwpck_require__(49609) + break + case 'text': + parser = __nccwpck_require__(26382) + break + case 'urlencoded': + parser = __nccwpck_require__(76100) + break + } - yield _this.ready; + // store to prevent invoking require() + return (parsers[parserName] = parser) +} - var _ref = yield _this.client.pipeline([cmd]).exec(); - var _ref2 = _slicedToArray(_ref, 1); +/***/ }), - var _ref2$ = _slicedToArray(_ref2[0], 2); +/***/ 88862: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - _ = _ref2$[0]; - deleted = _ref2$[1]; - return deleted; - })(); - } +"use strict"; +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - __addLimiter__(instance) { - return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => { - return new this.Promise((resolve, reject) => { - return this.subscriber.subscribe(channel, () => { - this.limiters[channel] = instance; - return resolve(); - }); - }); - })); - } - __removeLimiter__(instance) { - var _this2 = this; - return [instance.channel(), instance.channel_client()].forEach( - /*#__PURE__*/ - function () { - var _ref3 = _asyncToGenerator(function* (channel) { - if (!_this2.terminated) { - yield _this2.subscriber.unsubscribe(channel); - } +/** + * Module dependencies. + * @private + */ - return delete _this2.limiters[channel]; - }); +var createError = __nccwpck_require__(95193) +var getBody = __nccwpck_require__(47742) +var iconv = __nccwpck_require__(19032) +var onFinished = __nccwpck_require__(92098) +var zlib = __nccwpck_require__(78761) - return function (_x) { - return _ref3.apply(this, arguments); - }; - }()); - } +/** + * Module exports. + */ - __scriptArgs__(name, id, args, cb) { - var keys; - keys = Scripts.keys(name, id); - return [keys.length].concat(keys, args, cb); - } +module.exports = read - __scriptFn__(name) { - return this.client[name].bind(this.client); - } +/** + * Read a request into a buffer and parse. + * + * @param {object} req + * @param {object} res + * @param {function} next + * @param {function} parse + * @param {function} debug + * @param {object} options + * @private + */ - disconnect(flush = true) { - var i, k, len, ref; - ref = Object.keys(this.limiters); +function read (req, res, next, parse, debug, options) { + var length + var opts = options + var stream - for (i = 0, len = ref.length; i < len; i++) { - k = ref[i]; - clearInterval(this.limiters[k]._store.heartbeat); - } + // flag as parsed + req._body = true - this.limiters = {}; - this.terminated = true; + // read options + var encoding = opts.encoding !== null + ? opts.encoding + : null + var verify = opts.verify - if (flush) { - return this.Promise.all([this.client.quit(), this.subscriber.quit()]); - } else { - this.client.disconnect(); - this.subscriber.disconnect(); - return this.Promise.resolve(); - } - } + try { + // get the content stream + stream = contentstream(req, debug, opts.inflate) + length = stream.length + stream.length = undefined + } catch (err) { + return next(err) + } + // set raw-body options + opts.length = length + opts.encoding = verify + ? null + : encoding + + // assert charset is supported + if (opts.encoding === null && encoding !== null && !iconv.encodingExists(encoding)) { + return next(createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + })) } - ; - IORedisConnection.prototype.datastore = "ioredis"; - IORedisConnection.prototype.defaults = { - clientOptions: {}, - clusterNodes: null, - client: null, - Promise: Promise, - Events: null - }; - return IORedisConnection; -}.call(void 0); + // read body + debug('read body') + getBody(stream, opts, function (error, body) { + if (error) { + var _error -module.exports = IORedisConnection; + if (error.type === 'encoding.unsupported') { + // echo back charset + _error = createError(415, 'unsupported charset "' + encoding.toUpperCase() + '"', { + charset: encoding.toLowerCase(), + type: 'charset.unsupported' + }) + } else { + // set status code on error + _error = createError(400, error) + } -/***/ }), + // read off entire request + stream.resume() + onFinished(req, function onfinished () { + next(createError(400, _error)) + }) + return + } -/***/ 38979: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // verify + if (verify) { + try { + debug('verify body') + verify(req, res, body, encoding) + } catch (err) { + next(createError(403, err, { + body: body, + type: err.type || 'entity.verify.failed' + })) + return + } + } -"use strict"; + // parse + var str = body + try { + debug('parse body') + str = typeof body !== 'string' && encoding !== null + ? iconv.decode(body, encoding) + : body + req.body = parse(str) + } catch (err) { + next(createError(400, err, { + body: str, + type: err.type || 'entity.parse.failed' + })) + return + } + next() + }) +} -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } +/** + * Get the content stream of the request. + * + * @param {object} req + * @param {function} debug + * @param {boolean} [inflate=true] + * @return {object} + * @api private + */ -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } +function contentstream (req, debug, inflate) { + var encoding = (req.headers['content-encoding'] || 'identity').toLowerCase() + var length = req.headers['content-length'] + var stream -var BottleneckError, LocalDatastore, parser; -parser = __nccwpck_require__(67823); -BottleneckError = __nccwpck_require__(93529); -LocalDatastore = class LocalDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.clientId = this.instance._randomIndex(); - parser.load(storeInstanceOptions, storeInstanceOptions, this); - this._nextRequest = this._lastReservoirRefresh = Date.now(); - this._running = 0; - this._done = 0; - this._unblockTime = 0; - this.ready = this.Promise.resolve(); - this.clients = {}; + debug('content-encoding "%s"', encoding) - this._startHeartbeat(); + if (inflate === false && encoding !== 'identity') { + throw createError(415, 'content encoding unsupported', { + encoding: encoding, + type: 'encoding.unsupported' + }) } - _startHeartbeat() { - var base; - - if (this.heartbeat == null && this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null) { - return typeof (base = this.heartbeat = setInterval(() => { - var now; - now = Date.now(); - - if (now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { - this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; - this._lastReservoirRefresh = now; - return this.instance._drainAll(this.computeCapacity()); - } - }, this.heartbeatInterval)).unref === "function" ? base.unref() : void 0; - } else { - return clearInterval(this.heartbeat); - } + switch (encoding) { + case 'deflate': + stream = zlib.createInflate() + debug('inflate body') + req.pipe(stream) + break + case 'gzip': + stream = zlib.createGunzip() + debug('gunzip body') + req.pipe(stream) + break + case 'identity': + stream = req + stream.length = length + break + default: + throw createError(415, 'unsupported content encoding "' + encoding + '"', { + encoding: encoding, + type: 'encoding.unsupported' + }) } - __publish__(message) { - var _this = this; + return stream +} - return _asyncToGenerator(function* () { - yield _this.yieldLoop(); - return _this.instance.Events.trigger("message", message.toString()); - })(); - } - __disconnect__(flush) { - var _this2 = this; +/***/ }), - return _asyncToGenerator(function* () { - yield _this2.yieldLoop(); - clearInterval(_this2.heartbeat); - return _this2.Promise.resolve(); - })(); - } +/***/ 20859: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - yieldLoop(t = 0) { - return new this.Promise(function (resolve, reject) { - return setTimeout(resolve, t); - }); - } +"use strict"; +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5000; - } - __updateSettings__(options) { - var _this3 = this; - return _asyncToGenerator(function* () { - yield _this3.yieldLoop(); - parser.overwrite(options, options, _this3.storeOptions); +/** + * Module dependencies. + * @private + */ - _this3._startHeartbeat(); +var bytes = __nccwpck_require__(86966) +var contentType = __nccwpck_require__(99915) +var createError = __nccwpck_require__(95193) +var debug = __nccwpck_require__(7471)('body-parser:json') +var read = __nccwpck_require__(88862) +var typeis = __nccwpck_require__(71159) - _this3.instance._drainAll(_this3.computeCapacity()); +/** + * Module exports. + */ - return true; - })(); - } +module.exports = json - __running__() { - var _this4 = this; +/** + * RegExp to match the first non-space in a string. + * + * Allowed whitespace is defined in RFC 7159: + * + * ws = *( + * %x20 / ; Space + * %x09 / ; Horizontal tab + * %x0A / ; Line feed or New line + * %x0D ) ; Carriage return + */ - return _asyncToGenerator(function* () { - yield _this4.yieldLoop(); - return _this4._running; - })(); - } +var FIRST_CHAR_REGEXP = /^[\x20\x09\x0a\x0d]*(.)/ // eslint-disable-line no-control-regex - __queued__() { - var _this5 = this; +/** + * Create a middleware to parse JSON bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ - return _asyncToGenerator(function* () { - yield _this5.yieldLoop(); - return _this5.instance.queued(); - })(); - } +function json (options) { + var opts = options || {} - __done__() { - var _this6 = this; + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var inflate = opts.inflate !== false + var reviver = opts.reviver + var strict = opts.strict !== false + var type = opts.type || 'application/json' + var verify = opts.verify || false - return _asyncToGenerator(function* () { - yield _this6.yieldLoop(); - return _this6._done; - })(); + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') } - __groupCheck__(time) { - var _this7 = this; + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type - return _asyncToGenerator(function* () { - yield _this7.yieldLoop(); - return _this7._nextRequest + _this7.timeout < time; - })(); - } + function parse (body) { + if (body.length === 0) { + // special-case empty json body, as it's a common client-side mistake + // TODO: maybe make this configurable or part of "strict" option + return {} + } - computeCapacity() { - var maxConcurrent, reservoir; - var _this$storeOptions = this.storeOptions; - maxConcurrent = _this$storeOptions.maxConcurrent; - reservoir = _this$storeOptions.reservoir; + if (strict) { + var first = firstchar(body) - if (maxConcurrent != null && reservoir != null) { - return Math.min(maxConcurrent - this._running, reservoir); - } else if (maxConcurrent != null) { - return maxConcurrent - this._running; - } else if (reservoir != null) { - return reservoir; - } else { - return null; + if (first !== '{' && first !== '[') { + debug('strict violation') + throw createStrictSyntaxError(body, first) + } } - } - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return capacity == null || weight <= capacity; + try { + debug('parse json') + return JSON.parse(body, reviver) + } catch (e) { + throw normalizeJsonSyntaxError(e, { + message: e.message, + stack: e.stack + }) + } } - __incrementReservoir__(incr) { - var _this8 = this; + return function jsonParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return + } - return _asyncToGenerator(function* () { - var reservoir; - yield _this8.yieldLoop(); - reservoir = _this8.storeOptions.reservoir += incr; + req.body = req.body || {} - _this8.instance._drainAll(_this8.computeCapacity()); + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } - return reservoir; - })(); - } + debug('content-type %j', req.headers['content-type']) - __currentReservoir__() { - var _this9 = this; + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return + } - return _asyncToGenerator(function* () { - yield _this9.yieldLoop(); - return _this9.storeOptions.reservoir; - })(); - } + // assert charset per RFC 7159 sec 8.1 + var charset = getCharset(req) || 'utf-8' + if (charset.substr(0, 4) !== 'utf-') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } - isBlocked(now) { - return this._unblockTime >= now; + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) } +} - check(weight, now) { - return this.conditionsCheck(weight) && this._nextRequest - now <= 0; - } +/** + * Create strict violation syntax error matching native error. + * + * @param {string} str + * @param {string} char + * @return {Error} + * @private + */ - __check__(weight) { - var _this10 = this; +function createStrictSyntaxError (str, char) { + var index = str.indexOf(char) + var partial = str.substring(0, index) + '#' - return _asyncToGenerator(function* () { - var now; - yield _this10.yieldLoop(); - now = Date.now(); - return _this10.check(weight, now); - })(); + try { + JSON.parse(partial); /* istanbul ignore next */ throw new SyntaxError('strict violation') + } catch (e) { + return normalizeJsonSyntaxError(e, { + message: e.message.replace('#', char), + stack: e.stack + }) } +} - __register__(index, weight, expiration) { - var _this11 = this; - - return _asyncToGenerator(function* () { - var now, wait; - yield _this11.yieldLoop(); - now = Date.now(); - - if (_this11.conditionsCheck(weight)) { - _this11._running += weight; +/** + * Get the first non-whitespace character in a string. + * + * @param {string} str + * @return {function} + * @private + */ - if (_this11.storeOptions.reservoir != null) { - _this11.storeOptions.reservoir -= weight; - } +function firstchar (str) { + return FIRST_CHAR_REGEXP.exec(str)[1] +} - wait = Math.max(_this11._nextRequest - now, 0); - _this11._nextRequest = now + wait + _this11.storeOptions.minTime; - return { - success: true, - wait, - reservoir: _this11.storeOptions.reservoir - }; - } else { - return { - success: false - }; - } - })(); - } +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ - strategyIsBlock() { - return this.storeOptions.strategy === 3; +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined } +} - __submit__(queueLength, weight) { - var _this12 = this; - - return _asyncToGenerator(function* () { - var blocked, now, reachedHWM; - yield _this12.yieldLoop(); - - if (_this12.storeOptions.maxConcurrent != null && weight > _this12.storeOptions.maxConcurrent) { - throw new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${_this12.storeOptions.maxConcurrent}`); - } - - now = Date.now(); - reachedHWM = _this12.storeOptions.highWater != null && queueLength === _this12.storeOptions.highWater && !_this12.check(weight, now); - blocked = _this12.strategyIsBlock() && (reachedHWM || _this12.isBlocked(now)); - - if (blocked) { - _this12._unblockTime = now + _this12.computePenalty(); - _this12._nextRequest = _this12._unblockTime + _this12.storeOptions.minTime; +/** + * Normalize a SyntaxError for JSON.parse. + * + * @param {SyntaxError} error + * @param {object} obj + * @return {SyntaxError} + */ - _this12.instance._dropAllQueued(); - } +function normalizeJsonSyntaxError (error, obj) { + var keys = Object.getOwnPropertyNames(error) - return { - reachedHWM, - blocked, - strategy: _this12.storeOptions.strategy - }; - })(); + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key !== 'stack' && key !== 'message') { + delete error[key] + } } - __free__(index, weight) { - var _this13 = this; + // replace stack before message for Node.js 0.10 and below + error.stack = obj.stack.replace(error.message, obj.message) + error.message = obj.message - return _asyncToGenerator(function* () { - yield _this13.yieldLoop(); - _this13._running -= weight; - _this13._done += weight; + return error +} - _this13.instance._drainAll(_this13.computeCapacity()); +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ - return { - running: _this13._running - }; - })(); +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) } +} -}; -module.exports = LocalDatastore; /***/ }), -/***/ 65893: +/***/ 49609: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -var DLList, Events, Queues; -DLList = __nccwpck_require__(38579); -Events = __nccwpck_require__(107); -Queues = class Queues { - constructor(num_priorities) { - var i; - this.Events = new Events(this); - this._length = 0; - this._lists = function () { - var j, ref, results; - results = []; +/** + * Module dependencies. + */ - for (i = j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { - results.push(new DLList(this)); - } +var bytes = __nccwpck_require__(86966) +var debug = __nccwpck_require__(7471)('body-parser:raw') +var read = __nccwpck_require__(88862) +var typeis = __nccwpck_require__(71159) - return results; - }.call(this); - } +/** + * Module exports. + */ - incr() { - if (this._length++ === 0) { - return this.Events.trigger("leftzero"); - } - } +module.exports = raw - decr() { - if (--this._length === 0) { - return this.Events.trigger("zero"); - } +/** + * Create a middleware to parse raw bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ + +function raw (options) { + var opts = options || {} + + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/octet-stream' + var verify = opts.verify || false + + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') } - push(priority, job) { - return this._lists[priority].push(job); + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type + + function parse (buf) { + return buf } - queued(priority) { - if (priority != null) { - return this._lists[priority].length; - } else { - return this._length; + return function rawParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return } - } - shiftAll(fn) { - return this._lists.forEach(function (list) { - return list.forEachShift(fn); - }); - } + req.body = req.body || {} - getFirst(arr = this._lists) { - var j, len, list; + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } - for (j = 0, len = arr.length; j < len; j++) { - list = arr[j]; + debug('content-type %j', req.headers['content-type']) - if (list.length > 0) { - return list; - } + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return } - return []; + // read + read(req, res, next, parse, debug, { + encoding: null, + inflate: inflate, + limit: limit, + verify: verify + }) } +} - shiftLastFrom(priority) { - return this.getFirst(this._lists.slice(priority).reverse()).shift(); +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ + +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) } +} -}; -module.exports = Queues; /***/ }), -/***/ 29992: +/***/ 26382: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/*! + * body-parser + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - -var Events, RedisConnection, Scripts, parser; -parser = __nccwpck_require__(67823); -Events = __nccwpck_require__(107); -Scripts = __nccwpck_require__(4169); - -RedisConnection = function () { - class RedisConnection { - constructor(options = {}) { - var Redis; - Redis = eval("require")("redis"); // Obfuscated or else Webpack/Angular will try to inline the optional redis module - - parser.load(options, this.defaults, this); - - if (this.Events == null) { - this.Events = new Events(this); - } - this.terminated = false; +/** + * Module dependencies. + */ - if (this.client == null) { - this.client = Redis.createClient(this.clientOptions); - } +var bytes = __nccwpck_require__(86966) +var contentType = __nccwpck_require__(99915) +var debug = __nccwpck_require__(7471)('body-parser:text') +var read = __nccwpck_require__(88862) +var typeis = __nccwpck_require__(71159) - this.subscriber = this.client.duplicate(); - this.limiters = {}; - this.shas = {}; - this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => { - return this._loadScripts(); - }).then(() => { - return { - client: this.client, - subscriber: this.subscriber - }; - }); - } +/** + * Module exports. + */ - _setup(client, sub) { - client.setMaxListeners(0); - return new this.Promise((resolve, reject) => { - client.on("error", e => { - return this.Events.trigger("error", e); - }); +module.exports = text - if (sub) { - client.on("message", (channel, message) => { - var ref; - return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; - }); - } +/** + * Create a middleware to parse text bodies. + * + * @param {object} [options] + * @return {function} + * @api public + */ - if (client.ready) { - return resolve(); - } else { - return client.once("ready", resolve); - } - }); - } +function text (options) { + var opts = options || {} - _loadScript(name) { - return new this.Promise((resolve, reject) => { - var payload; - payload = Scripts.payload(name); - return this.client.multi([["script", "load", payload]]).exec((err, replies) => { - if (err != null) { - return reject(err); - } + var defaultCharset = opts.defaultCharset || 'utf-8' + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'text/plain' + var verify = opts.verify || false - this.shas[name] = replies[0]; - return resolve(replies[0]); - }); - }); - } + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') + } - _loadScripts() { - return this.Promise.all(Scripts.names.map(k => { - return this._loadScript(k); - })); - } + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type - __runCommand__(cmd) { - var _this = this; + function parse (buf) { + return buf + } - return _asyncToGenerator(function* () { - yield _this.ready; - return new _this.Promise((resolve, reject) => { - return _this.client.multi([cmd]).exec_atomic(function (err, replies) { - if (err != null) { - return reject(err); - } else { - return resolve(replies[0]); - } - }); - }); - })(); + return function textParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return } - __addLimiter__(instance) { - return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => { - return new this.Promise((resolve, reject) => { - var handler; - - handler = chan => { - if (chan === channel) { - this.subscriber.removeListener("subscribe", handler); - this.limiters[channel] = instance; - return resolve(); - } - }; + req.body = req.body || {} - this.subscriber.on("subscribe", handler); - return this.subscriber.subscribe(channel); - }); - })); + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return } - __removeLimiter__(instance) { - var _this2 = this; - - return this.Promise.all([instance.channel(), instance.channel_client()].map( - /*#__PURE__*/ - function () { - var _ref = _asyncToGenerator(function* (channel) { - if (!_this2.terminated) { - yield new _this2.Promise((resolve, reject) => { - return _this2.subscriber.unsubscribe(channel, function (err, chan) { - if (err != null) { - return reject(err); - } - - if (chan === channel) { - return resolve(); - } - }); - }); - } - - return delete _this2.limiters[channel]; - }); + debug('content-type %j', req.headers['content-type']) - return function (_x) { - return _ref.apply(this, arguments); - }; - }())); + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return } - __scriptArgs__(name, id, args, cb) { - var keys; - keys = Scripts.keys(name, id); - return [this.shas[name], keys.length].concat(keys, args, cb); - } + // get charset + var charset = getCharset(req) || defaultCharset - __scriptFn__(name) { - return this.client.evalsha.bind(this.client); - } + // read + read(req, res, next, parse, debug, { + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) + } +} - disconnect(flush = true) { - var i, k, len, ref; - ref = Object.keys(this.limiters); +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ - for (i = 0, len = ref.length; i < len; i++) { - k = ref[i]; - clearInterval(this.limiters[k]._store.heartbeat); - } +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined + } +} - this.limiters = {}; - this.terminated = true; - this.client.end(flush); - this.subscriber.end(flush); - return this.Promise.resolve(); - } +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) } +} - ; - RedisConnection.prototype.datastore = "redis"; - RedisConnection.prototype.defaults = { - clientOptions: {}, - client: null, - Promise: Promise, - Events: null - }; - return RedisConnection; -}.call(void 0); - -module.exports = RedisConnection; /***/ }), -/***/ 4946: +/***/ 76100: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +/*! + * body-parser + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } - -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } - -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } - -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - -function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - -function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - -var BottleneckError, IORedisConnection, RedisConnection, RedisDatastore, parser; -parser = __nccwpck_require__(67823); -BottleneckError = __nccwpck_require__(93529); -RedisConnection = __nccwpck_require__(29992); -IORedisConnection = __nccwpck_require__(47710); -RedisDatastore = class RedisDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.originalId = this.instance.id; - this.clientId = this.instance._randomIndex(); - parser.load(storeInstanceOptions, storeInstanceOptions, this); - this.clients = {}; - this.capacityPriorityCounters = {}; - this.sharedConnection = this.connection != null; - - if (this.connection == null) { - this.connection = this.instance.datastore === "redis" ? new RedisConnection({ - clientOptions: this.clientOptions, - Promise: this.Promise, - Events: this.instance.Events - }) : this.instance.datastore === "ioredis" ? new IORedisConnection({ - clientOptions: this.clientOptions, - clusterNodes: this.clusterNodes, - Promise: this.Promise, - Events: this.instance.Events - }) : void 0; - } - - this.instance.connection = this.connection; - this.instance.datastore = this.connection.datastore; - this.ready = this.connection.ready.then(clients => { - this.clients = clients; - return this.runScript("init", this.prepareInitSettings(this.clearDatastore)); - }).then(() => { - return this.connection.__addLimiter__(this.instance); - }).then(() => { - return this.runScript("register_client", [this.instance.queued()]); - }).then(() => { - var base; - - if (typeof (base = this.heartbeat = setInterval(() => { - return this.runScript("heartbeat", []).catch(e => { - return this.instance.Events.trigger("error", e); - }); - }, this.heartbeatInterval)).unref === "function") { - base.unref(); - } - - return this.clients; - }); - } - - __publish__(message) { - var _this = this; - - return _asyncToGenerator(function* () { - var client; - - var _ref = yield _this.ready; - client = _ref.client; - return client.publish(_this.instance.channel(), `message:${message.toString()}`); - })(); - } +/** + * Module dependencies. + * @private + */ - onMessage(channel, message) { - var _this2 = this; +var bytes = __nccwpck_require__(86966) +var contentType = __nccwpck_require__(99915) +var createError = __nccwpck_require__(95193) +var debug = __nccwpck_require__(7471)('body-parser:urlencoded') +var deprecate = __nccwpck_require__(18883)('body-parser') +var read = __nccwpck_require__(88862) +var typeis = __nccwpck_require__(71159) - return _asyncToGenerator(function* () { - var capacity, counter, data, drained, e, newCapacity, pos, priorityClient, rawCapacity, type; +/** + * Module exports. + */ - try { - pos = message.indexOf(":"); - var _ref2 = [message.slice(0, pos), message.slice(pos + 1)]; - type = _ref2[0]; - data = _ref2[1]; +module.exports = urlencoded - if (type === "capacity") { - return yield _this2.instance._drainAll(data.length > 0 ? ~~data : void 0); - } else if (type === "capacity-priority") { - var _data$split = data.split(":"); +/** + * Cache of parser modules. + */ - var _data$split2 = _slicedToArray(_data$split, 3); +var parsers = Object.create(null) - rawCapacity = _data$split2[0]; - priorityClient = _data$split2[1]; - counter = _data$split2[2]; - capacity = rawCapacity.length > 0 ? ~~rawCapacity : void 0; +/** + * Create a middleware to parse urlencoded bodies. + * + * @param {object} [options] + * @return {function} + * @public + */ - if (priorityClient === _this2.clientId) { - drained = yield _this2.instance._drainAll(capacity); - newCapacity = capacity != null ? capacity - (drained || 0) : ""; - return yield _this2.clients.client.publish(_this2.instance.channel(), `capacity-priority:${newCapacity}::${counter}`); - } else if (priorityClient === "") { - clearTimeout(_this2.capacityPriorityCounters[counter]); - delete _this2.capacityPriorityCounters[counter]; - return _this2.instance._drainAll(capacity); - } else { - return _this2.capacityPriorityCounters[counter] = setTimeout( - /*#__PURE__*/ - _asyncToGenerator(function* () { - var e; +function urlencoded (options) { + var opts = options || {} - try { - delete _this2.capacityPriorityCounters[counter]; - yield _this2.runScript("blacklist_client", [priorityClient]); - return yield _this2.instance._drainAll(capacity); - } catch (error) { - e = error; - return _this2.instance.Events.trigger("error", e); - } - }), 1000); - } - } else if (type === "message") { - return _this2.instance.Events.trigger("message", data); - } else if (type === "blocked") { - return yield _this2.instance._dropAllQueued(); - } - } catch (error) { - e = error; - return _this2.instance.Events.trigger("error", e); - } - })(); + // notice because option default will flip in next major + if (opts.extended === undefined) { + deprecate('undefined extended: provide extended option') } - __disconnect__(flush) { - clearInterval(this.heartbeat); + var extended = opts.extended !== false + var inflate = opts.inflate !== false + var limit = typeof opts.limit !== 'number' + ? bytes.parse(opts.limit || '100kb') + : opts.limit + var type = opts.type || 'application/x-www-form-urlencoded' + var verify = opts.verify || false - if (this.sharedConnection) { - return this.connection.__removeLimiter__(this.instance); - } else { - return this.connection.disconnect(flush); - } + if (verify !== false && typeof verify !== 'function') { + throw new TypeError('option verify must be function') } - runScript(name, args) { - var _this3 = this; - - return _asyncToGenerator(function* () { - if (!(name === "init" || name === "register_client")) { - yield _this3.ready; - } - - return new _this3.Promise((resolve, reject) => { - var all_args, arr; - all_args = [Date.now(), _this3.clientId].concat(args); - - _this3.instance.Events.trigger("debug", `Calling Redis script: ${name}.lua`, all_args); + // create the appropriate query parser + var queryparse = extended + ? extendedparser(opts) + : simpleparser(opts) - arr = _this3.connection.__scriptArgs__(name, _this3.originalId, all_args, function (err, replies) { - if (err != null) { - return reject(err); - } + // create the appropriate type checking function + var shouldParse = typeof type !== 'function' + ? typeChecker(type) + : type - return resolve(replies); - }); - return _this3.connection.__scriptFn__(name)(...arr); - }).catch(e => { - if (e.message === "SETTINGS_KEY_NOT_FOUND") { - if (name === "heartbeat") { - return _this3.Promise.resolve(); - } else { - return _this3.runScript("init", _this3.prepareInitSettings(false)).then(() => { - return _this3.runScript(name, args); - }); - } - } else if (e.message === "UNKNOWN_CLIENT") { - return _this3.runScript("register_client", [_this3.instance.queued()]).then(() => { - return _this3.runScript(name, args); - }); - } else { - return _this3.Promise.reject(e); - } - }); - })(); + function parse (body) { + return body.length + ? queryparse(body) + : {} } - prepareArray(arr) { - var i, len, results, x; - results = []; - - for (i = 0, len = arr.length; i < len; i++) { - x = arr[i]; - results.push(x != null ? x.toString() : ""); + return function urlencodedParser (req, res, next) { + if (req._body) { + debug('body already parsed') + next() + return } - return results; - } + req.body = req.body || {} - prepareObject(obj) { - var arr, k, v; - arr = []; + // skip requests without bodies + if (!typeis.hasBody(req)) { + debug('skip empty body') + next() + return + } - for (k in obj) { - v = obj[k]; - arr.push(k, v != null ? v.toString() : ""); + debug('content-type %j', req.headers['content-type']) + + // determine if request should be parsed + if (!shouldParse(req)) { + debug('skip parsing') + next() + return } - return arr; - } + // assert charset + var charset = getCharset(req) || 'utf-8' + if (charset !== 'utf-8') { + debug('invalid charset') + next(createError(415, 'unsupported charset "' + charset.toUpperCase() + '"', { + charset: charset, + type: 'charset.unsupported' + })) + return + } - prepareInitSettings(clear) { - var args; - args = this.prepareObject(Object.assign({}, this.storeOptions, { - id: this.originalId, - version: this.instance.version, - groupTimeout: this.timeout, - clientTimeout: this.clientTimeout - })); - args.unshift(clear ? 1 : 0, this.instance.version); - return args; + // read + read(req, res, next, parse, debug, { + debug: debug, + encoding: charset, + inflate: inflate, + limit: limit, + verify: verify + }) } +} - convertBool(b) { - return !!b; - } +/** + * Get the extended query parser. + * + * @param {object} options + */ - __updateSettings__(options) { - var _this4 = this; +function extendedparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('qs') - return _asyncToGenerator(function* () { - yield _this4.runScript("update_settings", _this4.prepareObject(options)); - return parser.overwrite(options, options, _this4.storeOptions); - })(); + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') } - __running__() { - return this.runScript("running", []); + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 } - __queued__() { - return this.runScript("queued", []); - } + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) - __done__() { - return this.runScript("done", []); - } + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } - __groupCheck__() { - var _this5 = this; + var arrayLimit = Math.max(100, paramCount) - return _asyncToGenerator(function* () { - return _this5.convertBool((yield _this5.runScript("group_check", []))); - })(); + debug('parse extended urlencoding') + return parse(body, { + allowPrototypes: true, + arrayLimit: arrayLimit, + depth: Infinity, + parameterLimit: parameterLimit + }) } +} - __incrementReservoir__(incr) { - return this.runScript("increment_reservoir", [incr]); - } +/** + * Get the charset of a request. + * + * @param {object} req + * @api private + */ - __currentReservoir__() { - return this.runScript("current_reservoir", []); +function getCharset (req) { + try { + return (contentType.parse(req).parameters.charset || '').toLowerCase() + } catch (e) { + return undefined } +} - __check__(weight) { - var _this6 = this; +/** + * Count the number of parameters, stopping once limit reached + * + * @param {string} body + * @param {number} limit + * @api private + */ - return _asyncToGenerator(function* () { - return _this6.convertBool((yield _this6.runScript("check", _this6.prepareArray([weight])))); - })(); +function parameterCount (body, limit) { + var count = 0 + var index = 0 + + while ((index = body.indexOf('&', index)) !== -1) { + count++ + index++ + + if (count === limit) { + return undefined + } } - __register__(index, weight, expiration) { - var _this7 = this; + return count +} - return _asyncToGenerator(function* () { - var reservoir, success, wait; +/** + * Get parser for module name dynamically. + * + * @param {string} name + * @return {function} + * @api private + */ - var _ref4 = yield _this7.runScript("register", _this7.prepareArray([index, weight, expiration])); +function parser (name) { + var mod = parsers[name] - var _ref5 = _slicedToArray(_ref4, 3); + if (mod !== undefined) { + return mod.parse + } - success = _ref5[0]; - wait = _ref5[1]; - reservoir = _ref5[2]; - return { - success: _this7.convertBool(success), - wait, - reservoir - }; - })(); + // this uses a switch for static require analysis + switch (name) { + case 'qs': + mod = __nccwpck_require__(22760) + break + case 'querystring': + mod = __nccwpck_require__(71191) + break } - __submit__(queueLength, weight) { - var _this8 = this; + // store to prevent invoking require() + parsers[name] = mod - return _asyncToGenerator(function* () { - var blocked, e, maxConcurrent, overweight, reachedHWM, strategy; + return mod.parse +} - try { - var _ref6 = yield _this8.runScript("submit", _this8.prepareArray([queueLength, weight])); +/** + * Get the simple query parser. + * + * @param {object} options + */ - var _ref7 = _slicedToArray(_ref6, 3); +function simpleparser (options) { + var parameterLimit = options.parameterLimit !== undefined + ? options.parameterLimit + : 1000 + var parse = parser('querystring') - reachedHWM = _ref7[0]; - blocked = _ref7[1]; - strategy = _ref7[2]; - return { - reachedHWM: _this8.convertBool(reachedHWM), - blocked: _this8.convertBool(blocked), - strategy - }; - } catch (error) { - e = error; + if (isNaN(parameterLimit) || parameterLimit < 1) { + throw new TypeError('option parameterLimit must be a positive number') + } - if (e.message.indexOf("OVERWEIGHT") === 0) { - var _e$message$split = e.message.split(":"); + if (isFinite(parameterLimit)) { + parameterLimit = parameterLimit | 0 + } - var _e$message$split2 = _slicedToArray(_e$message$split, 3); + return function queryparse (body) { + var paramCount = parameterCount(body, parameterLimit) - overweight = _e$message$split2[0]; - weight = _e$message$split2[1]; - maxConcurrent = _e$message$split2[2]; - throw new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${maxConcurrent}`); - } else { - throw e; - } - } - })(); + if (paramCount === undefined) { + debug('too many parameters') + throw createError(413, 'too many parameters', { + type: 'parameters.too.many' + }) + } + + debug('parse urlencoding') + return parse(body, undefined, undefined, { maxKeys: parameterLimit }) } +} - __free__(index, weight) { - var _this9 = this; +/** + * Get the simple type checker. + * + * @param {string} type + * @return {function} + */ - return _asyncToGenerator(function* () { - var running; - running = yield _this9.runScript("free", _this9.prepareArray([index])); - return { - running - }; - })(); +function typeChecker (type) { + return function checkType (req) { + return Boolean(typeis(req, type)) } +} -}; -module.exports = RedisDatastore; /***/ }), -/***/ 4169: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 15377: +/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ +exports = module.exports = __nccwpck_require__(22552); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); -var headers, lua, templates; -lua = __nccwpck_require__(23122); -headers = { - refs: lua["refs.lua"], - validate_keys: lua["validate_keys.lua"], - validate_client: lua["validate_client.lua"], - refresh_expiration: lua["refresh_expiration.lua"], - process_tick: lua["process_tick.lua"], - conditions_check: lua["conditions_check.lua"], - get_time: lua["get_time.lua"] -}; +/** + * Colors. + */ -exports.allKeys = function (id) { - return [ - /* - HASH - */ - `b_${id}_settings`, - /* - HASH - job index -> weight - */ - `b_${id}_job_weights`, - /* - ZSET - job index -> expiration - */ - `b_${id}_job_expirations`, - /* - HASH - job index -> client - */ - `b_${id}_job_clients`, - /* - ZSET - client -> sum running - */ - `b_${id}_client_running`, - /* - HASH - client -> num queued - */ - `b_${id}_client_num_queued`, - /* - ZSET - client -> last job registered - */ - `b_${id}_client_last_registered`, - /* - ZSET - client -> last seen - */ - `b_${id}_client_last_seen`]; -}; +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; -templates = { - init: { - keys: exports.allKeys, - headers: ["process_tick"], - refresh_expiration: true, - code: lua["init.lua"] - }, - group_check: { - keys: exports.allKeys, - headers: [], - refresh_expiration: false, - code: lua["group_check.lua"] - }, - register_client: { - keys: exports.allKeys, - headers: ["validate_keys"], - refresh_expiration: false, - code: lua["register_client.lua"] - }, - blacklist_client: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client"], - refresh_expiration: false, - code: lua["blacklist_client.lua"] - }, - heartbeat: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: false, - code: lua["heartbeat.lua"] - }, - update_settings: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: true, - code: lua["update_settings.lua"] - }, - running: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: false, - code: lua["running.lua"] - }, - queued: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client"], - refresh_expiration: false, - code: lua["queued.lua"] - }, - done: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: false, - code: lua["done.lua"] - }, - check: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], - refresh_expiration: false, - code: lua["check.lua"] - }, - submit: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], - refresh_expiration: true, - code: lua["submit.lua"] - }, - register: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], - refresh_expiration: true, - code: lua["register.lua"] - }, - free: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: true, - code: lua["free.lua"] - }, - current_reservoir: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: false, - code: lua["current_reservoir.lua"] - }, - increment_reservoir: { - keys: exports.allKeys, - headers: ["validate_keys", "validate_client", "process_tick"], - refresh_expiration: true, - code: lua["increment_reservoir.lua"] +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; } -}; -exports.names = Object.keys(templates); -exports.keys = function (name, id) { - return templates[name].keys(id); -}; + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ -exports.payload = function (name) { - var template; - template = templates[name]; - return Array.prototype.concat(headers.refs, template.headers.map(function (h) { - return headers[h]; - }), template.refresh_expiration ? headers.refresh_expiration : "", template.code).join("\n"); +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } }; -/***/ }), -/***/ 2527: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Colorize log arguments if enabled. + * + * @api public + */ -"use strict"; +function formatArgs(args) { + var useColors = this.useColors; + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); -var BottleneckError, States; -BottleneckError = __nccwpck_require__(93529); -States = class States { - constructor(status1) { - this.status = status1; - this.jobs = {}; - this.counts = this.status.map(function () { - return 0; - }); - } + if (!useColors) return; - next(id) { - var current, next; - current = this.jobs[id]; - next = current + 1; + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') - if (current != null && next < this.status.length) { - this.counts[current]--; - this.counts[next]++; - return this.jobs[id]++; - } else if (current != null) { - this.counts[current]--; - return delete this.jobs[id]; + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; } - } + }); - start(id) { - var initial; - initial = 0; - this.jobs[id] = initial; - return this.counts[initial]++; - } + args.splice(lastC, 0, c); +} - remove(id) { - var current; - current = this.jobs[id]; +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ - if (current != null) { - this.counts[current]--; - delete this.jobs[id]; +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; } + } catch(e) {} +} - return current != null; - } +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - jobStatus(id) { - var ref; - return (ref = this.status[this.jobs[id]]) != null ? ref : null; +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} + + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; } - statusJobs(status) { - var k, pos, ref, results, v; + return r; +} - if (status != null) { - pos = this.status.indexOf(status); +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ - if (pos < 0) { - throw new BottleneckError(`status must be one of ${this.status.join(', ')}`); - } +exports.enable(load()); - ref = this.jobs; - results = []; +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ - for (k in ref) { - v = ref[k]; +function localstorage() { + try { + return window.localStorage; + } catch (e) {} +} - if (v === pos) { - results.push(k); - } - } - return results; - } else { - return Object.keys(this.jobs); - } - } +/***/ }), - statusCounts() { - return this.counts.reduce((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }, {}); - } +/***/ 22552: +/***/ ((module, exports, __nccwpck_require__) => { -}; -module.exports = States; -/***/ }), +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ -/***/ 56029: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __nccwpck_require__(73233); -"use strict"; +/** + * The currently active debug mode names, and names to skip. + */ +exports.names = []; +exports.skips = []; -function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ -function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } +exports.formatters = {}; -function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } +/** + * Previous log timestamp. + */ -function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } +var prevTime; -function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ -function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } +function selectColor(namespace) { + var hash = 0, i; -var DLList, - Sync, - splice = [].splice; -DLList = __nccwpck_require__(38579); -Sync = class Sync { - constructor(name, Promise) { - this.submit = this.submit.bind(this); - this.name = name; - this.Promise = Promise; - this._running = 0; - this._queue = new DLList(); + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer } - isEmpty() { - return this._queue.length === 0; - } + return exports.colors[Math.abs(hash) % exports.colors.length]; +} - _tryToRun() { - var next; +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ - if (this._running < 1 && this._queue.length > 0) { - this._running++; - next = this._queue.shift(); - return next.task(...next.args, (...args) => { - this._running--; +function createDebug(namespace) { - this._tryToRun(); + function debug() { + // disabled? + if (!debug.enabled) return; - return typeof next.cb === "function" ? next.cb(...args) : void 0; - }); - } - } + var self = debug; - submit(task, ...args) { - var _ref, _ref2, _splice$call, _splice$call2; + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - var cb, ref; - ref = args, (_ref = ref, _ref2 = _toArray(_ref), args = _ref2.slice(0), _ref), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call); + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } - this._queue.push({ - task, - args, - cb - }); + args[0] = exports.coerce(args[0]); - return this._tryToRun(); - } + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } - schedule(task, ...args) { - var wrapped; + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); - wrapped = function wrapped(...args) { - var _ref3, _ref4, _splice$call3, _splice$call4; + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); - var cb, ref; - ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), args = _ref4.slice(0), _ref3), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3); - return task(...args).then(function (...args) { - return cb(null, ...args); - }).catch(function (...args) { - return cb(...args); - }); - }; + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); - return new this.Promise((resolve, reject) => { - return this.submit(wrapped, ...args, function (...args) { - return (args[0] != null ? reject : (args.shift(), resolve))(...args); - }); - }); + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); } -}; -module.exports = Sync; + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); -/***/ }), + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } -/***/ 27356: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return debug; +} -"use strict"; +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ +function enable(namespaces) { + exports.save(namespaces); -module.exports = __nccwpck_require__(83911); + exports.names = []; + exports.skips = []; -/***/ }), + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; -/***/ 67823: -/***/ ((__unused_webpack_module, exports) => { + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} -"use strict"; +/** + * Disable debug output. + * + * @api public + */ +function disable() { + exports.enable(''); +} -exports.load = function (received, defaults, onto = {}) { - var k, ref, v; +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ - for (k in defaults) { - v = defaults[k]; - onto[k] = (ref = received[k]) != null ? ref : v; +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} - return onto; -}; +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ -exports.overwrite = function (received, defaults, onto = {}) { - var k, v; +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} - for (k in received) { - v = received[k]; - if (defaults[k] !== void 0) { - onto[k] = v; - } - } +/***/ }), + +/***/ 7471: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ + +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __nccwpck_require__(15377); +} else { + module.exports = __nccwpck_require__(74117); +} - return onto; -}; /***/ }), -/***/ 11174: -/***/ (function(module) { +/***/ 74117: +/***/ ((module, exports, __nccwpck_require__) => { /** - * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support. - * https://github.com/SGrondin/bottleneck - */ -(function (global, factory) { - true ? module.exports = factory() : - 0; -}(this, (function () { 'use strict'; + * Module dependencies. + */ - var commonjsGlobal = typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; +var tty = __nccwpck_require__(33867); +var util = __nccwpck_require__(31669); - function getCjsExportFromNamespace (n) { - return n && n.default || n; - } +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ - var load = function(received, defaults, onto = {}) { - var k, ref, v; - for (k in defaults) { - v = defaults[k]; - onto[k] = (ref = received[k]) != null ? ref : v; - } - return onto; - }; +exports = module.exports = __nccwpck_require__(22552); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; - var overwrite = function(received, defaults, onto = {}) { - var k, v; - for (k in received) { - v = received[k]; - if (defaults[k] !== void 0) { - onto[k] = v; - } - } - return onto; - }; +/** + * Colors. + */ - var parser = { - load: load, - overwrite: overwrite - }; +exports.colors = [6, 2, 3, 4, 5, 1]; - var DLList; +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - DLList = class DLList { - constructor(_queues) { - this._queues = _queues; - this._first = null; - this._last = null; - this.length = 0; - } +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - push(value) { - var node, ref1; - this.length++; - if ((ref1 = this._queues) != null) { - ref1.incr(); - } - node = { - value, - next: null - }; - if (this._last != null) { - this._last.next = node; - this._last = node; - } else { - this._first = this._last = node; - } - return void 0; - } + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); - shift() { - var ref1, ref2, value; - if (this._first == null) { - return void 0; - } else { - this.length--; - if ((ref1 = this._queues) != null) { - ref1.decr(); - } - } - value = this._first.value; - this._first = (ref2 = this._first.next) != null ? ref2 : (this._last = null); - return value; - } + obj[prop] = val; + return obj; +}, {}); - first() { - if (this._first != null) { - return this._first.value; - } - } +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ - getArray() { - var node, ref, results; - node = this._first; - results = []; - while (node != null) { - results.push((ref = node, node = node.next, ref.value)); - } - return results; - } +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - forEachShift(cb) { - var node; - node = this.shift(); - while (node != null) { - (cb(node), node = this.shift()); - } - return void 0; - } +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} - }; +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); - var DLList_1 = DLList; +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ - var Events; +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} - Events = class Events { - constructor(instance) { - this.instance = instance; - this._events = {}; - if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) { - throw new Error("An Emitter already exists for this object"); - } - this.instance.on = (name, cb) => { - return this._addListener(name, "many", cb); - }; - this.instance.once = (name, cb) => { - return this._addListener(name, "once", cb); - }; - this.instance.removeAllListeners = (name = null) => { - if (name != null) { - return delete this._events[name]; - } else { - return this._events = {}; - } - }; - } +/** + * Map %o to `util.inspect()`, all on a single line. + */ - _addListener(name, status, cb) { - var base; - if ((base = this._events)[name] == null) { - base[name] = []; - } - this._events[name].push({cb, status}); - return this.instance; - } +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; - listenerCount(name) { - if (this._events[name] != null) { - return this._events[name].length; - } else { - return 0; - } - } +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ - async trigger(name, ...args) { - var e, promises; - try { - if (name !== "debug") { - this.trigger("debug", `Event triggered: ${name}`, args); - } - if (this._events[name] == null) { - return; - } - this._events[name] = this._events[name].filter(function(listener) { - return listener.status !== "none"; - }); - promises = this._events[name].map(async(listener) => { - var e, returned; - if (listener.status === "none") { - return; - } - if (listener.status === "once") { - listener.status = "none"; - } - try { - returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; - if (typeof (returned != null ? returned.then : void 0) === "function") { - return (await returned); - } else { - return returned; - } - } catch (error) { - e = error; - { - this.trigger("error", e); - } - return null; - } - }); - return ((await Promise.all(promises))).find(function(x) { - return x != null; - }); - } catch (error) { - e = error; - { - this.trigger("error", e); - } - return null; - } - } +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; - }; +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ - var Events_1 = Events; +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; - var DLList$1, Events$1, Queues; + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - DLList$1 = DLList_1; + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} - Events$1 = Events_1; +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ - Queues = class Queues { - constructor(num_priorities) { - var i; - this.Events = new Events$1(this); - this._length = 0; - this._lists = (function() { - var j, ref, results; - results = []; - for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { - results.push(new DLList$1(this)); - } - return results; - }).call(this); - } +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} - incr() { - if (this._length++ === 0) { - return this.Events.trigger("leftzero"); - } - } +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ - decr() { - if (--this._length === 0) { - return this.Events.trigger("zero"); - } - } +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} - push(priority, job) { - return this._lists[priority].push(job); - } +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - queued(priority) { - if (priority != null) { - return this._lists[priority].length; - } else { - return this._length; - } - } +function load() { + return process.env.DEBUG; +} - shiftAll(fn) { - return this._lists.forEach(function(list) { - return list.forEachShift(fn); - }); - } +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ - getFirst(arr = this._lists) { - var j, len, list; - for (j = 0, len = arr.length; j < len; j++) { - list = arr[j]; - if (list.length > 0) { - return list; - } - } - return []; - } +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); - shiftLastFrom(priority) { - return this.getFirst(this._lists.slice(priority).reverse()).shift(); - } + // Note stream._type is used for test-module-load-list.js - }; + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; - var Queues_1 = Queues; + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; - var BottleneckError; + case 'FILE': + var fs = __nccwpck_require__(35747); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; - BottleneckError = class BottleneckError extends Error {}; + case 'PIPE': + case 'TCP': + var net = __nccwpck_require__(11631); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); - var BottleneckError_1 = BottleneckError; + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; - var BottleneckError$1, LocalDatastore, parser$1; + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; - parser$1 = parser; + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } - BottleneckError$1 = BottleneckError_1; + // For supporting legacy API we put the FD here. + stream.fd = fd; - LocalDatastore = class LocalDatastore { - constructor(instance, storeOptions, storeInstanceOptions) { - this.instance = instance; - this.storeOptions = storeOptions; - this.clientId = this.instance._randomIndex(); - parser$1.load(storeInstanceOptions, storeInstanceOptions, this); - this._nextRequest = this._lastReservoirRefresh = Date.now(); - this._running = 0; - this._done = 0; - this._unblockTime = 0; - this.ready = this.Promise.resolve(); - this.clients = {}; - this._startHeartbeat(); - } + stream._isStdio = true; - _startHeartbeat() { - var base; - if ((this.heartbeat == null) && (this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) { - return typeof (base = (this.heartbeat = setInterval(() => { - var now; - now = Date.now(); - if (now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { - this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; - this._lastReservoirRefresh = now; - return this.instance._drainAll(this.computeCapacity()); - } - }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0; - } else { - return clearInterval(this.heartbeat); - } - } + return stream; +} - async __publish__(message) { - await this.yieldLoop(); - return this.instance.Events.trigger("message", message.toString()); - } +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ - async __disconnect__(flush) { - await this.yieldLoop(); - clearInterval(this.heartbeat); - return this.Promise.resolve(); - } +function init (debug) { + debug.inspectOpts = {}; - yieldLoop(t = 0) { - return new this.Promise(function(resolve, reject) { - return setTimeout(resolve, t); - }); - } + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} - computePenalty() { - var ref; - return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; - } +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ - async __updateSettings__(options) { - await this.yieldLoop(); - parser$1.overwrite(options, options, this.storeOptions); - this._startHeartbeat(); - this.instance._drainAll(this.computeCapacity()); - return true; - } +exports.enable(load()); - async __running__() { - await this.yieldLoop(); - return this._running; - } - async __queued__() { - await this.yieldLoop(); - return this.instance.queued(); - } +/***/ }), - async __done__() { - await this.yieldLoop(); - return this._done; - } +/***/ 73233: +/***/ ((module) => { - async __groupCheck__(time) { - await this.yieldLoop(); - return (this._nextRequest + this.timeout) < time; - } +/** + * Helpers. + */ - computeCapacity() { - var maxConcurrent, reservoir; - ({maxConcurrent, reservoir} = this.storeOptions); - if ((maxConcurrent != null) && (reservoir != null)) { - return Math.min(maxConcurrent - this._running, reservoir); - } else if (maxConcurrent != null) { - return maxConcurrent - this._running; - } else if (reservoir != null) { - return reservoir; - } else { - return null; - } - } +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; - conditionsCheck(weight) { - var capacity; - capacity = this.computeCapacity(); - return (capacity == null) || weight <= capacity; - } +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ - async __incrementReservoir__(incr) { - var reservoir; - await this.yieldLoop(); - reservoir = this.storeOptions.reservoir += incr; - this.instance._drainAll(this.computeCapacity()); - return reservoir; - } +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; - async __currentReservoir__() { - await this.yieldLoop(); - return this.storeOptions.reservoir; - } +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - isBlocked(now) { - return this._unblockTime >= now; - } +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} - check(weight, now) { - return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; - } +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - async __check__(weight) { - var now; - await this.yieldLoop(); - now = Date.now(); - return this.check(weight, now); - } +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} - async __register__(index, weight, expiration) { - var now, wait; - await this.yieldLoop(); - now = Date.now(); - if (this.conditionsCheck(weight)) { - this._running += weight; - if (this.storeOptions.reservoir != null) { - this.storeOptions.reservoir -= weight; - } - wait = Math.max(this._nextRequest - now, 0); - this._nextRequest = now + wait + this.storeOptions.minTime; - return { - success: true, - wait, - reservoir: this.storeOptions.reservoir - }; - } else { - return { - success: false - }; - } - } +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - strategyIsBlock() { - return this.storeOptions.strategy === 3; - } +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} - async __submit__(queueLength, weight) { - var blocked, now, reachedHWM; - await this.yieldLoop(); - if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { - throw new BottleneckError$1(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); - } - now = Date.now(); - reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now); - blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); - if (blocked) { - this._unblockTime = now + this.computePenalty(); - this._nextRequest = this._unblockTime + this.storeOptions.minTime; - this.instance._dropAllQueued(); - } - return { - reachedHWM, - blocked, - strategy: this.storeOptions.strategy - }; - } +/** + * Pluralization helper. + */ - async __free__(index, weight) { - await this.yieldLoop(); - this._running -= weight; - this._done += weight; - this.instance._drainAll(this.computeCapacity()); - return { - running: this._running - }; - } +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} - }; - var LocalDatastore_1 = LocalDatastore; +/***/ }), - var BottleneckError$2, States; +/***/ 85442: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - BottleneckError$2 = BottleneckError_1; +"use strict"; - States = class States { - constructor(status1) { - this.status = status1; - this.jobs = {}; - this.counts = this.status.map(function() { - return 0; - }); - } - next(id) { - var current, next; - current = this.jobs[id]; - next = current + 1; - if ((current != null) && next < this.status.length) { - this.counts[current]--; - this.counts[next]++; - return this.jobs[id]++; - } else if (current != null) { - this.counts[current]--; - return delete this.jobs[id]; - } - } +var Batcher, Events, parser; +parser = __nccwpck_require__(67823); +Events = __nccwpck_require__(107); - start(id) { - var initial; - initial = 0; - this.jobs[id] = initial; - return this.counts[initial]++; - } +Batcher = function () { + class Batcher { + constructor(options = {}) { + this.options = options; + parser.load(this.options, this.defaults, this); + this.Events = new Events(this); + this._arr = []; - remove(id) { - var current; - current = this.jobs[id]; - if (current != null) { - this.counts[current]--; - delete this.jobs[id]; - } - return current != null; - } + this._resetPromise(); - jobStatus(id) { - var ref; - return (ref = this.status[this.jobs[id]]) != null ? ref : null; - } + this._lastFlush = Date.now(); + } - statusJobs(status) { - var k, pos, ref, results, v; - if (status != null) { - pos = this.status.indexOf(status); - if (pos < 0) { - throw new BottleneckError$2(`status must be one of ${this.status.join(', ')}`); - } - ref = this.jobs; - results = []; - for (k in ref) { - v = ref[k]; - if (v === pos) { - results.push(k); - } - } - return results; - } else { - return Object.keys(this.jobs); - } - } + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } - statusCounts() { - return this.counts.reduce(((acc, v, i) => { - acc[this.status[i]] = v; - return acc; - }), {}); - } + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); - }; + this._resolve(); - var States_1 = States; + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); + } - var DLList$2, Sync, - splice = [].splice; + add(data) { + var ret; - DLList$2 = DLList_1; + this._arr.push(data); - Sync = class Sync { - constructor(name, Promise) { - this.submit = this.submit.bind(this); - this.name = name; - this.Promise = Promise; - this._running = 0; - this._queue = new DLList$2(); - } + ret = this._promise; - isEmpty() { - return this._queue.length === 0; - } + if (this._arr.length === this.maxSize) { + this._flush(); + } else if (this.maxTime != null && this._arr.length === 1) { + this._timeout = setTimeout(() => { + return this._flush(); + }, this.maxTime); + } - _tryToRun() { - var next; - if ((this._running < 1) && this._queue.length > 0) { - this._running++; - next = this._queue.shift(); - return next.task(...next.args, (...args) => { - this._running--; - this._tryToRun(); - return typeof next.cb === "function" ? next.cb(...args) : void 0; - }); - } - } + return ret; + } - submit(task, ...args) { - var cb, ref; - ref = args, [...args] = ref, [cb] = splice.call(args, -1); - this._queue.push({task, args, cb}); - return this._tryToRun(); - } + } - schedule(task, ...args) { - var wrapped; - wrapped = function(...args) { - var cb, ref; - ref = args, [...args] = ref, [cb] = splice.call(args, -1); - return (task(...args)).then(function(...args) { - return cb(null, ...args); - }).catch(function(...args) { - return cb(...args); - }); - }; - return new this.Promise((resolve, reject) => { - return this.submit(wrapped, ...args, function(...args) { - return (args[0] != null ? reject : (args.shift(), resolve))(...args); - }); - }); - } + ; + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise + }; + return Batcher; +}.call(void 0); - }; +module.exports = Batcher; - var Sync_1 = Sync; +/***/ }), - var version = "2.17.1"; - var version$1 = { - version: version - }; +/***/ 83911: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var version$2 = /*#__PURE__*/Object.freeze({ - version: version, - default: version$1 - }); +"use strict"; - var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } - var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } - var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$2; +function _toArray(arr) { return _arrayWithHoles(arr) || _iterableToArray(arr) || _nonIterableRest(); } - parser$2 = parser; +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } - Events$2 = Events_1; +function _iterableToArray(iter) { if (Symbol.iterator in Object(iter) || Object.prototype.toString.call(iter) === "[object Arguments]") return Array.from(iter); } - RedisConnection$1 = require$$2; +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - IORedisConnection$1 = require$$3; +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - Scripts$1 = require$$4; +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - Group = (function() { - class Group { - constructor(limiterOptions = {}) { - this.deleteKey = this.deleteKey.bind(this); - this.updateSettings = this.updateSettings.bind(this); - this.limiterOptions = limiterOptions; - parser$2.load(this.limiterOptions, this.defaults, this); - this.Events = new Events$2(this); - this.instances = {}; - this.Bottleneck = Bottleneck_1; - this._startAutoCleanup(); - this.sharedConnection = this.connection != null; - if (this.connection == null) { - if (this.limiterOptions.datastore === "redis") { - this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); - } else if (this.limiterOptions.datastore === "ioredis") { - this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); - } - } - } +var Bottleneck, + DEFAULT_PRIORITY, + Events, + Job, + LocalDatastore, + NUM_PRIORITIES, + Queues, + RedisDatastore, + States, + Sync, + parser, + splice = [].splice; +NUM_PRIORITIES = 10; +DEFAULT_PRIORITY = 5; +parser = __nccwpck_require__(67823); +Queues = __nccwpck_require__(65893); +Job = __nccwpck_require__(25949); +LocalDatastore = __nccwpck_require__(38979); +RedisDatastore = __nccwpck_require__(4946); +Events = __nccwpck_require__(107); +States = __nccwpck_require__(2527); +Sync = __nccwpck_require__(56029); - key(key = "") { - var ref; - return (ref = this.instances[key]) != null ? ref : (() => { - var limiter; - limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { - id: `${this.id}-${key}`, - timeout: this.timeout, - connection: this.connection - })); - this.Events.trigger("created", limiter, key); - return limiter; - })(); - } +Bottleneck = function () { + class Bottleneck { + constructor(options = {}, ...invalid) { + var storeInstanceOptions, storeOptions; + this._addToQueue = this._addToQueue.bind(this); - async deleteKey(key = "") { - var deleted, instance; - instance = this.instances[key]; - if (this.connection) { - deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)])); - } - if (instance != null) { - delete this.instances[key]; - await instance.disconnect(); - } - return (instance != null) || deleted > 0; - } + this._validateOptions(options, invalid); - limiters() { - var k, ref, results, v; - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - results.push({ - key: k, - limiter: v - }); - } - return results; - } + parser.load(options, this.instanceDefaults, this); + this._queues = new Queues(NUM_PRIORITIES); + this._scheduled = {}; + this._states = new States(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); + this._limiter = null; + this.Events = new Events(this); + this._submitLock = new Sync("submit", this.Promise); + this._registerLock = new Sync("register", this.Promise); + storeOptions = parser.load(options, this.storeDefaults, {}); - keys() { - return Object.keys(this.instances); - } + this._store = function () { + if (this.datastore === "redis" || this.datastore === "ioredis" || this.connection != null) { + storeInstanceOptions = parser.load(options, this.redisStoreDefaults, {}); + return new RedisDatastore(this, storeOptions, storeInstanceOptions); + } else if (this.datastore === "local") { + storeInstanceOptions = parser.load(options, this.localStoreDefaults, {}); + return new LocalDatastore(this, storeOptions, storeInstanceOptions); + } else { + throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); + } + }.call(this); - async clusterKeys() { - var cursor, end, found, i, k, keys, len, next, start; - if (this.connection == null) { - return this.Promise.resolve(this.keys()); - } - keys = []; - cursor = null; - start = `b_${this.id}-`.length; - end = "_settings".length; - while (cursor !== 0) { - [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000])); - cursor = ~~next; - for (i = 0, len = found.length; i < len; i++) { - k = found[i]; - keys.push(k.slice(start, -end)); - } - } - return keys; - } + this._queues.on("leftzero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; + }); - _startAutoCleanup() { - var base; - clearInterval(this.interval); - return typeof (base = (this.interval = setInterval(async() => { - var e, k, ref, results, time, v; - time = Date.now(); - ref = this.instances; - results = []; - for (k in ref) { - v = ref[k]; - try { - if ((await v._store.__groupCheck__(time))) { - results.push(this.deleteKey(k)); - } else { - results.push(void 0); - } - } catch (error) { - e = error; - results.push(v.Events.trigger("error", e)); - } - } - return results; - }, this.timeout / 2))).unref === "function" ? base.unref() : void 0; - } + this._queues.on("zero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; + }); + } - updateSettings(options = {}) { - parser$2.overwrite(options, this.defaults, this); - parser$2.overwrite(options, options, this.limiterOptions); - if (options.timeout != null) { - return this._startAutoCleanup(); - } - } + _validateOptions(options, invalid) { + if (!(options != null && typeof options === "object" && invalid.length === 0)) { + throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); + } + } - disconnect(flush = true) { - var ref; - if (!this.sharedConnection) { - return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; - } - } + ready() { + return this._store.ready; + } - } - Group.prototype.defaults = { - timeout: 1000 * 60 * 5, - connection: null, - Promise: Promise, - id: "group-key" - }; + clients() { + return this._store.clients; + } - return Group; + channel() { + return `b_${this.id}`; + } - }).call(commonjsGlobal); + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } - var Group_1 = Group; + publish(message) { + return this._store.__publish__(message); + } - var Batcher, Events$3, parser$3; + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } - parser$3 = parser; + chain(_limiter) { + this._limiter = _limiter; + return this; + } - Events$3 = Events_1; + queued(priority) { + return this._queues.queued(priority); + } - Batcher = (function() { - class Batcher { - constructor(options = {}) { - this.options = options; - parser$3.load(this.options, this.defaults, this); - this.Events = new Events$3(this); - this._arr = []; - this._resetPromise(); - this._lastFlush = Date.now(); - } + clusterQueued() { + return this._store.__queued__(); + } - _resetPromise() { - return this._promise = new this.Promise((res, rej) => { - return this._resolve = res; - }); - } + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } - _flush() { - clearTimeout(this._timeout); - this._lastFlush = Date.now(); - this._resolve(); - this.Events.trigger("batch", this._arr); - this._arr = []; - return this._resetPromise(); - } + running() { + return this._store.__running__(); + } - add(data) { - var ret; - this._arr.push(data); - ret = this._promise; - if (this._arr.length === this.maxSize) { - this._flush(); - } else if ((this.maxTime != null) && this._arr.length === 1) { - this._timeout = setTimeout(() => { - return this._flush(); - }, this.maxTime); - } - return ret; - } + done() { + return this._store.__done__(); + } - } - Batcher.prototype.defaults = { - maxTime: null, - maxSize: null, - Promise: Promise - }; + jobStatus(id) { + return this._states.jobStatus(id); + } - return Batcher; + jobs(status) { + return this._states.statusJobs(status); + } - }).call(commonjsGlobal); + counts() { + return this._states.statusCounts(); + } - var Batcher_1 = Batcher; + _randomIndex() { + return Math.random().toString(36).slice(2); + } - var require$$3$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); + check(weight = 1) { + return this._store.__check__(weight); + } - var require$$7 = getCjsExportFromNamespace(version$2); + _clearGlobalState(index) { + if (this._scheduled[index] != null) { + clearTimeout(this._scheduled[index].expiration); + delete this._scheduled[index]; + return true; + } else { + return false; + } + } - var Bottleneck, DEFAULT_PRIORITY, Events$4, LocalDatastore$1, NUM_PRIORITIES, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$4, - splice$1 = [].splice; + _free(index, job, options, eventInfo) { + var _this = this; - NUM_PRIORITIES = 10; + return _asyncToGenerator(function* () { + var e, running; - DEFAULT_PRIORITY = 5; + try { + var _ref = yield _this._store.__free__(index, options.weight); - parser$4 = parser; + running = _ref.running; - Queues$1 = Queues_1; + _this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); - LocalDatastore$1 = LocalDatastore_1; + if (running === 0 && _this.empty()) { + return _this.Events.trigger("idle"); + } + } catch (error1) { + e = error1; + return _this.Events.trigger("error", e); + } + })(); + } - RedisDatastore$1 = require$$3$1; + _run(index, job, wait) { + var clearGlobalState, free, run; + job.doRun(); + clearGlobalState = this._clearGlobalState.bind(this, index); + run = this._run.bind(this, index, job); + free = this._free.bind(this, index, job); + return this._scheduled[index] = { + timeout: setTimeout(() => { + return job.doExecute(this._limiter, clearGlobalState, run, free); + }, wait), + expiration: job.options.expiration != null ? setTimeout(function () { + return job.doExpire(clearGlobalState, run, free); + }, wait + job.options.expiration) : void 0, + job: job + }; + } - Events$4 = Events_1; + _drainOne(capacity) { + return this._registerLock.schedule(() => { + var args, index, next, options, queue; - States$1 = States_1; + if (this.queued() === 0) { + return this.Promise.resolve(null); + } - Sync$1 = Sync_1; + queue = this._queues.getFirst(); - Bottleneck = (function() { - class Bottleneck { - constructor(options = {}, ...invalid) { - var storeInstanceOptions, storeOptions; - this._drainOne = this._drainOne.bind(this); - this.submit = this.submit.bind(this); - this.schedule = this.schedule.bind(this); - this.updateSettings = this.updateSettings.bind(this); - this.incrementReservoir = this.incrementReservoir.bind(this); - this._validateOptions(options, invalid); - parser$4.load(options, this.instanceDefaults, this); - this._queues = new Queues$1(NUM_PRIORITIES); - this._scheduled = {}; - this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); - this._limiter = null; - this.Events = new Events$4(this); - this._submitLock = new Sync$1("submit", this.Promise); - this._registerLock = new Sync$1("register", this.Promise); - storeOptions = parser$4.load(options, this.storeDefaults, {}); - this._store = (function() { - if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { - storeInstanceOptions = parser$4.load(options, this.redisStoreDefaults, {}); - return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); - } else if (this.datastore === "local") { - storeInstanceOptions = parser$4.load(options, this.localStoreDefaults, {}); - return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); - } else { - throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); - } - }).call(this); - this._queues.on("leftzero", () => { - var base; - return typeof (base = this._store.heartbeat).ref === "function" ? base.ref() : void 0; - }); - this._queues.on("zero", () => { - var base; - return typeof (base = this._store.heartbeat).unref === "function" ? base.unref() : void 0; - }); - } + var _next2 = next = queue.first(); - _validateOptions(options, invalid) { - if (!((options != null) && typeof options === "object" && invalid.length === 0)) { - throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); - } - } + options = _next2.options; + args = _next2.args; - ready() { - return this._store.ready; - } + if (capacity != null && options.weight > capacity) { + return this.Promise.resolve(null); + } - clients() { - return this._store.clients; - } + this.Events.trigger("debug", `Draining ${options.id}`, { + args, + options + }); + index = this._randomIndex(); + return this._store.__register__(index, options.weight, options.expiration).then(({ + success, + wait, + reservoir + }) => { + var empty; + this.Events.trigger("debug", `Drained ${options.id}`, { + success, + args, + options + }); - channel() { - return `b_${this.id}`; - } + if (success) { + queue.shift(); + empty = this.empty(); - channel_client() { - return `b_${this.id}_${this._store.clientId}`; - } + if (empty) { + this.Events.trigger("empty"); + } - publish(message) { - return this._store.__publish__(message); - } + if (reservoir === 0) { + this.Events.trigger("depleted", empty); + } - disconnect(flush = true) { - return this._store.__disconnect__(flush); - } + this._run(index, next, wait); - chain(_limiter) { - this._limiter = _limiter; - return this; - } + return this.Promise.resolve(options.weight); + } else { + return this.Promise.resolve(null); + } + }); + }); + } - queued(priority) { - return this._queues.queued(priority); - } + _drainAll(capacity, total = 0) { + return this._drainOne(capacity).then(drained => { + var newCapacity; - clusterQueued() { - return this._store.__queued__(); - } + if (drained != null) { + newCapacity = capacity != null ? capacity - drained : capacity; + return this._drainAll(newCapacity, total + drained); + } else { + return this.Promise.resolve(total); + } + }).catch(e => { + return this.Events.trigger("error", e); + }); + } - empty() { - return this.queued() === 0 && this._submitLock.isEmpty(); - } + _dropAllQueued(message) { + return this._queues.shiftAll(function (job) { + return job.doDrop({ + message + }); + }); + } - running() { - return this._store.__running__(); - } + stop(options = {}) { + var done, waitForExecuting; + options = parser.load(options, this.stopDefaults); - done() { - return this._store.__done__(); - } + waitForExecuting = at => { + var finished; - jobStatus(id) { - return this._states.jobStatus(id); - } + finished = () => { + var counts; + counts = this._states.counts; + return counts[0] + counts[1] + counts[2] + counts[3] === at; + }; - jobs(status) { - return this._states.statusJobs(status); - } + return new this.Promise((resolve, reject) => { + if (finished()) { + return resolve(); + } else { + return this.on("done", () => { + if (finished()) { + this.removeAllListeners("done"); + return resolve(); + } + }); + } + }); + }; - counts() { - return this._states.statusCounts(); - } + done = options.dropWaitingJobs ? (this._run = function (index, next) { + return next.doDrop({ + message: options.dropErrorMessage + }); + }, this._drainOne = () => { + return this.Promise.resolve(null); + }, this._registerLock.schedule(() => { + return this._submitLock.schedule(() => { + var k, ref, v; + ref = this._scheduled; - _sanitizePriority(priority) { - var sProperty; - sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; - if (sProperty < 0) { - return 0; - } else if (sProperty > NUM_PRIORITIES - 1) { - return NUM_PRIORITIES - 1; - } else { - return sProperty; - } - } + for (k in ref) { + v = ref[k]; - _randomIndex() { - return Math.random().toString(36).slice(2); - } + if (this.jobStatus(v.job.options.id) === "RUNNING") { + clearTimeout(v.timeout); + clearTimeout(v.expiration); + v.job.doDrop({ + message: options.dropErrorMessage + }); + } + } - check(weight = 1) { - return this._store.__check__(weight); - } + this._dropAllQueued(options.dropErrorMessage); - _run(next, wait, index, retryCount) { - var completed, done; - this.Events.trigger("debug", `Scheduling ${next.options.id}`, { - args: next.args, - options: next.options - }); - done = false; - completed = async(...args) => { - var e, error, eventInfo, retry, retryAfter, running; - if (!done) { - try { - done = true; - clearTimeout(this._scheduled[index].expiration); - delete this._scheduled[index]; - eventInfo = { - args: next.args, - options: next.options, - retryCount - }; - if ((error = args[0]) != null) { - retry = (await this.Events.trigger("failed", error, eventInfo)); - if (retry != null) { - retryAfter = ~~retry; - this.Events.trigger("retry", `Retrying ${next.options.id} after ${retryAfter} ms`, eventInfo); - return this._run(next, retryAfter, index, retryCount + 1); - } - } - this._states.next(next.options.id); // DONE - this.Events.trigger("debug", `Completed ${next.options.id}`, eventInfo); - this.Events.trigger("done", `Completed ${next.options.id}`, eventInfo); - ({running} = (await this._store.__free__(index, next.options.weight))); - this.Events.trigger("debug", `Freed ${next.options.id}`, eventInfo); - if (running === 0 && this.empty()) { - this.Events.trigger("idle"); - } - return typeof next.cb === "function" ? next.cb(...args) : void 0; - } catch (error1) { - e = error1; - return this.Events.trigger("error", e); - } - } - }; - if (retryCount === 0) { // RUNNING - this._states.next(next.options.id); - } - return this._scheduled[index] = { - timeout: setTimeout(() => { - this.Events.trigger("debug", `Executing ${next.options.id}`, { - args: next.args, - options: next.options - }); - if (retryCount === 0) { // EXECUTING - this._states.next(next.options.id); - } - if (this._limiter != null) { - return this._limiter.submit(next.options, next.task, ...next.args, completed); - } else { - return next.task(...next.args, completed); - } - }, wait), - expiration: next.options.expiration != null ? setTimeout(() => { - return completed(new Bottleneck.prototype.BottleneckError(`This job timed out after ${next.options.expiration} ms.`)); - }, wait + next.options.expiration) : void 0, - job: next - }; - } + return waitForExecuting(0); + }); + })) : this.schedule({ + priority: NUM_PRIORITIES - 1, + weight: 0 + }, () => { + return waitForExecuting(1); + }); - _drainOne(capacity) { - return this._registerLock.schedule(() => { - var args, index, next, options, queue; - if (this.queued() === 0) { - return this.Promise.resolve(null); - } - queue = this._queues.getFirst(); - ({options, args} = next = queue.first()); - if ((capacity != null) && options.weight > capacity) { - return this.Promise.resolve(null); - } - this.Events.trigger("debug", `Draining ${options.id}`, {args, options}); - index = this._randomIndex(); - return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => { - var empty; - this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options}); - if (success) { - queue.shift(); - empty = this.empty(); - if (empty) { - this.Events.trigger("empty"); - } - if (reservoir === 0) { - this.Events.trigger("depleted", empty); - } - this._run(next, wait, index, 0); - return this.Promise.resolve(options.weight); - } else { - return this.Promise.resolve(null); - } - }); - }); - } + this._receive = function (job) { + return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); + }; - _drainAll(capacity, total = 0) { - return this._drainOne(capacity).then((drained) => { - var newCapacity; - if (drained != null) { - newCapacity = capacity != null ? capacity - drained : capacity; - return this._drainAll(newCapacity, total + drained); - } else { - return this.Promise.resolve(total); - } - }).catch((e) => { - return this.Events.trigger("error", e); - }); - } + this.stop = () => { + return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); + }; - _drop(job, message = "This job has been dropped by Bottleneck") { - if (this._states.remove(job.options.id)) { - if (this.rejectOnDrop) { - if (typeof job.cb === "function") { - job.cb(new Bottleneck.prototype.BottleneckError(message)); - } - } - return this.Events.trigger("dropped", job); - } - } + return done; + } - _dropAllQueued(message) { - return this._queues.shiftAll((job) => { - return this._drop(job, message); - }); - } + _addToQueue(job) { + var _this2 = this; - stop(options = {}) { - var done, waitForExecuting; - options = parser$4.load(options, this.stopDefaults); - waitForExecuting = (at) => { - var finished; - finished = () => { - var counts; - counts = this._states.counts; - return (counts[0] + counts[1] + counts[2] + counts[3]) === at; - }; - return new this.Promise((resolve, reject) => { - if (finished()) { - return resolve(); - } else { - return this.on("done", () => { - if (finished()) { - this.removeAllListeners("done"); - return resolve(); - } - }); - } - }); - }; - done = options.dropWaitingJobs ? (this._run = (next) => { - return this._drop(next, options.dropErrorMessage); - }, this._drainOne = () => { - return this.Promise.resolve(null); - }, this._registerLock.schedule(() => { - return this._submitLock.schedule(() => { - var k, ref, v; - ref = this._scheduled; - for (k in ref) { - v = ref[k]; - if (this.jobStatus(v.job.options.id) === "RUNNING") { - clearTimeout(v.timeout); - clearTimeout(v.expiration); - this._drop(v.job, options.dropErrorMessage); - } - } - this._dropAllQueued(options.dropErrorMessage); - return waitForExecuting(0); - }); - })) : this.schedule({ - priority: NUM_PRIORITIES - 1, - weight: 0 - }, () => { - return waitForExecuting(1); - }); - this.submit = (...args) => { - var cb, ref; - ref = args, [...args] = ref, [cb] = splice$1.call(args, -1); - return typeof cb === "function" ? cb(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)) : void 0; - }; - this.stop = () => { - return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); - }; - return done; - } + return _asyncToGenerator(function* () { + var args, blocked, error, options, reachedHWM, shifted, strategy; + args = job.args; + options = job.options; - submit(...args) { - var cb, job, options, ref, ref1, task; - if (typeof args[0] === "function") { - ref = args, [task, ...args] = ref, [cb] = splice$1.call(args, -1); - options = parser$4.load({}, this.jobDefaults, {}); - } else { - ref1 = args, [options, task, ...args] = ref1, [cb] = splice$1.call(args, -1); - options = parser$4.load(options, this.jobDefaults); - } - job = {options, task, args, cb}; - options.priority = this._sanitizePriority(options.priority); - if (options.id === this.jobDefaults.id) { - options.id = `${options.id}-${this._randomIndex()}`; - } - if (this.jobStatus(options.id) != null) { - if (typeof job.cb === "function") { - job.cb(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${options.id})`)); - } - return false; - } - this._states.start(options.id); // RECEIVED - this.Events.trigger("debug", `Queueing ${options.id}`, {args, options}); - return this._submitLock.schedule(async() => { - var blocked, e, reachedHWM, shifted, strategy; - try { - ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); - this.Events.trigger("debug", `Queued ${options.id}`, {args, options, reachedHWM, blocked}); - } catch (error1) { - e = error1; - this._states.remove(options.id); - this.Events.trigger("debug", `Could not queue ${options.id}`, { - args, - options, - error: e - }); - if (typeof job.cb === "function") { - job.cb(e); - } - return false; - } - if (blocked) { - this._drop(job); - return true; - } else if (reachedHWM) { - shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; - if (shifted != null) { - this._drop(shifted); - } - if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { - if (shifted == null) { - this._drop(job); - } - return reachedHWM; - } - } - this._states.next(job.options.id); // QUEUED - this._queues.push(options.priority, job); - await this._drainAll(); - return reachedHWM; - }); - } + try { + var _ref2 = yield _this2._store.__submit__(_this2.queued(), options.weight); - schedule(...args) { - var options, task, wrapped; - if (typeof args[0] === "function") { - [task, ...args] = args; - options = parser$4.load({}, this.jobDefaults, {}); - } else { - [options, task, ...args] = args; - options = parser$4.load(options, this.jobDefaults); - } - wrapped = (...args) => { - var cb, e, ref, returned; - ref = args, [...args] = ref, [cb] = splice$1.call(args, -1); - returned = (function() { - try { - return task(...args); - } catch (error1) { - e = error1; - return this.Promise.reject(e); - } - }).call(this); - return (!(((returned != null ? returned.then : void 0) != null) && typeof returned.then === "function") ? this.Promise.resolve(returned) : returned).then(function(...args) { - return cb(null, ...args); - }).catch(function(...args) { - return cb(...args); - }); - }; - return new this.Promise((resolve, reject) => { - return this.submit(options, wrapped, ...args, function(...args) { - return (args[0] != null ? reject : (args.shift(), resolve))(...args); - }).catch((e) => { - return this.Events.trigger("error", e); - }); - }); - } + reachedHWM = _ref2.reachedHWM; + blocked = _ref2.blocked; + strategy = _ref2.strategy; + } catch (error1) { + error = error1; - wrap(fn) { - var schedule, wrapped; - schedule = this.schedule; - wrapped = function(...args) { - return schedule(fn.bind(this), ...args); - }; - wrapped.withOptions = (options, ...args) => { - return schedule(options, fn, ...args); - }; - return wrapped; - } + _this2.Events.trigger("debug", `Could not queue ${options.id}`, { + args, + options, + error + }); - async updateSettings(options = {}) { - await this._store.__updateSettings__(parser$4.overwrite(options, this.storeDefaults)); - parser$4.overwrite(options, this.instanceDefaults, this); - return this; - } + job.doDrop({ + error + }); + return false; + } - currentReservoir() { - return this._store.__currentReservoir__(); - } + if (blocked) { + job.doDrop(); + return true; + } else if (reachedHWM) { + shifted = strategy === Bottleneck.prototype.strategy.LEAK ? _this2._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? _this2._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; - incrementReservoir(incr = 0) { - return this._store.__incrementReservoir__(incr); - } + if (shifted != null) { + shifted.doDrop(); + } - } - Bottleneck.default = Bottleneck; + if (shifted == null || strategy === Bottleneck.prototype.strategy.OVERFLOW) { + if (shifted == null) { + job.doDrop(); + } - Bottleneck.Events = Events$4; + return reachedHWM; + } + } - Bottleneck.version = Bottleneck.prototype.version = require$$7.version; + job.doQueue(reachedHWM, blocked); - Bottleneck.strategy = Bottleneck.prototype.strategy = { - LEAK: 1, - OVERFLOW: 2, - OVERFLOW_PRIORITY: 4, - BLOCK: 3 - }; + _this2._queues.push(job); - Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; + yield _this2._drainAll(); + return reachedHWM; + })(); + } - Bottleneck.Group = Bottleneck.prototype.Group = Group_1; + _receive(job) { + if (this._states.jobStatus(job.options.id) != null) { + job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); - Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; + return false; + } else { + job.doReceive(); + return this._submitLock.schedule(this._addToQueue, job); + } + } - Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; + submit(...args) { + var cb, fn, job, options, ref, ref1, task; - Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; + if (typeof args[0] === "function") { + var _ref3, _ref4, _splice$call, _splice$call2; - Bottleneck.prototype.jobDefaults = { - priority: DEFAULT_PRIORITY, - weight: 1, - expiration: null, - id: "" - }; + ref = args, (_ref3 = ref, _ref4 = _toArray(_ref3), fn = _ref4[0], args = _ref4.slice(1), _ref3), (_splice$call = splice.call(args, -1), _splice$call2 = _slicedToArray(_splice$call, 1), cb = _splice$call2[0], _splice$call); + options = parser.load({}, this.jobDefaults); + } else { + var _ref5, _ref6, _splice$call3, _splice$call4; - Bottleneck.prototype.storeDefaults = { - maxConcurrent: null, - minTime: 0, - highWater: null, - strategy: Bottleneck.prototype.strategy.LEAK, - penalty: null, - reservoir: null, - reservoirRefreshInterval: null, - reservoirRefreshAmount: null - }; + ref1 = args, (_ref5 = ref1, _ref6 = _toArray(_ref5), options = _ref6[0], fn = _ref6[1], args = _ref6.slice(2), _ref5), (_splice$call3 = splice.call(args, -1), _splice$call4 = _slicedToArray(_splice$call3, 1), cb = _splice$call4[0], _splice$call3); + options = parser.load(options, this.jobDefaults); + } - Bottleneck.prototype.localStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 250 - }; + task = (...args) => { + return new this.Promise(function (resolve, reject) { + return fn(...args, function (...args) { + return (args[0] != null ? reject : resolve)(args); + }); + }); + }; - Bottleneck.prototype.redisStoreDefaults = { - Promise: Promise, - timeout: null, - heartbeatInterval: 5000, - clientTimeout: 10000, - clientOptions: {}, - clusterNodes: null, - clearDatastore: false, - connection: null - }; + job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + job.promise.then(function (args) { + return typeof cb === "function" ? cb(...args) : void 0; + }).catch(function (args) { + if (Array.isArray(args)) { + return typeof cb === "function" ? cb(...args) : void 0; + } else { + return typeof cb === "function" ? cb(args) : void 0; + } + }); + return this._receive(job); + } - Bottleneck.prototype.instanceDefaults = { - datastore: "local", - connection: null, - id: "", - rejectOnDrop: true, - trackDoneStatus: false, - Promise: Promise - }; + schedule(...args) { + var job, options, task; - Bottleneck.prototype.stopDefaults = { - enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", - dropWaitingJobs: true, - dropErrorMessage: "This limiter has been stopped." - }; + if (typeof args[0] === "function") { + var _args = args; - return Bottleneck; + var _args2 = _toArray(_args); - }).call(commonjsGlobal); + task = _args2[0]; + args = _args2.slice(1); + options = {}; + } else { + var _args3 = args; - var Bottleneck_1 = Bottleneck; + var _args4 = _toArray(_args3); - var lib = Bottleneck_1; + options = _args4[0]; + task = _args4[1]; + args = _args4.slice(2); + } - return lib; + job = new Job(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); -}))); + this._receive(job); + return job.promise; + } -/***/ }), + wrap(fn) { + var schedule, wrapped; + schedule = this.schedule.bind(this); -/***/ 9239: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + wrapped = function wrapped(...args) { + return schedule(fn.bind(this), ...args); + }; -"use strict"; -/*jshint node:true */ + wrapped.withOptions = function (options, ...args) { + return schedule(options, fn, ...args); + }; -var Buffer = __nccwpck_require__(64293).Buffer; // browserify -var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; + return wrapped; + } -module.exports = bufferEq; + updateSettings(options = {}) { + var _this3 = this; -function bufferEq(a, b) { + return _asyncToGenerator(function* () { + yield _this3._store.__updateSettings__(parser.overwrite(options, _this3.storeDefaults)); + parser.overwrite(options, _this3.instanceDefaults, _this3); + return _this3; + })(); + } - // shortcutting on type is necessary for correctness - if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { - return false; - } + currentReservoir() { + return this._store.__currentReservoir__(); + } - // buffer sizes should be well-known information, so despite this - // shortcutting, it doesn't leak any information about the *contents* of the - // buffers. - if (a.length !== b.length) { - return false; - } + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } - var c = 0; - for (var i = 0; i < a.length; i++) { - /*jshint bitwise:false */ - c |= a[i] ^ b[i]; // XOR } - return c === 0; -} -bufferEq.install = function() { - Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { - return bufferEq(this, that); + ; + Bottleneck.default = Bottleneck; + Bottleneck.Events = Events; + Bottleneck.version = Bottleneck.prototype.version = __nccwpck_require__(18372)/* .version */ .i; + Bottleneck.strategy = Bottleneck.prototype.strategy = { + LEAK: 1, + OVERFLOW: 2, + OVERFLOW_PRIORITY: 4, + BLOCK: 3 }; -}; - -var origBufEqual = Buffer.prototype.equal; -var origSlowBufEqual = SlowBuffer.prototype.equal; -bufferEq.restore = function() { - Buffer.prototype.equal = origBufEqual; - SlowBuffer.prototype.equal = origSlowBufEqual; -}; + Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = __nccwpck_require__(93529); + Bottleneck.Group = Bottleneck.prototype.Group = __nccwpck_require__(53068); + Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = __nccwpck_require__(29992); + Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = __nccwpck_require__(47710); + Bottleneck.Batcher = Bottleneck.prototype.Batcher = __nccwpck_require__(85442); + Bottleneck.prototype.jobDefaults = { + priority: DEFAULT_PRIORITY, + weight: 1, + expiration: null, + id: "" + }; + Bottleneck.prototype.storeDefaults = { + maxConcurrent: null, + minTime: 0, + highWater: null, + strategy: Bottleneck.prototype.strategy.LEAK, + penalty: null, + reservoir: null, + reservoirRefreshInterval: null, + reservoirRefreshAmount: null, + reservoirIncreaseInterval: null, + reservoirIncreaseAmount: null, + reservoirIncreaseMaximum: null + }; + Bottleneck.prototype.localStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 250 + }; + Bottleneck.prototype.redisStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 5000, + clientTimeout: 10000, + Redis: null, + clientOptions: {}, + clusterNodes: null, + clearDatastore: false, + connection: null + }; + Bottleneck.prototype.instanceDefaults = { + datastore: "local", + connection: null, + id: "", + rejectOnDrop: true, + trackDoneStatus: false, + Promise: Promise + }; + Bottleneck.prototype.stopDefaults = { + enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", + dropWaitingJobs: true, + dropErrorMessage: "This limiter has been stopped." + }; + return Bottleneck; +}.call(void 0); +module.exports = Bottleneck; /***/ }), -/***/ 86966: +/***/ 93529: /***/ ((module) => { "use strict"; -/*! - * bytes - * Copyright(c) 2012-2014 TJ Holowaychuk - * Copyright(c) 2015 Jed Watson - * MIT Licensed - */ +var BottleneckError; +BottleneckError = class BottleneckError extends Error {}; +module.exports = BottleneckError; -/** - * Module exports. - * @public - */ +/***/ }), -module.exports = bytes; -module.exports.format = format; -module.exports.parse = parse; +/***/ 38579: +/***/ ((module) => { -/** - * Module variables. - * @private - */ +"use strict"; -var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; -var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; +var DLList; +DLList = class DLList { + constructor(incr, decr) { + this.incr = incr; + this.decr = decr; + this._first = null; + this._last = null; + this.length = 0; + } -var map = { - b: 1, - kb: 1 << 10, - mb: 1 << 20, - gb: 1 << 30, - tb: Math.pow(1024, 4), - pb: Math.pow(1024, 5), -}; + push(value) { + var node; + this.length++; -var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; + if (typeof this.incr === "function") { + this.incr(); + } -/** - * Convert the given value in bytes into a string or parse to string to an integer in bytes. - * - * @param {string|number} value - * @param {{ - * case: [string], - * decimalPlaces: [number] - * fixedDecimals: [boolean] - * thousandsSeparator: [string] - * unitSeparator: [string] - * }} [options] bytes options. - * - * @returns {string|number|null} - */ + node = { + value, + prev: this._last, + next: null + }; -function bytes(value, options) { - if (typeof value === 'string') { - return parse(value); - } + if (this._last != null) { + this._last.next = node; + this._last = node; + } else { + this._first = this._last = node; + } - if (typeof value === 'number') { - return format(value, options); + return void 0; } - return null; -} + shift() { + var value; -/** - * Format the given value in bytes into a string. - * - * If the value is negative, it is kept as such. If it is a float, - * it is rounded. - * - * @param {number} value - * @param {object} [options] - * @param {number} [options.decimalPlaces=2] - * @param {number} [options.fixedDecimals=false] - * @param {string} [options.thousandsSeparator=] - * @param {string} [options.unit=] - * @param {string} [options.unitSeparator=] - * - * @returns {string|null} - * @public - */ + if (this._first == null) { + return; + } else { + this.length--; -function format(value, options) { - if (!Number.isFinite(value)) { - return null; - } + if (typeof this.decr === "function") { + this.decr(); + } + } - var mag = Math.abs(value); - var thousandsSeparator = (options && options.thousandsSeparator) || ''; - var unitSeparator = (options && options.unitSeparator) || ''; - var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; - var fixedDecimals = Boolean(options && options.fixedDecimals); - var unit = (options && options.unit) || ''; + value = this._first.value; - if (!unit || !map[unit.toLowerCase()]) { - if (mag >= map.pb) { - unit = 'PB'; - } else if (mag >= map.tb) { - unit = 'TB'; - } else if (mag >= map.gb) { - unit = 'GB'; - } else if (mag >= map.mb) { - unit = 'MB'; - } else if (mag >= map.kb) { - unit = 'KB'; + if ((this._first = this._first.next) != null) { + this._first.prev = null; } else { - unit = 'B'; + this._last = null; } - } - - var val = value / map[unit.toLowerCase()]; - var str = val.toFixed(decimalPlaces); - if (!fixedDecimals) { - str = str.replace(formatDecimalsRegExp, '$1'); + return value; } - if (thousandsSeparator) { - str = str.replace(formatThousandsRegExp, thousandsSeparator); + first() { + if (this._first != null) { + return this._first.value; + } } - return str + unitSeparator + unit; -} + getArray() { + var node, ref, results; + node = this._first; + results = []; -/** - * Parse the string value into an integer in bytes. - * - * If no unit is given, it is assumed the value is in bytes. - * - * @param {number|string} val - * - * @returns {number|null} - * @public - */ + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } -function parse(val) { - if (typeof val === 'number' && !isNaN(val)) { - return val; + return results; } - if (typeof val !== 'string') { - return null; - } + forEachShift(cb) { + var node; + node = this.shift(); - // Test if the string passed is valid - var results = parseRegExp.exec(val); - var floatValue; - var unit = 'b'; + while (node != null) { + cb(node), node = this.shift(); + } - if (!results) { - // Nothing could be extracted from the given string - floatValue = parseInt(val, 10); - unit = 'b' - } else { - // Retrieve the value and the unit - floatValue = parseFloat(results[1]); - unit = results[4].toLowerCase(); + return void 0; } - return Math.floor(map[unit] * floatValue); -} + debug() { + var node, ref, ref1, ref2, results; + node = this._first; + results = []; + + while (node != null) { + results.push((ref = node, node = node.next, { + value: ref.value, + prev: (ref1 = ref.prev) != null ? ref1.value : void 0, + next: (ref2 = ref.next) != null ? ref2.value : void 0 + })); + } + + return results; + } +}; +module.exports = DLList; /***/ }), -/***/ 78818: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 107: +/***/ ((module) => { "use strict"; -const ansiStyles = __nccwpck_require__(52068); -const {stdout: stdoutColor, stderr: stderrColor} = __nccwpck_require__(59318); -const { - stringReplaceAll, - stringEncaseCRLFWithFirstIndex -} = __nccwpck_require__(82415); - -const {isArray} = Array; - -// `supportsColor.level` → `ansiStyles.color[name]` mapping -const levelMapping = [ - 'ansi', - 'ansi', - 'ansi256', - 'ansi16m' -]; -const styles = Object.create(null); +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -const applyOptions = (object, options = {}) => { - if (options.level && !(Number.isInteger(options.level) && options.level >= 0 && options.level <= 3)) { - throw new Error('The `level` option should be an integer from 0 to 3'); - } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - // Detect level if not set manually - const colorLevel = stdoutColor ? stdoutColor.level : 0; - object.level = options.level === undefined ? colorLevel : options.level; -}; +var Events; +Events = class Events { + constructor(instance) { + this.instance = instance; + this._events = {}; -class ChalkClass { - constructor(options) { - // eslint-disable-next-line no-constructor-return - return chalkFactory(options); - } -} + if (this.instance.on != null || this.instance.once != null || this.instance.removeAllListeners != null) { + throw new Error("An Emitter already exists for this object"); + } -const chalkFactory = options => { - const chalk = {}; - applyOptions(chalk, options); + this.instance.on = (name, cb) => { + return this._addListener(name, "many", cb); + }; - chalk.template = (...arguments_) => chalkTag(chalk.template, ...arguments_); + this.instance.once = (name, cb) => { + return this._addListener(name, "once", cb); + }; - Object.setPrototypeOf(chalk, Chalk.prototype); - Object.setPrototypeOf(chalk.template, chalk); + this.instance.removeAllListeners = (name = null) => { + if (name != null) { + return delete this._events[name]; + } else { + return this._events = {}; + } + }; + } - chalk.template.constructor = () => { - throw new Error('`chalk.constructor()` is deprecated. Use `new chalk.Instance()` instead.'); - }; + _addListener(name, status, cb) { + var base; - chalk.template.Instance = ChalkClass; + if ((base = this._events)[name] == null) { + base[name] = []; + } - return chalk.template; -}; + this._events[name].push({ + cb, + status + }); -function Chalk(options) { - return chalkFactory(options); -} + return this.instance; + } -for (const [styleName, style] of Object.entries(ansiStyles)) { - styles[styleName] = { - get() { - const builder = createBuilder(this, createStyler(style.open, style.close, this._styler), this._isEmpty); - Object.defineProperty(this, styleName, {value: builder}); - return builder; - } - }; -} + listenerCount(name) { + if (this._events[name] != null) { + return this._events[name].length; + } else { + return 0; + } + } -styles.visible = { - get() { - const builder = createBuilder(this, this._styler, true); - Object.defineProperty(this, 'visible', {value: builder}); - return builder; - } -}; + trigger(name, ...args) { + var _this = this; -const usedModels = ['rgb', 'hex', 'keyword', 'hsl', 'hsv', 'hwb', 'ansi', 'ansi256']; + return _asyncToGenerator(function* () { + var e, promises; -for (const model of usedModels) { - styles[model] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(ansiStyles.color[levelMapping[level]][model](...arguments_), ansiStyles.color.close, this._styler); - return createBuilder(this, styler, this._isEmpty); - }; - } - }; -} + try { + if (name !== "debug") { + _this.trigger("debug", `Event triggered: ${name}`, args); + } -for (const model of usedModels) { - const bgModel = 'bg' + model[0].toUpperCase() + model.slice(1); - styles[bgModel] = { - get() { - const {level} = this; - return function (...arguments_) { - const styler = createStyler(ansiStyles.bgColor[levelMapping[level]][model](...arguments_), ansiStyles.bgColor.close, this._styler); - return createBuilder(this, styler, this._isEmpty); - }; - } - }; -} + if (_this._events[name] == null) { + return; + } -const proto = Object.defineProperties(() => {}, { - ...styles, - level: { - enumerable: true, - get() { - return this._generator.level; - }, - set(level) { - this._generator.level = level; - } - } -}); + _this._events[name] = _this._events[name].filter(function (listener) { + return listener.status !== "none"; + }); + promises = _this._events[name].map( + /*#__PURE__*/ + function () { + var _ref = _asyncToGenerator(function* (listener) { + var e, returned; + + if (listener.status === "none") { + return; + } + + if (listener.status === "once") { + listener.status = "none"; + } + + try { + returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; + + if (typeof (returned != null ? returned.then : void 0) === "function") { + return yield returned; + } else { + return returned; + } + } catch (error) { + e = error; + + if (true) { + _this.trigger("error", e); + } + + return null; + } + }); + + return function (_x) { + return _ref.apply(this, arguments); + }; + }()); + return (yield Promise.all(promises)).find(function (x) { + return x != null; + }); + } catch (error) { + e = error; + + if (true) { + _this.trigger("error", e); + } -const createStyler = (open, close, parent) => { - let openAll; - let closeAll; - if (parent === undefined) { - openAll = open; - closeAll = close; - } else { - openAll = parent.openAll + open; - closeAll = close + parent.closeAll; - } + return null; + } + })(); + } - return { - open, - close, - openAll, - closeAll, - parent - }; }; +module.exports = Events; -const createBuilder = (self, _styler, _isEmpty) => { - const builder = (...arguments_) => { - if (isArray(arguments_[0]) && isArray(arguments_[0].raw)) { - // Called as a template literal, for example: chalk.red`2 + 3 = {bold ${2+3}}` - return applyStyle(builder, chalkTag(builder, ...arguments_)); - } - - // Single argument is hot path, implicit coercion is faster than anything - // eslint-disable-next-line no-implicit-coercion - return applyStyle(builder, (arguments_.length === 1) ? ('' + arguments_[0]) : arguments_.join(' ')); - }; +/***/ }), - // We alter the prototype because we must return a function, but there is - // no way to create a function with a different prototype - Object.setPrototypeOf(builder, proto); +/***/ 53068: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - builder._generator = self; - builder._styler = _styler; - builder._isEmpty = _isEmpty; +"use strict"; - return builder; -}; -const applyStyle = (self, string) => { - if (self.level <= 0 || !string) { - return self._isEmpty ? '' : string; - } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } - let styler = self._styler; +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } - if (styler === undefined) { - return string; - } +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } - const {openAll, closeAll} = styler; - if (string.indexOf('\u001B') !== -1) { - while (styler !== undefined) { - // Replace any instances already present with a re-opening code - // otherwise only the part of the string until said closing code - // will be colored, and the rest will simply be 'plain'. - string = stringReplaceAll(string, styler.close, styler.open); +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - styler = styler.parent; - } - } +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - // We can move both next actions out of loop, because remaining actions in loop won't have - // any/visible effect on parts we add here. Close the styling before a linebreak and reopen - // after next line to fix a bleed issue on macOS: https://github.com/chalk/chalk/pull/92 - const lfIndex = string.indexOf('\n'); - if (lfIndex !== -1) { - string = stringEncaseCRLFWithFirstIndex(string, closeAll, openAll, lfIndex); - } +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - return openAll + string + closeAll; -}; +var Events, Group, IORedisConnection, RedisConnection, Scripts, parser; +parser = __nccwpck_require__(67823); +Events = __nccwpck_require__(107); +RedisConnection = __nccwpck_require__(29992); +IORedisConnection = __nccwpck_require__(47710); +Scripts = __nccwpck_require__(4169); -let template; -const chalkTag = (chalk, ...strings) => { - const [firstString] = strings; +Group = function () { + class Group { + constructor(limiterOptions = {}) { + this.deleteKey = this.deleteKey.bind(this); + this.limiterOptions = limiterOptions; + parser.load(this.limiterOptions, this.defaults, this); + this.Events = new Events(this); + this.instances = {}; + this.Bottleneck = __nccwpck_require__(83911); - if (!isArray(firstString) || !isArray(firstString.raw)) { - // If chalk() was called by itself or with a string, - // return the string itself as a string. - return strings.join(' '); - } + this._startAutoCleanup(); - const arguments_ = strings.slice(1); - const parts = [firstString.raw[0]]; + this.sharedConnection = this.connection != null; - for (let i = 1; i < firstString.length; i++) { - parts.push( - String(arguments_[i - 1]).replace(/[{}\\]/g, '\\$&'), - String(firstString.raw[i]) - ); - } + if (this.connection == null) { + if (this.limiterOptions.datastore === "redis") { + this.connection = new RedisConnection(Object.assign({}, this.limiterOptions, { + Events: this.Events + })); + } else if (this.limiterOptions.datastore === "ioredis") { + this.connection = new IORedisConnection(Object.assign({}, this.limiterOptions, { + Events: this.Events + })); + } + } + } - if (template === undefined) { - template = __nccwpck_require__(20500); - } + key(key = "") { + var ref; + return (ref = this.instances[key]) != null ? ref : (() => { + var limiter; + limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { + id: `${this.id}-${key}`, + timeout: this.timeout, + connection: this.connection + })); + this.Events.trigger("created", limiter, key); + return limiter; + })(); + } - return template(chalk, parts.join('')); -}; + deleteKey(key = "") { + var _this = this; -Object.defineProperties(Chalk.prototype, styles); + return _asyncToGenerator(function* () { + var deleted, instance; + instance = _this.instances[key]; -const chalk = Chalk(); // eslint-disable-line new-cap -chalk.supportsColor = stdoutColor; -chalk.stderr = Chalk({level: stderrColor ? stderrColor.level : 0}); // eslint-disable-line new-cap -chalk.stderr.supportsColor = stderrColor; + if (_this.connection) { + deleted = yield _this.connection.__runCommand__(['del', ...Scripts.allKeys(`${_this.id}-${key}`)]); + } -module.exports = chalk; + if (instance != null) { + delete _this.instances[key]; + yield instance.disconnect(); + } + return instance != null || deleted > 0; + })(); + } -/***/ }), + limiters() { + var k, ref, results, v; + ref = this.instances; + results = []; -/***/ 20500: -/***/ ((module) => { + for (k in ref) { + v = ref[k]; + results.push({ + key: k, + limiter: v + }); + } -"use strict"; + return results; + } -const TEMPLATE_REGEX = /(?:\\(u(?:[a-f\d]{4}|\{[a-f\d]{1,6}\})|x[a-f\d]{2}|.))|(?:\{(~)?(\w+(?:\([^)]*\))?(?:\.\w+(?:\([^)]*\))?)*)(?:[ \t]|(?=\r?\n)))|(\})|((?:.|[\r\n\f])+?)/gi; -const STYLE_REGEX = /(?:^|\.)(\w+)(?:\(([^)]*)\))?/g; -const STRING_REGEX = /^(['"])((?:\\.|(?!\1)[^\\])*)\1$/; -const ESCAPE_REGEX = /\\(u(?:[a-f\d]{4}|{[a-f\d]{1,6}})|x[a-f\d]{2}|.)|([^\\])/gi; + keys() { + return Object.keys(this.instances); + } -const ESCAPES = new Map([ - ['n', '\n'], - ['r', '\r'], - ['t', '\t'], - ['b', '\b'], - ['f', '\f'], - ['v', '\v'], - ['0', '\0'], - ['\\', '\\'], - ['e', '\u001B'], - ['a', '\u0007'] -]); + clusterKeys() { + var _this2 = this; -function unescape(c) { - const u = c[0] === 'u'; - const bracket = c[1] === '{'; + return _asyncToGenerator(function* () { + var cursor, end, found, i, k, keys, len, next, start; - if ((u && !bracket && c.length === 5) || (c[0] === 'x' && c.length === 3)) { - return String.fromCharCode(parseInt(c.slice(1), 16)); - } + if (_this2.connection == null) { + return _this2.Promise.resolve(_this2.keys()); + } - if (u && bracket) { - return String.fromCodePoint(parseInt(c.slice(2, -1), 16)); - } + keys = []; + cursor = null; + start = `b_${_this2.id}-`.length; + end = "_settings".length; - return ESCAPES.get(c) || c; -} + while (cursor !== 0) { + var _ref = yield _this2.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${_this2.id}-*_settings`, "count", 10000]); -function parseArguments(name, arguments_) { - const results = []; - const chunks = arguments_.trim().split(/\s*,\s*/g); - let matches; + var _ref2 = _slicedToArray(_ref, 2); - for (const chunk of chunks) { - const number = Number(chunk); - if (!Number.isNaN(number)) { - results.push(number); - } else if ((matches = chunk.match(STRING_REGEX))) { - results.push(matches[2].replace(ESCAPE_REGEX, (m, escape, character) => escape ? unescape(escape) : character)); - } else { - throw new Error(`Invalid Chalk template style argument: ${chunk} (in style '${name}')`); - } - } + next = _ref2[0]; + found = _ref2[1]; + cursor = ~~next; - return results; -} + for (i = 0, len = found.length; i < len; i++) { + k = found[i]; + keys.push(k.slice(start, -end)); + } + } -function parseStyle(style) { - STYLE_REGEX.lastIndex = 0; + return keys; + })(); + } - const results = []; - let matches; + _startAutoCleanup() { + var _this3 = this; - while ((matches = STYLE_REGEX.exec(style)) !== null) { - const name = matches[1]; + var base; + clearInterval(this.interval); + return typeof (base = this.interval = setInterval( + /*#__PURE__*/ + _asyncToGenerator(function* () { + var e, k, ref, results, time, v; + time = Date.now(); + ref = _this3.instances; + results = []; - if (matches[2]) { - const args = parseArguments(name, matches[2]); - results.push([name].concat(args)); - } else { - results.push([name]); - } - } + for (k in ref) { + v = ref[k]; - return results; -} + try { + if (yield v._store.__groupCheck__(time)) { + results.push(_this3.deleteKey(k)); + } else { + results.push(void 0); + } + } catch (error) { + e = error; + results.push(v.Events.trigger("error", e)); + } + } -function buildStyle(chalk, styles) { - const enabled = {}; + return results; + }), this.timeout / 2)).unref === "function" ? base.unref() : void 0; + } - for (const layer of styles) { - for (const style of layer.styles) { - enabled[style[0]] = layer.inverse ? null : style.slice(1); - } - } + updateSettings(options = {}) { + parser.overwrite(options, this.defaults, this); + parser.overwrite(options, options, this.limiterOptions); - let current = chalk; - for (const [styleName, styles] of Object.entries(enabled)) { - if (!Array.isArray(styles)) { - continue; - } + if (options.timeout != null) { + return this._startAutoCleanup(); + } + } - if (!(styleName in current)) { - throw new Error(`Unknown Chalk style: ${styleName}`); - } + disconnect(flush = true) { + var ref; - current = styles.length > 0 ? current[styleName](...styles) : current[styleName]; - } + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; + } + } - return current; -} - -module.exports = (chalk, temporary) => { - const styles = []; - const chunks = []; - let chunk = []; - - // eslint-disable-next-line max-params - temporary.replace(TEMPLATE_REGEX, (m, escapeCharacter, inverse, style, close, character) => { - if (escapeCharacter) { - chunk.push(unescape(escapeCharacter)); - } else if (style) { - const string = chunk.join(''); - chunk = []; - chunks.push(styles.length === 0 ? string : buildStyle(chalk, styles)(string)); - styles.push({inverse, styles: parseStyle(style)}); - } else if (close) { - if (styles.length === 0) { - throw new Error('Found extraneous } in Chalk template literal'); - } + } - chunks.push(buildStyle(chalk, styles)(chunk.join(''))); - chunk = []; - styles.pop(); - } else { - chunk.push(character); - } - }); + ; + Group.prototype.defaults = { + timeout: 1000 * 60 * 5, + connection: null, + Promise: Promise, + id: "group-key" + }; + return Group; +}.call(void 0); - chunks.push(chunk.join('')); +module.exports = Group; - if (styles.length > 0) { - const errMessage = `Chalk template literal is missing ${styles.length} closing bracket${styles.length === 1 ? '' : 's'} (\`}\`)`; - throw new Error(errMessage); - } +/***/ }), - return chunks.join(''); -}; +/***/ 47710: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +"use strict"; -/***/ }), -/***/ 82415: -/***/ ((module) => { +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } -"use strict"; +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } -const stringReplaceAll = (string, substring, replacer) => { - let index = string.indexOf(substring); - if (index === -1) { - return string; - } +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - const substringLength = substring.length; - let endIndex = 0; - let returnValue = ''; - do { - returnValue += string.substr(endIndex, index - endIndex) + substring + replacer; - endIndex = index + substringLength; - index = string.indexOf(substring, endIndex); - } while (index !== -1); +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - returnValue += string.substr(endIndex); - return returnValue; -}; +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -const stringEncaseCRLFWithFirstIndex = (string, prefix, postfix, index) => { - let endIndex = 0; - let returnValue = ''; - do { - const gotCR = string[index - 1] === '\r'; - returnValue += string.substr(endIndex, (gotCR ? index - 1 : index) - endIndex) + prefix + (gotCR ? '\r\n' : '\n') + postfix; - endIndex = index + 1; - index = string.indexOf('\n', endIndex); - } while (index !== -1); +var Events, IORedisConnection, Scripts, parser; +parser = __nccwpck_require__(67823); +Events = __nccwpck_require__(107); +Scripts = __nccwpck_require__(4169); - returnValue += string.substr(endIndex); - return returnValue; -}; +IORedisConnection = function () { + class IORedisConnection { + constructor(options = {}) { + parser.load(options, this.defaults, this); -module.exports = { - stringReplaceAll, - stringEncaseCRLFWithFirstIndex -}; + if (this.Redis == null) { + this.Redis = eval("require")("ioredis"); // Obfuscated or else Webpack/Angular will try to inline the optional ioredis module. To override this behavior: pass the ioredis module to Bottleneck as the 'Redis' option. + } + if (this.Events == null) { + this.Events = new Events(this); + } -/***/ }), + this.terminated = false; -/***/ 27972: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (this.clusterNodes != null) { + this.client = new this.Redis.Cluster(this.clusterNodes, this.clientOptions); + this.subscriber = new this.Redis.Cluster(this.clusterNodes, this.clientOptions); + } else if (this.client != null && this.client.duplicate == null) { + this.subscriber = new this.Redis.Cluster(this.client.startupNodes, this.client.options); + } else { + if (this.client == null) { + this.client = new this.Redis(this.clientOptions); + } -"use strict"; + this.subscriber = this.client.duplicate(); + } -const os = __nccwpck_require__(12087); + this.limiters = {}; + this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => { + this._loadScripts(); -const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; -const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; -const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); + return { + client: this.client, + subscriber: this.subscriber + }; + }); + } -module.exports = (stack, options) => { - options = Object.assign({pretty: false}, options); + _setup(client, sub) { + client.setMaxListeners(0); + return new this.Promise((resolve, reject) => { + client.on("error", e => { + return this.Events.trigger("error", e); + }); - return stack.replace(/\\/g, '/') - .split('\n') - .filter(line => { - const pathMatches = line.match(extractPathRegex); - if (pathMatches === null || !pathMatches[1]) { - return true; - } + if (sub) { + client.on("message", (channel, message) => { + var ref; + return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; + }); + } - const match = pathMatches[1]; + if (client.status === "ready") { + return resolve(); + } else { + return client.once("ready", resolve); + } + }); + } - // Electron - if ( - match.includes('.app/Contents/Resources/electron.asar') || - match.includes('.app/Contents/Resources/default_app.asar') - ) { - return false; - } + _loadScripts() { + return Scripts.names.forEach(name => { + return this.client.defineCommand(name, { + lua: Scripts.payload(name) + }); + }); + } - return !pathRegex.test(match); - }) - .filter(line => line.trim() !== '') - .map(line => { - if (options.pretty) { - return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); - } + __runCommand__(cmd) { + var _this = this; - return line; - }) - .join('\n'); -}; + return _asyncToGenerator(function* () { + var _, deleted; + yield _this.ready; -/***/ }), + var _ref = yield _this.client.pipeline([cmd]).exec(); -/***/ 2101: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var _ref2 = _slicedToArray(_ref, 1); -module.exports = __nccwpck_require__(16136); + var _ref2$ = _slicedToArray(_ref2[0], 2); -/***/ }), + _ = _ref2$[0]; + deleted = _ref2$[1]; + return deleted; + })(); + } -/***/ 66168: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + __addLimiter__(instance) { + return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => { + return new this.Promise((resolve, reject) => { + return this.subscriber.subscribe(channel, () => { + this.limiters[channel] = instance; + return resolve(); + }); + }); + })); + } -const utils = __nccwpck_require__(98911); + __removeLimiter__(instance) { + var _this2 = this; -class Cell { - /** - * A representation of a cell within the table. - * Implementations must have `init` and `draw` methods, - * as well as `colSpan`, `rowSpan`, `desiredHeight` and `desiredWidth` properties. - * @param options - * @constructor - */ - constructor(options) { - this.setOptions(options); + return [instance.channel(), instance.channel_client()].forEach( + /*#__PURE__*/ + function () { + var _ref3 = _asyncToGenerator(function* (channel) { + if (!_this2.terminated) { + yield _this2.subscriber.unsubscribe(channel); + } - /** - * Each cell will have it's `x` and `y` values set by the `layout-manager` prior to - * `init` being called; - * @type {Number} - */ - this.x = null; - this.y = null; - } + return delete _this2.limiters[channel]; + }); - setOptions(options) { - if (['boolean', 'number', 'string'].indexOf(typeof options) !== -1) { - options = { content: '' + options }; + return function (_x) { + return _ref3.apply(this, arguments); + }; + }()); } - options = options || {}; - this.options = options; - let content = options.content; - if (['boolean', 'number', 'string'].indexOf(typeof content) !== -1) { - this.content = String(content); - } else if (!content) { - this.content = ''; - } else { - throw new Error('Content needs to be a primitive, got: ' + typeof content); + + __scriptArgs__(name, id, args, cb) { + var keys; + keys = Scripts.keys(name, id); + return [keys.length].concat(keys, args, cb); } - this.colSpan = options.colSpan || 1; - this.rowSpan = options.rowSpan || 1; - } - mergeTableOptions(tableOptions, cells) { - this.cells = cells; + __scriptFn__(name) { + return this.client[name].bind(this.client); + } - let optionsChars = this.options.chars || {}; - let tableChars = tableOptions.chars; - let chars = (this.chars = {}); - CHAR_NAMES.forEach(function (name) { - setOption(optionsChars, tableChars, name, chars); - }); + disconnect(flush = true) { + var i, k, len, ref; + ref = Object.keys(this.limiters); - this.truncate = this.options.truncate || tableOptions.truncate; + for (i = 0, len = ref.length; i < len; i++) { + k = ref[i]; + clearInterval(this.limiters[k]._store.heartbeat); + } - let style = (this.options.style = this.options.style || {}); - let tableStyle = tableOptions.style; - setOption(style, tableStyle, 'padding-left', this); - setOption(style, tableStyle, 'padding-right', this); - this.head = style.head || tableStyle.head; - this.border = style.border || tableStyle.border; + this.limiters = {}; + this.terminated = true; - let fixedWidth = tableOptions.colWidths[this.x]; - if (tableOptions.wordWrap && fixedWidth) { - fixedWidth -= this.paddingLeft + this.paddingRight; - if (this.colSpan) { - let i = 1; - while (i < this.colSpan) { - fixedWidth += tableOptions.colWidths[this.x + i]; - i++; - } + if (flush) { + return this.Promise.all([this.client.quit(), this.subscriber.quit()]); + } else { + this.client.disconnect(); + this.subscriber.disconnect(); + return this.Promise.resolve(); } - this.lines = utils.colorizeLines(utils.wordWrap(fixedWidth, this.content)); - } else { - this.lines = utils.colorizeLines(this.content.split('\n')); } - this.desiredWidth = utils.strlen(this.content) + this.paddingLeft + this.paddingRight; - this.desiredHeight = this.lines.length; - } - - /** - * Initializes the Cells data structure. - * - * @param tableOptions - A fully populated set of tableOptions. - * In addition to the standard default values, tableOptions must have fully populated the - * `colWidths` and `rowWidths` arrays. Those arrays must have lengths equal to the number - * of columns or rows (respectively) in this table, and each array item must be a Number. - * - */ - init(tableOptions) { - let x = this.x; - let y = this.y; - this.widths = tableOptions.colWidths.slice(x, x + this.colSpan); - this.heights = tableOptions.rowHeights.slice(y, y + this.rowSpan); - this.width = this.widths.reduce(sumPlusOne, -1); - this.height = this.heights.reduce(sumPlusOne, -1); - - this.hAlign = this.options.hAlign || tableOptions.colAligns[x]; - this.vAlign = this.options.vAlign || tableOptions.rowAligns[y]; - - this.drawRight = x + this.colSpan == tableOptions.colWidths.length; } - /** - * Draws the given line of the cell. - * This default implementation defers to methods `drawTop`, `drawBottom`, `drawLine` and `drawEmpty`. - * @param lineNum - can be `top`, `bottom` or a numerical line number. - * @param spanningCell - will be a number if being called from a RowSpanCell, and will represent how - * many rows below it's being called from. Otherwise it's undefined. - * @returns {String} The representation of this line. - */ - draw(lineNum, spanningCell) { - if (lineNum == 'top') return this.drawTop(this.drawRight); - if (lineNum == 'bottom') return this.drawBottom(this.drawRight); - let padLen = Math.max(this.height - this.lines.length, 0); - let padTop; - switch (this.vAlign) { - case 'center': - padTop = Math.ceil(padLen / 2); - break; - case 'bottom': - padTop = padLen; - break; - default: - padTop = 0; - } - if (lineNum < padTop || lineNum >= padTop + this.lines.length) { - return this.drawEmpty(this.drawRight, spanningCell); + ; + IORedisConnection.prototype.datastore = "ioredis"; + IORedisConnection.prototype.defaults = { + Redis: null, + clientOptions: {}, + clusterNodes: null, + client: null, + Promise: Promise, + Events: null + }; + return IORedisConnection; +}.call(void 0); + +module.exports = IORedisConnection; + +/***/ }), + +/***/ 25949: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +var BottleneckError, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser; +NUM_PRIORITIES = 10; +DEFAULT_PRIORITY = 5; +parser = __nccwpck_require__(67823); +BottleneckError = __nccwpck_require__(93529); +Job = class Job { + constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { + this.task = task; + this.args = args; + this.rejectOnDrop = rejectOnDrop; + this.Events = Events; + this._states = _states; + this.Promise = Promise; + this.options = parser.load(options, jobDefaults); + this.options.priority = this._sanitizePriority(this.options.priority); + + if (this.options.id === jobDefaults.id) { + this.options.id = `${this.options.id}-${this._randomIndex()}`; } - let forceTruncation = this.lines.length > this.height && lineNum + 1 >= this.height; - return this.drawLine(lineNum - padTop, this.drawRight, forceTruncation, spanningCell); + + this.promise = new this.Promise((_resolve, _reject) => { + this._resolve = _resolve; + this._reject = _reject; + }); + this.retryCount = 0; } - /** - * Renders the top line of the cell. - * @param drawRight - true if this method should render the right edge of the cell. - * @returns {String} - */ - drawTop(drawRight) { - let content = []; - if (this.cells) { - //TODO: cells should always exist - some tests don't fill it in though - this.widths.forEach(function (width, index) { - content.push(this._topLeftChar(index)); - content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], width)); - }, this); + _sanitizePriority(priority) { + var sProperty; + sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; + + if (sProperty < 0) { + return 0; + } else if (sProperty > NUM_PRIORITIES - 1) { + return NUM_PRIORITIES - 1; } else { - content.push(this._topLeftChar(0)); - content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], this.width)); - } - if (drawRight) { - content.push(this.chars[this.y == 0 ? 'topRight' : 'rightMid']); + return sProperty; } - return this.wrapWithStyleColors('border', content.join('')); } - _topLeftChar(offset) { - let x = this.x + offset; - let leftChar; - if (this.y == 0) { - leftChar = x == 0 ? 'topLeft' : offset == 0 ? 'topMid' : 'top'; - } else { - if (x == 0) { - leftChar = 'leftMid'; - } else { - leftChar = offset == 0 ? 'midMid' : 'bottomMid'; - if (this.cells) { - //TODO: cells should always exist - some tests don't fill it in though - let spanAbove = this.cells[this.y - 1][x] instanceof Cell.ColSpanCell; - if (spanAbove) { - leftChar = offset == 0 ? 'topMid' : 'mid'; - } - if (offset == 0) { - let i = 1; - while (this.cells[this.y][x - i] instanceof Cell.ColSpanCell) { - i++; - } - if (this.cells[this.y][x - i] instanceof Cell.RowSpanCell) { - leftChar = 'leftMid'; - } - } - } - } - } - return this.chars[leftChar]; + _randomIndex() { + return Math.random().toString(36).slice(2); } - wrapWithStyleColors(styleProperty, content) { - if (this[styleProperty] && this[styleProperty].length) { - try { - let colors = __nccwpck_require__(41997); - for (let i = this[styleProperty].length - 1; i >= 0; i--) { - colors = colors[this[styleProperty][i]]; - } - return colors(content); - } catch (e) { - return content; + doDrop({ + error, + message = "This job has been dropped by Bottleneck" + } = {}) { + if (this._states.remove(this.options.id)) { + if (this.rejectOnDrop) { + this._reject(error != null ? error : new BottleneckError(message)); } + + this.Events.trigger("dropped", { + args: this.args, + options: this.options, + task: this.task, + promise: this.promise + }); + return true; } else { - return content; + return false; } } - /** - * Renders a line of text. - * @param lineNum - Which line of text to render. This is not necessarily the line within the cell. - * There may be top-padding above the first line of text. - * @param drawRight - true if this method should render the right edge of the cell. - * @param forceTruncationSymbol - `true` if the rendered text should end with the truncation symbol even - * if the text fits. This is used when the cell is vertically truncated. If `false` the text should - * only include the truncation symbol if the text will not fit horizontally within the cell width. - * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined. - * @returns {String} - */ - drawLine(lineNum, drawRight, forceTruncationSymbol, spanningCell) { - let left = this.chars[this.x == 0 ? 'left' : 'middle']; - if (this.x && spanningCell && this.cells) { - let cellLeft = this.cells[this.y + spanningCell][this.x - 1]; - while (cellLeft instanceof ColSpanCell) { - cellLeft = this.cells[cellLeft.y][cellLeft.x - 1]; - } - if (!(cellLeft instanceof RowSpanCell)) { - left = this.chars['rightMid']; - } + _assertStatus(expected) { + var status; + status = this._states.jobStatus(this.options.id); + + if (!(status === expected || expected === "DONE" && status === null)) { + throw new BottleneckError(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); } - let leftPadding = utils.repeat(' ', this.paddingLeft); - let right = drawRight ? this.chars['right'] : ''; - let rightPadding = utils.repeat(' ', this.paddingRight); - let line = this.lines[lineNum]; - let len = this.width - (this.paddingLeft + this.paddingRight); - if (forceTruncationSymbol) line += this.truncate || '…'; - let content = utils.truncate(line, len, this.truncate); - content = utils.pad(content, len, ' ', this.hAlign); - content = leftPadding + content + rightPadding; - return this.stylizeLine(left, content, right); } - stylizeLine(left, content, right) { - left = this.wrapWithStyleColors('border', left); - right = this.wrapWithStyleColors('border', right); - if (this.y === 0) { - content = this.wrapWithStyleColors('head', content); - } - return left + content + right; + doReceive() { + this._states.start(this.options.id); + + return this.Events.trigger("received", { + args: this.args, + options: this.options + }); } - /** - * Renders the bottom line of the cell. - * @param drawRight - true if this method should render the right edge of the cell. - * @returns {String} - */ - drawBottom(drawRight) { - let left = this.chars[this.x == 0 ? 'bottomLeft' : 'bottomMid']; - let content = utils.repeat(this.chars.bottom, this.width); - let right = drawRight ? this.chars['bottomRight'] : ''; - return this.wrapWithStyleColors('border', left + content + right); + doQueue(reachedHWM, blocked) { + this._assertStatus("RECEIVED"); + + this._states.next(this.options.id); + + return this.Events.trigger("queued", { + args: this.args, + options: this.options, + reachedHWM, + blocked + }); } - /** - * Renders a blank line of text within the cell. Used for top and/or bottom padding. - * @param drawRight - true if this method should render the right edge of the cell. - * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined. - * @returns {String} - */ - drawEmpty(drawRight, spanningCell) { - let left = this.chars[this.x == 0 ? 'left' : 'middle']; - if (this.x && spanningCell && this.cells) { - let cellLeft = this.cells[this.y + spanningCell][this.x - 1]; - while (cellLeft instanceof ColSpanCell) { - cellLeft = this.cells[cellLeft.y][cellLeft.x - 1]; - } - if (!(cellLeft instanceof RowSpanCell)) { - left = this.chars['rightMid']; - } + doRun() { + if (this.retryCount === 0) { + this._assertStatus("QUEUED"); + + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); } - let right = drawRight ? this.chars['right'] : ''; - let content = utils.repeat(' ', this.width); - return this.stylizeLine(left, content, right); + + return this.Events.trigger("scheduled", { + args: this.args, + options: this.options + }); } -} -class ColSpanCell { - /** - * A Cell that doesn't do anything. It just draws empty lines. - * Used as a placeholder in column spanning. - * @constructor - */ - constructor() {} + doExecute(chained, clearGlobalState, run, free) { + var _this = this; - draw() { - return ''; - } + return _asyncToGenerator(function* () { + var error, eventInfo, passed; - init() {} + if (_this.retryCount === 0) { + _this._assertStatus("RUNNING"); - mergeTableOptions() {} -} + _this._states.next(_this.options.id); + } else { + _this._assertStatus("EXECUTING"); + } -class RowSpanCell { - /** - * A placeholder Cell for a Cell that spans multiple rows. - * It delegates rendering to the original cell, but adds the appropriate offset. - * @param originalCell - * @constructor - */ - constructor(originalCell) { - this.originalCell = originalCell; - } + eventInfo = { + args: _this.args, + options: _this.options, + retryCount: _this.retryCount + }; - init(tableOptions) { - let y = this.y; - let originalY = this.originalCell.y; - this.cellOffset = y - originalY; - this.offset = findDimension(tableOptions.rowHeights, originalY, this.cellOffset); + _this.Events.trigger("executing", eventInfo); + + try { + passed = yield chained != null ? chained.schedule(_this.options, _this.task, ..._this.args) : _this.task(..._this.args); + + if (clearGlobalState()) { + _this.doDone(eventInfo); + + yield free(_this.options, eventInfo); + + _this._assertStatus("DONE"); + + return _this._resolve(passed); + } + } catch (error1) { + error = error1; + return _this._onFailure(error, eventInfo, clearGlobalState, run, free); + } + })(); } - draw(lineNum) { - if (lineNum == 'top') { - return this.originalCell.draw(this.offset, this.cellOffset); - } - if (lineNum == 'bottom') { - return this.originalCell.draw('bottom'); + doExpire(clearGlobalState, run, free) { + var error, eventInfo; + + if (this._states.jobStatus(this.options.id === "RUNNING")) { + this._states.next(this.options.id); } - return this.originalCell.draw(this.offset + 1 + lineNum); - } - mergeTableOptions() {} -} + this._assertStatus("EXECUTING"); -// HELPER FUNCTIONS -function setOption(objA, objB, nameB, targetObj) { - let nameA = nameB.split('-'); - if (nameA.length > 1) { - nameA[1] = nameA[1].charAt(0).toUpperCase() + nameA[1].substr(1); - nameA = nameA.join(''); - targetObj[nameA] = objA[nameA] || objA[nameB] || objB[nameA] || objB[nameB]; - } else { - targetObj[nameB] = objA[nameB] || objB[nameB]; + eventInfo = { + args: this.args, + options: this.options, + retryCount: this.retryCount + }; + error = new BottleneckError(`This job timed out after ${this.options.expiration} ms.`); + return this._onFailure(error, eventInfo, clearGlobalState, run, free); } -} -function findDimension(dimensionTable, startingIndex, span) { - let ret = dimensionTable[startingIndex]; - for (let i = 1; i < span; i++) { - ret += 1 + dimensionTable[startingIndex + i]; + _onFailure(error, eventInfo, clearGlobalState, run, free) { + var _this2 = this; + + return _asyncToGenerator(function* () { + var retry, retryAfter; + + if (clearGlobalState()) { + retry = yield _this2.Events.trigger("failed", error, eventInfo); + + if (retry != null) { + retryAfter = ~~retry; + + _this2.Events.trigger("retry", `Retrying ${_this2.options.id} after ${retryAfter} ms`, eventInfo); + + _this2.retryCount++; + return run(retryAfter); + } else { + _this2.doDone(eventInfo); + + yield free(_this2.options, eventInfo); + + _this2._assertStatus("DONE"); + + return _this2._reject(error); + } + } + })(); } - return ret; -} -function sumPlusOne(a, b) { - return a + b + 1; -} + doDone(eventInfo) { + this._assertStatus("EXECUTING"); -let CHAR_NAMES = [ - 'top', - 'top-mid', - 'top-left', - 'top-right', - 'bottom', - 'bottom-mid', - 'bottom-left', - 'bottom-right', - 'left', - 'left-mid', - 'mid', - 'mid-mid', - 'right', - 'right-mid', - 'middle', -]; -module.exports = Cell; -module.exports.ColSpanCell = ColSpanCell; -module.exports.RowSpanCell = RowSpanCell; + this._states.next(this.options.id); + + return this.Events.trigger("done", eventInfo); + } +}; +module.exports = Job; /***/ }), -/***/ 93875: +/***/ 38979: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const objectAssign = __nccwpck_require__(17426); -const Cell = __nccwpck_require__(66168); -const { ColSpanCell, RowSpanCell } = Cell; +"use strict"; -(function () { - function layoutTable(table) { - table.forEach(function (row, rowIndex) { - row.forEach(function (cell, columnIndex) { - cell.y = rowIndex; - cell.x = columnIndex; - for (let y = rowIndex; y >= 0; y--) { - let row2 = table[y]; - let xMax = y === rowIndex ? columnIndex : row2.length; - for (let x = 0; x < xMax; x++) { - let cell2 = row2[x]; - while (cellsConflict(cell, cell2)) { - cell.x++; - } + +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } + +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } + +var BottleneckError, LocalDatastore, parser; +parser = __nccwpck_require__(67823); +BottleneckError = __nccwpck_require__(93529); +LocalDatastore = class LocalDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.clientId = this.instance._randomIndex(); + parser.load(storeInstanceOptions, storeInstanceOptions, this); + this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); + this._running = 0; + this._done = 0; + this._unblockTime = 0; + this.ready = this.Promise.resolve(); + this.clients = {}; + + this._startHeartbeat(); + } + + _startHeartbeat() { + var base; + + if (this.heartbeat == null && (this.storeOptions.reservoirRefreshInterval != null && this.storeOptions.reservoirRefreshAmount != null || this.storeOptions.reservoirIncreaseInterval != null && this.storeOptions.reservoirIncreaseAmount != null)) { + return typeof (base = this.heartbeat = setInterval(() => { + var amount, incr, maximum, now, reservoir; + now = Date.now(); + + if (this.storeOptions.reservoirRefreshInterval != null && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { + this._lastReservoirRefresh = now; + this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; + + this.instance._drainAll(this.computeCapacity()); + } + + if (this.storeOptions.reservoirIncreaseInterval != null && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { + var _this$storeOptions = this.storeOptions; + amount = _this$storeOptions.reservoirIncreaseAmount; + maximum = _this$storeOptions.reservoirIncreaseMaximum; + reservoir = _this$storeOptions.reservoir; + this._lastReservoirIncrease = now; + incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; + + if (incr > 0) { + this.storeOptions.reservoir += incr; + return this.instance._drainAll(this.computeCapacity()); } } - }); - }); + }, this.heartbeatInterval)).unref === "function" ? base.unref() : void 0; + } else { + return clearInterval(this.heartbeat); + } } - function maxWidth(table) { - let mw = 0; - table.forEach(function (row) { - row.forEach(function (cell) { - mw = Math.max(mw, cell.x + (cell.colSpan || 1)); - }); + __publish__(message) { + var _this = this; + + return _asyncToGenerator(function* () { + yield _this.yieldLoop(); + return _this.instance.Events.trigger("message", message.toString()); + })(); + } + + __disconnect__(flush) { + var _this2 = this; + + return _asyncToGenerator(function* () { + yield _this2.yieldLoop(); + clearInterval(_this2.heartbeat); + return _this2.Promise.resolve(); + })(); + } + + yieldLoop(t = 0) { + return new this.Promise(function (resolve, reject) { + return setTimeout(resolve, t); }); - return mw; } - function maxHeight(table) { - return table.length; + computePenalty() { + var ref; + return (ref = this.storeOptions.penalty) != null ? ref : 15 * this.storeOptions.minTime || 5000; } - function cellsConflict(cell1, cell2) { - let yMin1 = cell1.y; - let yMax1 = cell1.y - 1 + (cell1.rowSpan || 1); - let yMin2 = cell2.y; - let yMax2 = cell2.y - 1 + (cell2.rowSpan || 1); - let yConflict = !(yMin1 > yMax2 || yMin2 > yMax1); + __updateSettings__(options) { + var _this3 = this; - let xMin1 = cell1.x; - let xMax1 = cell1.x - 1 + (cell1.colSpan || 1); - let xMin2 = cell2.x; - let xMax2 = cell2.x - 1 + (cell2.colSpan || 1); - let xConflict = !(xMin1 > xMax2 || xMin2 > xMax1); + return _asyncToGenerator(function* () { + yield _this3.yieldLoop(); + parser.overwrite(options, options, _this3.storeOptions); - return yConflict && xConflict; + _this3._startHeartbeat(); + + _this3.instance._drainAll(_this3.computeCapacity()); + + return true; + })(); } - function conflictExists(rows, x, y) { - let i_max = Math.min(rows.length - 1, y); - let cell = { x: x, y: y }; - for (let i = 0; i <= i_max; i++) { - let row = rows[i]; - for (let j = 0; j < row.length; j++) { - if (cellsConflict(cell, row[j])) { - return true; - } - } - } - return false; + __running__() { + var _this4 = this; + + return _asyncToGenerator(function* () { + yield _this4.yieldLoop(); + return _this4._running; + })(); } - function allBlank(rows, y, xMin, xMax) { - for (let x = xMin; x < xMax; x++) { - if (conflictExists(rows, x, y)) { - return false; - } - } - return true; + __queued__() { + var _this5 = this; + + return _asyncToGenerator(function* () { + yield _this5.yieldLoop(); + return _this5.instance.queued(); + })(); } - function addRowSpanCells(table) { - table.forEach(function (row, rowIndex) { - row.forEach(function (cell) { - for (let i = 1; i < cell.rowSpan; i++) { - let rowSpanCell = new RowSpanCell(cell); - rowSpanCell.x = cell.x; - rowSpanCell.y = cell.y + i; - rowSpanCell.colSpan = cell.colSpan; - insertCell(rowSpanCell, table[rowIndex + i]); - } - }); - }); + __done__() { + var _this6 = this; + + return _asyncToGenerator(function* () { + yield _this6.yieldLoop(); + return _this6._done; + })(); } - function addColSpanCells(cellRows) { - for (let rowIndex = cellRows.length - 1; rowIndex >= 0; rowIndex--) { - let cellColumns = cellRows[rowIndex]; - for (let columnIndex = 0; columnIndex < cellColumns.length; columnIndex++) { - let cell = cellColumns[columnIndex]; - for (let k = 1; k < cell.colSpan; k++) { - let colSpanCell = new ColSpanCell(); - colSpanCell.x = cell.x + k; - colSpanCell.y = cell.y; - cellColumns.splice(columnIndex + 1, 0, colSpanCell); - } - } + __groupCheck__(time) { + var _this7 = this; + + return _asyncToGenerator(function* () { + yield _this7.yieldLoop(); + return _this7._nextRequest + _this7.timeout < time; + })(); + } + + computeCapacity() { + var maxConcurrent, reservoir; + var _this$storeOptions2 = this.storeOptions; + maxConcurrent = _this$storeOptions2.maxConcurrent; + reservoir = _this$storeOptions2.reservoir; + + if (maxConcurrent != null && reservoir != null) { + return Math.min(maxConcurrent - this._running, reservoir); + } else if (maxConcurrent != null) { + return maxConcurrent - this._running; + } else if (reservoir != null) { + return reservoir; + } else { + return null; } } - function insertCell(cell, row) { - let x = 0; - while (x < row.length && row[x].x < cell.x) { - x++; - } - row.splice(x, 0, cell); + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return capacity == null || weight <= capacity; + } + + __incrementReservoir__(incr) { + var _this8 = this; + + return _asyncToGenerator(function* () { + var reservoir; + yield _this8.yieldLoop(); + reservoir = _this8.storeOptions.reservoir += incr; + + _this8.instance._drainAll(_this8.computeCapacity()); + + return reservoir; + })(); + } + + __currentReservoir__() { + var _this9 = this; + + return _asyncToGenerator(function* () { + yield _this9.yieldLoop(); + return _this9.storeOptions.reservoir; + })(); + } + + isBlocked(now) { + return this._unblockTime >= now; + } + + check(weight, now) { + return this.conditionsCheck(weight) && this._nextRequest - now <= 0; } - function fillInTable(table) { - let h_max = maxHeight(table); - let w_max = maxWidth(table); - for (let y = 0; y < h_max; y++) { - for (let x = 0; x < w_max; x++) { - if (!conflictExists(table, x, y)) { - let opts = { x: x, y: y, colSpan: 1, rowSpan: 1 }; - x++; - while (x < w_max && !conflictExists(table, x, y)) { - opts.colSpan++; - x++; - } - let y2 = y + 1; - while (y2 < h_max && allBlank(table, y2, opts.x, opts.x + opts.colSpan)) { - opts.rowSpan++; - y2++; - } + __check__(weight) { + var _this10 = this; - let cell = new Cell(opts); - cell.x = opts.x; - cell.y = opts.y; - insertCell(cell, table[y]); - } - } - } + return _asyncToGenerator(function* () { + var now; + yield _this10.yieldLoop(); + now = Date.now(); + return _this10.check(weight, now); + })(); } - function generateCells(rows) { - return rows.map(function (row) { - if (!Array.isArray(row)) { - let key = Object.keys(row)[0]; - row = row[key]; - if (Array.isArray(row)) { - row = row.slice(); - row.unshift(key); - } else { - row = [key, row]; + __register__(index, weight, expiration) { + var _this11 = this; + + return _asyncToGenerator(function* () { + var now, wait; + yield _this11.yieldLoop(); + now = Date.now(); + + if (_this11.conditionsCheck(weight)) { + _this11._running += weight; + + if (_this11.storeOptions.reservoir != null) { + _this11.storeOptions.reservoir -= weight; } + + wait = Math.max(_this11._nextRequest - now, 0); + _this11._nextRequest = now + wait + _this11.storeOptions.minTime; + return { + success: true, + wait, + reservoir: _this11.storeOptions.reservoir + }; + } else { + return { + success: false + }; } - return row.map(function (cell) { - return new Cell(cell); - }); - }); + })(); } - function makeTableLayout(rows) { - let cellRows = generateCells(rows); - layoutTable(cellRows); - fillInTable(cellRows); - addRowSpanCells(cellRows); - addColSpanCells(cellRows); - return cellRows; + strategyIsBlock() { + return this.storeOptions.strategy === 3; } - module.exports = { - makeTableLayout: makeTableLayout, - layoutTable: layoutTable, - addRowSpanCells: addRowSpanCells, - maxWidth: maxWidth, - fillInTable: fillInTable, - computeWidths: makeComputeWidths('colSpan', 'desiredWidth', 'x', 1), - computeHeights: makeComputeWidths('rowSpan', 'desiredHeight', 'y', 1), - }; -})(); + __submit__(queueLength, weight) { + var _this12 = this; -function makeComputeWidths(colSpan, desiredWidth, x, forcedMin) { - return function (vals, table) { - let result = []; - let spanners = []; - table.forEach(function (row) { - row.forEach(function (cell) { - if ((cell[colSpan] || 1) > 1) { - spanners.push(cell); - } else { - result[cell[x]] = Math.max(result[cell[x]] || 0, cell[desiredWidth] || 0, forcedMin); - } - }); - }); + return _asyncToGenerator(function* () { + var blocked, now, reachedHWM; + yield _this12.yieldLoop(); - vals.forEach(function (val, index) { - if (typeof val === 'number') { - result[index] = val; + if (_this12.storeOptions.maxConcurrent != null && weight > _this12.storeOptions.maxConcurrent) { + throw new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${_this12.storeOptions.maxConcurrent}`); } - }); - //spanners.forEach(function(cell){ - for (let k = spanners.length - 1; k >= 0; k--) { - let cell = spanners[k]; - let span = cell[colSpan]; - let col = cell[x]; - let existingWidth = result[col]; - let editableCols = typeof vals[col] === 'number' ? 0 : 1; - for (let i = 1; i < span; i++) { - existingWidth += 1 + result[col + i]; - if (typeof vals[col + i] !== 'number') { - editableCols++; - } - } - if (cell[desiredWidth] > existingWidth) { - let i = 0; - while (editableCols > 0 && cell[desiredWidth] > existingWidth) { - if (typeof vals[col + i] !== 'number') { - let dif = Math.round((cell[desiredWidth] - existingWidth) / editableCols); - existingWidth += dif; - result[col + i] += dif; - editableCols--; - } - i++; - } + now = Date.now(); + reachedHWM = _this12.storeOptions.highWater != null && queueLength === _this12.storeOptions.highWater && !_this12.check(weight, now); + blocked = _this12.strategyIsBlock() && (reachedHWM || _this12.isBlocked(now)); + + if (blocked) { + _this12._unblockTime = now + _this12.computePenalty(); + _this12._nextRequest = _this12._unblockTime + _this12.storeOptions.minTime; + + _this12.instance._dropAllQueued(); } - } - objectAssign(vals, result); - for (let j = 0; j < vals.length; j++) { - vals[j] = Math.max(forcedMin, vals[j] || 0); - } - }; -} + return { + reachedHWM, + blocked, + strategy: _this12.storeOptions.strategy + }; + })(); + } + + __free__(index, weight) { + var _this13 = this; + return _asyncToGenerator(function* () { + yield _this13.yieldLoop(); + _this13._running -= weight; + _this13._done += weight; + + _this13.instance._drainAll(_this13.computeCapacity()); + + return { + running: _this13._running + }; + })(); + } + +}; +module.exports = LocalDatastore; /***/ }), -/***/ 16136: +/***/ 65893: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const utils = __nccwpck_require__(98911); -const tableLayout = __nccwpck_require__(93875); +"use strict"; -class Table extends Array { - constructor(options) { - super(); - this.options = utils.mergeOptions(options); - } +var DLList, Events, Queues; +DLList = __nccwpck_require__(38579); +Events = __nccwpck_require__(107); +Queues = class Queues { + constructor(num_priorities) { + var i; + this.Events = new Events(this); + this._length = 0; - toString() { - let array = this; - let headersPresent = this.options.head && this.options.head.length; - if (headersPresent) { - array = [this.options.head]; - if (this.length) { - array.push.apply(array, this); + this._lists = function () { + var j, ref, results; + results = []; + + for (i = j = 1, ref = num_priorities; 1 <= ref ? j <= ref : j >= ref; i = 1 <= ref ? ++j : --j) { + results.push(new DLList(() => { + return this.incr(); + }, () => { + return this.decr(); + })); } - } else { - this.options.style.head = []; - } - let cells = tableLayout.makeTableLayout(array); + return results; + }.call(this); + } - cells.forEach(function (row) { - row.forEach(function (cell) { - cell.mergeTableOptions(this.options, cells); - }, this); - }, this); + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); + } + } - tableLayout.computeWidths(this.options.colWidths, cells); - tableLayout.computeHeights(this.options.rowHeights, cells); + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); + } + } - cells.forEach(function (row) { - row.forEach(function (cell) { - cell.init(this.options); - }, this); - }, this); + push(job) { + return this._lists[job.options.priority].push(job); + } - let result = []; + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; + } + } - for (let rowIndex = 0; rowIndex < cells.length; rowIndex++) { - let row = cells[rowIndex]; - let heightOfRow = this.options.rowHeights[rowIndex]; + shiftAll(fn) { + return this._lists.forEach(function (list) { + return list.forEachShift(fn); + }); + } - if (rowIndex === 0 || !this.options.style.compact || (rowIndex == 1 && headersPresent)) { - doDraw(row, 'top', result); - } + getFirst(arr = this._lists) { + var j, len, list; - for (let lineNum = 0; lineNum < heightOfRow; lineNum++) { - doDraw(row, lineNum, result); - } + for (j = 0, len = arr.length; j < len; j++) { + list = arr[j]; - if (rowIndex + 1 == cells.length) { - doDraw(row, 'bottom', result); + if (list.length > 0) { + return list; } } - return result.join('\n'); + return []; } - get width() { - let str = this.toString().split('\n'); - return str[0].length; + shiftLastFrom(priority) { + return this.getFirst(this._lists.slice(priority).reverse()).shift(); } -} - -function doDraw(row, lineNum, result) { - let line = []; - row.forEach(function (cell) { - line.push(cell.draw(lineNum)); - }); - let str = line.join(''); - if (str.length) result.push(str); -} - -module.exports = Table; +}; +module.exports = Queues; /***/ }), -/***/ 98911: +/***/ 29992: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -const objectAssign = __nccwpck_require__(17426); -const stringWidth = __nccwpck_require__(42577); +"use strict"; -function codeRegex(capture) { - return capture ? /\u001b\[((?:\d*;){0,5}\d*)m/g : /\u001b\[(?:\d*;){0,5}\d*m/g; -} -function strlen(str) { - let code = codeRegex(); - let stripped = ('' + str).replace(code, ''); - let split = stripped.split('\n'); - return split.reduce(function (memo, s) { - return stringWidth(s) > memo ? stringWidth(s) : memo; - }, 0); -} +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function repeat(str, times) { - return Array(times + 1).join(str); -} +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function pad(str, len, pad, dir) { - let length = strlen(str); - if (len + 1 >= length) { - let padlen = len - length; - switch (dir) { - case 'right': { - str = repeat(pad, padlen) + str; - break; +var Events, RedisConnection, Scripts, parser; +parser = __nccwpck_require__(67823); +Events = __nccwpck_require__(107); +Scripts = __nccwpck_require__(4169); + +RedisConnection = function () { + class RedisConnection { + constructor(options = {}) { + parser.load(options, this.defaults, this); + + if (this.Redis == null) { + this.Redis = eval("require")("redis"); // Obfuscated or else Webpack/Angular will try to inline the optional redis module. To override this behavior: pass the redis module to Bottleneck as the 'Redis' option. } - case 'center': { - let right = Math.ceil(padlen / 2); - let left = padlen - right; - str = repeat(pad, left) + str + repeat(pad, right); - break; + + if (this.Events == null) { + this.Events = new Events(this); } - default: { - str = str + repeat(pad, padlen); - break; + + this.terminated = false; + + if (this.client == null) { + this.client = this.Redis.createClient(this.clientOptions); } + + this.subscriber = this.client.duplicate(); + this.limiters = {}; + this.shas = {}; + this.ready = this.Promise.all([this._setup(this.client, false), this._setup(this.subscriber, true)]).then(() => { + return this._loadScripts(); + }).then(() => { + return { + client: this.client, + subscriber: this.subscriber + }; + }); } - } - return str; -} -let codeCache = {}; + _setup(client, sub) { + client.setMaxListeners(0); + return new this.Promise((resolve, reject) => { + client.on("error", e => { + return this.Events.trigger("error", e); + }); -function addToCodeCache(name, on, off) { - on = '\u001b[' + on + 'm'; - off = '\u001b[' + off + 'm'; - codeCache[on] = { set: name, to: true }; - codeCache[off] = { set: name, to: false }; - codeCache[name] = { on: on, off: off }; -} + if (sub) { + client.on("message", (channel, message) => { + var ref; + return (ref = this.limiters[channel]) != null ? ref._store.onMessage(channel, message) : void 0; + }); + } -//https://github.com/Marak/colors.js/blob/master/lib/styles.js -addToCodeCache('bold', 1, 22); -addToCodeCache('italics', 3, 23); -addToCodeCache('underline', 4, 24); -addToCodeCache('inverse', 7, 27); -addToCodeCache('strikethrough', 9, 29); + if (client.ready) { + return resolve(); + } else { + return client.once("ready", resolve); + } + }); + } -function updateState(state, controlChars) { - let controlCode = controlChars[1] ? parseInt(controlChars[1].split(';')[0]) : 0; - if ((controlCode >= 30 && controlCode <= 39) || (controlCode >= 90 && controlCode <= 97)) { - state.lastForegroundAdded = controlChars[0]; - return; - } - if ((controlCode >= 40 && controlCode <= 49) || (controlCode >= 100 && controlCode <= 107)) { - state.lastBackgroundAdded = controlChars[0]; - return; - } - if (controlCode === 0) { - for (let i in state) { - /* istanbul ignore else */ - if (Object.prototype.hasOwnProperty.call(state, i)) { - delete state[i]; - } + _loadScript(name) { + return new this.Promise((resolve, reject) => { + var payload; + payload = Scripts.payload(name); + return this.client.multi([["script", "load", payload]]).exec((err, replies) => { + if (err != null) { + return reject(err); + } + + this.shas[name] = replies[0]; + return resolve(replies[0]); + }); + }); } - return; - } - let info = codeCache[controlChars[0]]; - if (info) { - state[info.set] = info.to; - } -} -function readState(line) { - let code = codeRegex(true); - let controlChars = code.exec(line); - let state = {}; - while (controlChars !== null) { - updateState(state, controlChars); - controlChars = code.exec(line); - } - return state; -} + _loadScripts() { + return this.Promise.all(Scripts.names.map(k => { + return this._loadScript(k); + })); + } -function unwindState(state, ret) { - let lastBackgroundAdded = state.lastBackgroundAdded; - let lastForegroundAdded = state.lastForegroundAdded; + __runCommand__(cmd) { + var _this = this; + + return _asyncToGenerator(function* () { + yield _this.ready; + return new _this.Promise((resolve, reject) => { + return _this.client.multi([cmd]).exec_atomic(function (err, replies) { + if (err != null) { + return reject(err); + } else { + return resolve(replies[0]); + } + }); + }); + })(); + } + + __addLimiter__(instance) { + return this.Promise.all([instance.channel(), instance.channel_client()].map(channel => { + return new this.Promise((resolve, reject) => { + var handler; + + handler = chan => { + if (chan === channel) { + this.subscriber.removeListener("subscribe", handler); + this.limiters[channel] = instance; + return resolve(); + } + }; + + this.subscriber.on("subscribe", handler); + return this.subscriber.subscribe(channel); + }); + })); + } + + __removeLimiter__(instance) { + var _this2 = this; + + return this.Promise.all([instance.channel(), instance.channel_client()].map( + /*#__PURE__*/ + function () { + var _ref = _asyncToGenerator(function* (channel) { + if (!_this2.terminated) { + yield new _this2.Promise((resolve, reject) => { + return _this2.subscriber.unsubscribe(channel, function (err, chan) { + if (err != null) { + return reject(err); + } + + if (chan === channel) { + return resolve(); + } + }); + }); + } - delete state.lastBackgroundAdded; - delete state.lastForegroundAdded; + return delete _this2.limiters[channel]; + }); - Object.keys(state).forEach(function (key) { - if (state[key]) { - ret += codeCache[key].off; + return function (_x) { + return _ref.apply(this, arguments); + }; + }())); } - }); - if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { - ret += '\u001b[49m'; - } - if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { - ret += '\u001b[39m'; - } + __scriptArgs__(name, id, args, cb) { + var keys; + keys = Scripts.keys(name, id); + return [this.shas[name], keys.length].concat(keys, args, cb); + } - return ret; -} + __scriptFn__(name) { + return this.client.evalsha.bind(this.client); + } -function rewindState(state, ret) { - let lastBackgroundAdded = state.lastBackgroundAdded; - let lastForegroundAdded = state.lastForegroundAdded; + disconnect(flush = true) { + var i, k, len, ref; + ref = Object.keys(this.limiters); - delete state.lastBackgroundAdded; - delete state.lastForegroundAdded; + for (i = 0, len = ref.length; i < len; i++) { + k = ref[i]; + clearInterval(this.limiters[k]._store.heartbeat); + } - Object.keys(state).forEach(function (key) { - if (state[key]) { - ret = codeCache[key].on + ret; + this.limiters = {}; + this.terminated = true; + this.client.end(flush); + this.subscriber.end(flush); + return this.Promise.resolve(); } - }); - if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { - ret = lastBackgroundAdded + ret; - } - if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { - ret = lastForegroundAdded + ret; } - return ret; -} + ; + RedisConnection.prototype.datastore = "redis"; + RedisConnection.prototype.defaults = { + Redis: null, + clientOptions: {}, + client: null, + Promise: Promise, + Events: null + }; + return RedisConnection; +}.call(void 0); -function truncateWidth(str, desiredLength) { - if (str.length === strlen(str)) { - return str.substr(0, desiredLength); - } +module.exports = RedisConnection; - while (strlen(str) > desiredLength) { - str = str.slice(0, -1); - } +/***/ }), - return str; -} +/***/ 4946: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function truncateWidthWithAnsi(str, desiredLength) { - let code = codeRegex(true); - let split = str.split(codeRegex()); - let splitIndex = 0; - let retLen = 0; - let ret = ''; - let myArray; - let state = {}; +"use strict"; - while (retLen < desiredLength) { - myArray = code.exec(str); - let toAdd = split[splitIndex]; - splitIndex++; - if (retLen + strlen(toAdd) > desiredLength) { - toAdd = truncateWidth(toAdd, desiredLength - retLen); - } - ret += toAdd; - retLen += strlen(toAdd); - if (retLen < desiredLength) { - if (!myArray) { - break; - } // full-width chars may cause a whitespace which cannot be filled - ret += myArray[0]; - updateState(state, myArray); - } - } +function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest(); } - return unwindState(state, ret); -} +function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } -function truncate(str, desiredLength, truncateChar) { - truncateChar = truncateChar || '…'; - let lengthOfStr = strlen(str); - if (lengthOfStr <= desiredLength) { - return str; - } - desiredLength -= strlen(truncateChar); +function _iterableToArrayLimit(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } - let ret = truncateWidthWithAnsi(str, desiredLength); +function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; } - return ret + truncateChar; -} +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } -function defaultOptions() { - return { - chars: { - top: '─', - 'top-mid': '┬', - 'top-left': '┌', - 'top-right': '┐', - bottom: '─', - 'bottom-mid': '┴', - 'bottom-left': '└', - 'bottom-right': '┘', - left: '│', - 'left-mid': '├', - mid: '─', - 'mid-mid': '┼', - right: '│', - 'right-mid': '┤', - middle: '│', - }, - truncate: '…', - colWidths: [], - rowHeights: [], - colAligns: [], - rowAligns: [], - style: { - 'padding-left': 1, - 'padding-right': 1, - head: ['red'], - border: ['grey'], - compact: false, - }, - head: [], - }; -} +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } -function mergeOptions(options, defaults) { - options = options || {}; - defaults = defaults || defaultOptions(); - let ret = objectAssign({}, defaults, options); - ret.chars = objectAssign({}, defaults.chars, options.chars); - ret.style = objectAssign({}, defaults.style, options.style); - return ret; -} +var BottleneckError, IORedisConnection, RedisConnection, RedisDatastore, parser; +parser = __nccwpck_require__(67823); +BottleneckError = __nccwpck_require__(93529); +RedisConnection = __nccwpck_require__(29992); +IORedisConnection = __nccwpck_require__(47710); +RedisDatastore = class RedisDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.originalId = this.instance.id; + this.clientId = this.instance._randomIndex(); + parser.load(storeInstanceOptions, storeInstanceOptions, this); + this.clients = {}; + this.capacityPriorityCounters = {}; + this.sharedConnection = this.connection != null; -function wordWrap(maxLength, input) { - let lines = []; - let split = input.split(/(\s+)/g); - let line = []; - let lineLength = 0; - let whitespace; - for (let i = 0; i < split.length; i += 2) { - let word = split[i]; - let newLength = lineLength + strlen(word); - if (lineLength > 0 && whitespace) { - newLength += whitespace.length; + if (this.connection == null) { + this.connection = this.instance.datastore === "redis" ? new RedisConnection({ + Redis: this.Redis, + clientOptions: this.clientOptions, + Promise: this.Promise, + Events: this.instance.Events + }) : this.instance.datastore === "ioredis" ? new IORedisConnection({ + Redis: this.Redis, + clientOptions: this.clientOptions, + clusterNodes: this.clusterNodes, + Promise: this.Promise, + Events: this.instance.Events + }) : void 0; } - if (newLength > maxLength) { - if (lineLength !== 0) { - lines.push(line.join('')); + + this.instance.connection = this.connection; + this.instance.datastore = this.connection.datastore; + this.ready = this.connection.ready.then(clients => { + this.clients = clients; + return this.runScript("init", this.prepareInitSettings(this.clearDatastore)); + }).then(() => { + return this.connection.__addLimiter__(this.instance); + }).then(() => { + return this.runScript("register_client", [this.instance.queued()]); + }).then(() => { + var base; + + if (typeof (base = this.heartbeat = setInterval(() => { + return this.runScript("heartbeat", []).catch(e => { + return this.instance.Events.trigger("error", e); + }); + }, this.heartbeatInterval)).unref === "function") { + base.unref(); } - line = [word]; - lineLength = strlen(word); - } else { - line.push(whitespace || '', word); - lineLength = newLength; - } - whitespace = split[i + 1]; - } - if (lineLength) { - lines.push(line.join('')); - } - return lines; -} -function multiLineWordWrap(maxLength, input) { - let output = []; - input = input.split('\n'); - for (let i = 0; i < input.length; i++) { - output.push.apply(output, wordWrap(maxLength, input[i])); + return this.clients; + }); } - return output; -} -function colorizeLines(input) { - let state = {}; - let output = []; - for (let i = 0; i < input.length; i++) { - let line = rewindState(state, input[i]); - state = readState(line); - let temp = objectAssign({}, state); - output.push(unwindState(temp, line)); + __publish__(message) { + var _this = this; + + return _asyncToGenerator(function* () { + var client; + + var _ref = yield _this.ready; + + client = _ref.client; + return client.publish(_this.instance.channel(), `message:${message.toString()}`); + })(); } - return output; -} -module.exports = { - strlen: strlen, - repeat: repeat, - pad: pad, - truncate: truncate, - mergeOptions: mergeOptions, - wordWrap: multiLineWordWrap, - colorizeLines: colorizeLines, -}; + onMessage(channel, message) { + var _this2 = this; + return _asyncToGenerator(function* () { + var capacity, counter, data, drained, e, newCapacity, pos, priorityClient, rawCapacity, type; -/***/ }), + try { + pos = message.indexOf(":"); + var _ref2 = [message.slice(0, pos), message.slice(pos + 1)]; + type = _ref2[0]; + data = _ref2[1]; -/***/ 48481: -/***/ ((module) => { + if (type === "capacity") { + return yield _this2.instance._drainAll(data.length > 0 ? ~~data : void 0); + } else if (type === "capacity-priority") { + var _data$split = data.split(":"); -/* - * Copyright 2001-2010 Georges Menie (www.menie.org) - * Copyright 2010 Salvatore Sanfilippo (adapted to Redis coding style) - * Copyright 2015 Zihua Li (http://zihua.li) (ported to JavaScript) - * Copyright 2016 Mike Diarmid (http://github.com/salakar) (re-write for performance, ~700% perf inc) - * All rights reserved. - * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions are met: - * - * * Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * * Redistributions in binary form must reproduce the above copyright - * notice, this list of conditions and the following disclaimer in the - * documentation and/or other materials provided with the distribution. - * * Neither the name of the University of California, Berkeley nor the - * names of its contributors may be used to endorse or promote products - * derived from this software without specific prior written permission. - * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY - * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED - * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE - * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY - * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES - * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; - * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND - * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT - * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS - * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. - */ + var _data$split2 = _slicedToArray(_data$split, 3); -/* CRC16 implementation according to CCITT standards. - * - * Note by @antirez: this is actually the XMODEM CRC 16 algorithm, using the - * following parameters: - * - * Name : "XMODEM", also known as "ZMODEM", "CRC-16/ACORN" - * Width : 16 bit - * Poly : 1021 (That is actually x^16 + x^12 + x^5 + 1) - * Initialization : 0000 - * Reflect Input byte : False - * Reflect Output CRC : False - * Xor constant to output CRC : 0000 - * Output for "123456789" : 31C3 - */ + rawCapacity = _data$split2[0]; + priorityClient = _data$split2[1]; + counter = _data$split2[2]; + capacity = rawCapacity.length > 0 ? ~~rawCapacity : void 0; -var lookup = [ - 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, - 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, - 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, - 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, - 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, - 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, - 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, - 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, - 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, - 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, - 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, - 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, - 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, - 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, - 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, - 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, - 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, - 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, - 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, - 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, - 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, - 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, - 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, - 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, - 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, - 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, - 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, - 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, - 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, - 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, - 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, - 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 -]; + if (priorityClient === _this2.clientId) { + drained = yield _this2.instance._drainAll(capacity); + newCapacity = capacity != null ? capacity - (drained || 0) : ""; + return yield _this2.clients.client.publish(_this2.instance.channel(), `capacity-priority:${newCapacity}::${counter}`); + } else if (priorityClient === "") { + clearTimeout(_this2.capacityPriorityCounters[counter]); + delete _this2.capacityPriorityCounters[counter]; + return _this2.instance._drainAll(capacity); + } else { + return _this2.capacityPriorityCounters[counter] = setTimeout( + /*#__PURE__*/ + _asyncToGenerator(function* () { + var e; -/** - * Convert a string to a UTF8 array - faster than via buffer - * @param str - * @returns {Array} - */ -var toUTF8Array = function toUTF8Array(str) { - var char; - var i = 0; - var p = 0; - var utf8 = []; - var len = str.length; + try { + delete _this2.capacityPriorityCounters[counter]; + yield _this2.runScript("blacklist_client", [priorityClient]); + return yield _this2.instance._drainAll(capacity); + } catch (error) { + e = error; + return _this2.instance.Events.trigger("error", e); + } + }), 1000); + } + } else if (type === "message") { + return _this2.instance.Events.trigger("message", data); + } else if (type === "blocked") { + return yield _this2.instance._dropAllQueued(); + } + } catch (error) { + e = error; + return _this2.instance.Events.trigger("error", e); + } + })(); + } - for (; i < len; i++) { - char = str.charCodeAt(i); - if (char < 128) { - utf8[p++] = char; - } else if (char < 2048) { - utf8[p++] = (char >> 6) | 192; - utf8[p++] = (char & 63) | 128; - } else if ( - ((char & 0xFC00) === 0xD800) && (i + 1) < str.length && - ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) { - char = 0x10000 + ((char & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF); - utf8[p++] = (char >> 18) | 240; - utf8[p++] = ((char >> 12) & 63) | 128; - utf8[p++] = ((char >> 6) & 63) | 128; - utf8[p++] = (char & 63) | 128; + __disconnect__(flush) { + clearInterval(this.heartbeat); + + if (this.sharedConnection) { + return this.connection.__removeLimiter__(this.instance); } else { - utf8[p++] = (char >> 12) | 224; - utf8[p++] = ((char >> 6) & 63) | 128; - utf8[p++] = (char & 63) | 128; + return this.connection.disconnect(flush); } } - return utf8; -}; - -/** - * Convert a string into a redis slot hash. - * @param str - * @returns {number} - */ -var generate = module.exports = function generate(str) { - var char; - var i = 0; - var start = -1; - var result = 0; - var resultHash = 0; - var utf8 = typeof str === 'string' ? toUTF8Array(str) : str; - var len = utf8.length; + runScript(name, args) { + var _this3 = this; - while (i < len) { - char = utf8[i++]; - if (start === -1) { - if (char === 0x7B) { - start = i; + return _asyncToGenerator(function* () { + if (!(name === "init" || name === "register_client")) { + yield _this3.ready; } - } else if (char !== 0x7D) { - resultHash = lookup[(char ^ (resultHash >> 8)) & 0xFF] ^ (resultHash << 8); - } else if (i - 1 !== start) { - return resultHash & 0x3FFF; + + return new _this3.Promise((resolve, reject) => { + var all_args, arr; + all_args = [Date.now(), _this3.clientId].concat(args); + + _this3.instance.Events.trigger("debug", `Calling Redis script: ${name}.lua`, all_args); + + arr = _this3.connection.__scriptArgs__(name, _this3.originalId, all_args, function (err, replies) { + if (err != null) { + return reject(err); + } + + return resolve(replies); + }); + return _this3.connection.__scriptFn__(name)(...arr); + }).catch(e => { + if (e.message === "SETTINGS_KEY_NOT_FOUND") { + if (name === "heartbeat") { + return _this3.Promise.resolve(); + } else { + return _this3.runScript("init", _this3.prepareInitSettings(false)).then(() => { + return _this3.runScript(name, args); + }); + } + } else if (e.message === "UNKNOWN_CLIENT") { + return _this3.runScript("register_client", [_this3.instance.queued()]).then(() => { + return _this3.runScript(name, args); + }); + } else { + return _this3.Promise.reject(e); + } + }); + })(); + } + + prepareArray(arr) { + var i, len, results, x; + results = []; + + for (i = 0, len = arr.length; i < len; i++) { + x = arr[i]; + results.push(x != null ? x.toString() : ""); } - result = lookup[(char ^ (result >> 8)) & 0xFF] ^ (result << 8); + return results; } - return result & 0x3FFF; -}; + prepareObject(obj) { + var arr, k, v; + arr = []; -/** - * Convert an array of multiple strings into a redis slot hash. - * Returns -1 if one of the keys is not for the same slot as the others - * @param keys - * @returns {number} - */ -module.exports.generateMulti = function generateMulti(keys) { - var i = 1; - var len = keys.length; - var base = generate(keys[0]); + for (k in obj) { + v = obj[k]; + arr.push(k, v != null ? v.toString() : ""); + } - while (i < len) { - if (generate(keys[i++]) !== base) return -1; + return arr; } - return base; -}; + prepareInitSettings(clear) { + var args; + args = this.prepareObject(Object.assign({}, this.storeOptions, { + id: this.originalId, + version: this.instance.version, + groupTimeout: this.timeout, + clientTimeout: this.clientTimeout + })); + args.unshift(clear ? 1 : 0, this.instance.version); + return args; + } + convertBool(b) { + return !!b; + } -/***/ }), + __updateSettings__(options) { + var _this4 = this; -/***/ 97391: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return _asyncToGenerator(function* () { + yield _this4.runScript("update_settings", _this4.prepareObject(options)); + return parser.overwrite(options, options, _this4.storeOptions); + })(); + } -/* MIT license */ -/* eslint-disable no-mixed-operators */ -const cssKeywords = __nccwpck_require__(78510); - -// NOTE: conversions should only return primitive values (i.e. arrays, or -// values that give correct `typeof` results). -// do not use box values types (i.e. Number(), String(), etc.) - -const reverseKeywords = {}; -for (const key of Object.keys(cssKeywords)) { - reverseKeywords[cssKeywords[key]] = key; -} - -const convert = { - rgb: {channels: 3, labels: 'rgb'}, - hsl: {channels: 3, labels: 'hsl'}, - hsv: {channels: 3, labels: 'hsv'}, - hwb: {channels: 3, labels: 'hwb'}, - cmyk: {channels: 4, labels: 'cmyk'}, - xyz: {channels: 3, labels: 'xyz'}, - lab: {channels: 3, labels: 'lab'}, - lch: {channels: 3, labels: 'lch'}, - hex: {channels: 1, labels: ['hex']}, - keyword: {channels: 1, labels: ['keyword']}, - ansi16: {channels: 1, labels: ['ansi16']}, - ansi256: {channels: 1, labels: ['ansi256']}, - hcg: {channels: 3, labels: ['h', 'c', 'g']}, - apple: {channels: 3, labels: ['r16', 'g16', 'b16']}, - gray: {channels: 1, labels: ['gray']} -}; - -module.exports = convert; - -// Hide .channels and .labels properties -for (const model of Object.keys(convert)) { - if (!('channels' in convert[model])) { - throw new Error('missing channels property: ' + model); - } + __running__() { + return this.runScript("running", []); + } - if (!('labels' in convert[model])) { - throw new Error('missing channel labels property: ' + model); - } + __queued__() { + return this.runScript("queued", []); + } - if (convert[model].labels.length !== convert[model].channels) { - throw new Error('channel and label counts mismatch: ' + model); - } + __done__() { + return this.runScript("done", []); + } - const {channels, labels} = convert[model]; - delete convert[model].channels; - delete convert[model].labels; - Object.defineProperty(convert[model], 'channels', {value: channels}); - Object.defineProperty(convert[model], 'labels', {value: labels}); -} - -convert.rgb.hsl = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const min = Math.min(r, g, b); - const max = Math.max(r, g, b); - const delta = max - min; - let h; - let s; - - if (max === min) { - h = 0; - } else if (r === max) { - h = (g - b) / delta; - } else if (g === max) { - h = 2 + (b - r) / delta; - } else if (b === max) { - h = 4 + (r - g) / delta; - } + __groupCheck__() { + var _this5 = this; - h = Math.min(h * 60, 360); + return _asyncToGenerator(function* () { + return _this5.convertBool((yield _this5.runScript("group_check", []))); + })(); + } - if (h < 0) { - h += 360; - } + __incrementReservoir__(incr) { + return this.runScript("increment_reservoir", [incr]); + } - const l = (min + max) / 2; + __currentReservoir__() { + return this.runScript("current_reservoir", []); + } - if (max === min) { - s = 0; - } else if (l <= 0.5) { - s = delta / (max + min); - } else { - s = delta / (2 - max - min); - } + __check__(weight) { + var _this6 = this; - return [h, s * 100, l * 100]; -}; + return _asyncToGenerator(function* () { + return _this6.convertBool((yield _this6.runScript("check", _this6.prepareArray([weight])))); + })(); + } -convert.rgb.hsv = function (rgb) { - let rdif; - let gdif; - let bdif; - let h; - let s; + __register__(index, weight, expiration) { + var _this7 = this; - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const v = Math.max(r, g, b); - const diff = v - Math.min(r, g, b); - const diffc = function (c) { - return (v - c) / 6 / diff + 1 / 2; - }; + return _asyncToGenerator(function* () { + var reservoir, success, wait; - if (diff === 0) { - h = 0; - s = 0; - } else { - s = diff / v; - rdif = diffc(r); - gdif = diffc(g); - bdif = diffc(b); - - if (r === v) { - h = bdif - gdif; - } else if (g === v) { - h = (1 / 3) + rdif - bdif; - } else if (b === v) { - h = (2 / 3) + gdif - rdif; - } + var _ref4 = yield _this7.runScript("register", _this7.prepareArray([index, weight, expiration])); - if (h < 0) { - h += 1; - } else if (h > 1) { - h -= 1; - } - } + var _ref5 = _slicedToArray(_ref4, 3); - return [ - h * 360, - s * 100, - v * 100 - ]; -}; + success = _ref5[0]; + wait = _ref5[1]; + reservoir = _ref5[2]; + return { + success: _this7.convertBool(success), + wait, + reservoir + }; + })(); + } -convert.rgb.hwb = function (rgb) { - const r = rgb[0]; - const g = rgb[1]; - let b = rgb[2]; - const h = convert.rgb.hsl(rgb)[0]; - const w = 1 / 255 * Math.min(r, Math.min(g, b)); + __submit__(queueLength, weight) { + var _this8 = this; + + return _asyncToGenerator(function* () { + var blocked, e, maxConcurrent, overweight, reachedHWM, strategy; - b = 1 - 1 / 255 * Math.max(r, Math.max(g, b)); + try { + var _ref6 = yield _this8.runScript("submit", _this8.prepareArray([queueLength, weight])); - return [h, w * 100, b * 100]; -}; + var _ref7 = _slicedToArray(_ref6, 3); + + reachedHWM = _ref7[0]; + blocked = _ref7[1]; + strategy = _ref7[2]; + return { + reachedHWM: _this8.convertBool(reachedHWM), + blocked: _this8.convertBool(blocked), + strategy + }; + } catch (error) { + e = error; -convert.rgb.cmyk = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; + if (e.message.indexOf("OVERWEIGHT") === 0) { + var _e$message$split = e.message.split(":"); - const k = Math.min(1 - r, 1 - g, 1 - b); - const c = (1 - r - k) / (1 - k) || 0; - const m = (1 - g - k) / (1 - k) || 0; - const y = (1 - b - k) / (1 - k) || 0; + var _e$message$split2 = _slicedToArray(_e$message$split, 3); - return [c * 100, m * 100, y * 100, k * 100]; -}; + overweight = _e$message$split2[0]; + weight = _e$message$split2[1]; + maxConcurrent = _e$message$split2[2]; + throw new BottleneckError(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${maxConcurrent}`); + } else { + throw e; + } + } + })(); + } -function comparativeDistance(x, y) { - /* - See https://en.m.wikipedia.org/wiki/Euclidean_distance#Squared_Euclidean_distance - */ - return ( - ((x[0] - y[0]) ** 2) + - ((x[1] - y[1]) ** 2) + - ((x[2] - y[2]) ** 2) - ); -} + __free__(index, weight) { + var _this9 = this; -convert.rgb.keyword = function (rgb) { - const reversed = reverseKeywords[rgb]; - if (reversed) { - return reversed; - } + return _asyncToGenerator(function* () { + var running; + running = yield _this9.runScript("free", _this9.prepareArray([index])); + return { + running + }; + })(); + } - let currentClosestDistance = Infinity; - let currentClosestKeyword; +}; +module.exports = RedisDatastore; - for (const keyword of Object.keys(cssKeywords)) { - const value = cssKeywords[keyword]; +/***/ }), - // Compute comparative distance - const distance = comparativeDistance(rgb, value); +/***/ 4169: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - // Check if its less, if so set as closest - if (distance < currentClosestDistance) { - currentClosestDistance = distance; - currentClosestKeyword = keyword; - } - } +"use strict"; - return currentClosestKeyword; -}; -convert.keyword.rgb = function (keyword) { - return cssKeywords[keyword]; +var headers, lua, templates; +lua = __nccwpck_require__(23122); +headers = { + refs: lua["refs.lua"], + validate_keys: lua["validate_keys.lua"], + validate_client: lua["validate_client.lua"], + refresh_expiration: lua["refresh_expiration.lua"], + process_tick: lua["process_tick.lua"], + conditions_check: lua["conditions_check.lua"], + get_time: lua["get_time.lua"] }; -convert.rgb.xyz = function (rgb) { - let r = rgb[0] / 255; - let g = rgb[1] / 255; - let b = rgb[2] / 255; +exports.allKeys = function (id) { + return [ + /* + HASH + */ + `b_${id}_settings`, + /* + HASH + job index -> weight + */ + `b_${id}_job_weights`, + /* + ZSET + job index -> expiration + */ + `b_${id}_job_expirations`, + /* + HASH + job index -> client + */ + `b_${id}_job_clients`, + /* + ZSET + client -> sum running + */ + `b_${id}_client_running`, + /* + HASH + client -> num queued + */ + `b_${id}_client_num_queued`, + /* + ZSET + client -> last job registered + */ + `b_${id}_client_last_registered`, + /* + ZSET + client -> last seen + */ + `b_${id}_client_last_seen`]; +}; - // Assume sRGB - r = r > 0.04045 ? (((r + 0.055) / 1.055) ** 2.4) : (r / 12.92); - g = g > 0.04045 ? (((g + 0.055) / 1.055) ** 2.4) : (g / 12.92); - b = b > 0.04045 ? (((b + 0.055) / 1.055) ** 2.4) : (b / 12.92); +templates = { + init: { + keys: exports.allKeys, + headers: ["process_tick"], + refresh_expiration: true, + code: lua["init.lua"] + }, + group_check: { + keys: exports.allKeys, + headers: [], + refresh_expiration: false, + code: lua["group_check.lua"] + }, + register_client: { + keys: exports.allKeys, + headers: ["validate_keys"], + refresh_expiration: false, + code: lua["register_client.lua"] + }, + blacklist_client: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client"], + refresh_expiration: false, + code: lua["blacklist_client.lua"] + }, + heartbeat: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: false, + code: lua["heartbeat.lua"] + }, + update_settings: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: true, + code: lua["update_settings.lua"] + }, + running: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: false, + code: lua["running.lua"] + }, + queued: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client"], + refresh_expiration: false, + code: lua["queued.lua"] + }, + done: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: false, + code: lua["done.lua"] + }, + check: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], + refresh_expiration: false, + code: lua["check.lua"] + }, + submit: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], + refresh_expiration: true, + code: lua["submit.lua"] + }, + register: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick", "conditions_check"], + refresh_expiration: true, + code: lua["register.lua"] + }, + free: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: true, + code: lua["free.lua"] + }, + current_reservoir: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: false, + code: lua["current_reservoir.lua"] + }, + increment_reservoir: { + keys: exports.allKeys, + headers: ["validate_keys", "validate_client", "process_tick"], + refresh_expiration: true, + code: lua["increment_reservoir.lua"] + } +}; +exports.names = Object.keys(templates); - const x = (r * 0.4124) + (g * 0.3576) + (b * 0.1805); - const y = (r * 0.2126) + (g * 0.7152) + (b * 0.0722); - const z = (r * 0.0193) + (g * 0.1192) + (b * 0.9505); +exports.keys = function (name, id) { + return templates[name].keys(id); +}; - return [x * 100, y * 100, z * 100]; +exports.payload = function (name) { + var template; + template = templates[name]; + return Array.prototype.concat(headers.refs, template.headers.map(function (h) { + return headers[h]; + }), template.refresh_expiration ? headers.refresh_expiration : "", template.code).join("\n"); }; -convert.rgb.lab = function (rgb) { - const xyz = convert.rgb.xyz(rgb); - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; +/***/ }), - x /= 95.047; - y /= 100; - z /= 108.883; +/***/ 2527: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); +"use strict"; - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); - return [l, a, b]; -}; +var BottleneckError, States; +BottleneckError = __nccwpck_require__(93529); +States = class States { + constructor(status1) { + this.status = status1; + this._jobs = {}; + this.counts = this.status.map(function () { + return 0; + }); + } -convert.hsl.rgb = function (hsl) { - const h = hsl[0] / 360; - const s = hsl[1] / 100; - const l = hsl[2] / 100; - let t2; - let t3; - let val; + next(id) { + var current, next; + current = this._jobs[id]; + next = current + 1; - if (s === 0) { - val = l * 255; - return [val, val, val]; - } + if (current != null && next < this.status.length) { + this.counts[current]--; + this.counts[next]++; + return this._jobs[id]++; + } else if (current != null) { + this.counts[current]--; + return delete this._jobs[id]; + } + } - if (l < 0.5) { - t2 = l * (1 + s); - } else { - t2 = l + s - l * s; - } + start(id) { + var initial; + initial = 0; + this._jobs[id] = initial; + return this.counts[initial]++; + } - const t1 = 2 * l - t2; + remove(id) { + var current; + current = this._jobs[id]; - const rgb = [0, 0, 0]; - for (let i = 0; i < 3; i++) { - t3 = h + 1 / 3 * -(i - 1); - if (t3 < 0) { - t3++; - } + if (current != null) { + this.counts[current]--; + delete this._jobs[id]; + } - if (t3 > 1) { - t3--; - } + return current != null; + } - if (6 * t3 < 1) { - val = t1 + (t2 - t1) * 6 * t3; - } else if (2 * t3 < 1) { - val = t2; - } else if (3 * t3 < 2) { - val = t1 + (t2 - t1) * (2 / 3 - t3) * 6; - } else { - val = t1; - } + jobStatus(id) { + var ref; + return (ref = this.status[this._jobs[id]]) != null ? ref : null; + } - rgb[i] = val * 255; - } + statusJobs(status) { + var k, pos, ref, results, v; - return rgb; -}; - -convert.hsl.hsv = function (hsl) { - const h = hsl[0]; - let s = hsl[1] / 100; - let l = hsl[2] / 100; - let smin = s; - const lmin = Math.max(l, 0.01); - - l *= 2; - s *= (l <= 1) ? l : 2 - l; - smin *= lmin <= 1 ? lmin : 2 - lmin; - const v = (l + s) / 2; - const sv = l === 0 ? (2 * smin) / (lmin + smin) : (2 * s) / (l + s); - - return [h, sv * 100, v * 100]; -}; - -convert.hsv.rgb = function (hsv) { - const h = hsv[0] / 60; - const s = hsv[1] / 100; - let v = hsv[2] / 100; - const hi = Math.floor(h) % 6; - - const f = h - Math.floor(h); - const p = 255 * v * (1 - s); - const q = 255 * v * (1 - (s * f)); - const t = 255 * v * (1 - (s * (1 - f))); - v *= 255; - - switch (hi) { - case 0: - return [v, t, p]; - case 1: - return [q, v, p]; - case 2: - return [p, v, t]; - case 3: - return [p, q, v]; - case 4: - return [t, p, v]; - case 5: - return [v, p, q]; - } -}; + if (status != null) { + pos = this.status.indexOf(status); -convert.hsv.hsl = function (hsv) { - const h = hsv[0]; - const s = hsv[1] / 100; - const v = hsv[2] / 100; - const vmin = Math.max(v, 0.01); - let sl; - let l; - - l = (2 - s) * v; - const lmin = (2 - s) * vmin; - sl = s * vmin; - sl /= (lmin <= 1) ? lmin : 2 - lmin; - sl = sl || 0; - l /= 2; - - return [h, sl * 100, l * 100]; -}; - -// http://dev.w3.org/csswg/css-color/#hwb-to-rgb -convert.hwb.rgb = function (hwb) { - const h = hwb[0] / 360; - let wh = hwb[1] / 100; - let bl = hwb[2] / 100; - const ratio = wh + bl; - let f; - - // Wh + bl cant be > 1 - if (ratio > 1) { - wh /= ratio; - bl /= ratio; - } + if (pos < 0) { + throw new BottleneckError(`status must be one of ${this.status.join(', ')}`); + } + + ref = this._jobs; + results = []; - const i = Math.floor(6 * h); - const v = 1 - bl; - f = 6 * h - i; + for (k in ref) { + v = ref[k]; - if ((i & 0x01) !== 0) { - f = 1 - f; - } + if (v === pos) { + results.push(k); + } + } - const n = wh + f * (v - wh); // Linear interpolation + return results; + } else { + return Object.keys(this._jobs); + } + } - let r; - let g; - let b; - /* eslint-disable max-statements-per-line,no-multi-spaces */ - switch (i) { - default: - case 6: - case 0: r = v; g = n; b = wh; break; - case 1: r = n; g = v; b = wh; break; - case 2: r = wh; g = v; b = n; break; - case 3: r = wh; g = n; b = v; break; - case 4: r = n; g = wh; b = v; break; - case 5: r = v; g = wh; b = n; break; - } - /* eslint-enable max-statements-per-line,no-multi-spaces */ + statusCounts() { + return this.counts.reduce((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }, {}); + } - return [r * 255, g * 255, b * 255]; }; +module.exports = States; -convert.cmyk.rgb = function (cmyk) { - const c = cmyk[0] / 100; - const m = cmyk[1] / 100; - const y = cmyk[2] / 100; - const k = cmyk[3] / 100; +/***/ }), - const r = 1 - Math.min(1, c * (1 - k) + k); - const g = 1 - Math.min(1, m * (1 - k) + k); - const b = 1 - Math.min(1, y * (1 - k) + k); +/***/ 56029: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return [r * 255, g * 255, b * 255]; -}; +"use strict"; -convert.xyz.rgb = function (xyz) { - const x = xyz[0] / 100; - const y = xyz[1] / 100; - const z = xyz[2] / 100; - let r; - let g; - let b; - r = (x * 3.2406) + (y * -1.5372) + (z * -0.4986); - g = (x * -0.9689) + (y * 1.8758) + (z * 0.0415); - b = (x * 0.0557) + (y * -0.2040) + (z * 1.0570); +function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } } - // Assume sRGB - r = r > 0.0031308 - ? ((1.055 * (r ** (1.0 / 2.4))) - 0.055) - : r * 12.92; +function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; } - g = g > 0.0031308 - ? ((1.055 * (g ** (1.0 / 2.4))) - 0.055) - : g * 12.92; +var DLList, Sync; +DLList = __nccwpck_require__(38579); +Sync = class Sync { + constructor(name, Promise) { + this.schedule = this.schedule.bind(this); + this.name = name; + this.Promise = Promise; + this._running = 0; + this._queue = new DLList(); + } - b = b > 0.0031308 - ? ((1.055 * (b ** (1.0 / 2.4))) - 0.055) - : b * 12.92; + isEmpty() { + return this._queue.length === 0; + } - r = Math.min(Math.max(0, r), 1); - g = Math.min(Math.max(0, g), 1); - b = Math.min(Math.max(0, b), 1); + _tryToRun() { + var _this = this; - return [r * 255, g * 255, b * 255]; -}; + return _asyncToGenerator(function* () { + var args, cb, error, reject, resolve, returned, task; -convert.xyz.lab = function (xyz) { - let x = xyz[0]; - let y = xyz[1]; - let z = xyz[2]; + if (_this._running < 1 && _this._queue.length > 0) { + _this._running++; - x /= 95.047; - y /= 100; - z /= 108.883; + var _this$_queue$shift = _this._queue.shift(); - x = x > 0.008856 ? (x ** (1 / 3)) : (7.787 * x) + (16 / 116); - y = y > 0.008856 ? (y ** (1 / 3)) : (7.787 * y) + (16 / 116); - z = z > 0.008856 ? (z ** (1 / 3)) : (7.787 * z) + (16 / 116); + task = _this$_queue$shift.task; + args = _this$_queue$shift.args; + resolve = _this$_queue$shift.resolve; + reject = _this$_queue$shift.reject; + cb = yield _asyncToGenerator(function* () { + try { + returned = yield task(...args); + return function () { + return resolve(returned); + }; + } catch (error1) { + error = error1; + return function () { + return reject(error); + }; + } + })(); + _this._running--; - const l = (116 * y) - 16; - const a = 500 * (x - y); - const b = 200 * (y - z); + _this._tryToRun(); - return [l, a, b]; -}; + return cb(); + } + })(); + } -convert.lab.xyz = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let x; - let y; - let z; + schedule(task, ...args) { + var promise, reject, resolve; + resolve = reject = null; + promise = new this.Promise(function (_resolve, _reject) { + resolve = _resolve; + return reject = _reject; + }); - y = (l + 16) / 116; - x = a / 500 + y; - z = y - b / 200; + this._queue.push({ + task, + args, + resolve, + reject + }); - const y2 = y ** 3; - const x2 = x ** 3; - const z2 = z ** 3; - y = y2 > 0.008856 ? y2 : (y - 16 / 116) / 7.787; - x = x2 > 0.008856 ? x2 : (x - 16 / 116) / 7.787; - z = z2 > 0.008856 ? z2 : (z - 16 / 116) / 7.787; + this._tryToRun(); - x *= 95.047; - y *= 100; - z *= 108.883; + return promise; + } - return [x, y, z]; }; +module.exports = Sync; -convert.lab.lch = function (lab) { - const l = lab[0]; - const a = lab[1]; - const b = lab[2]; - let h; +/***/ }), - const hr = Math.atan2(b, a); - h = hr * 360 / 2 / Math.PI; +/***/ 27356: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (h < 0) { - h += 360; - } +"use strict"; - const c = Math.sqrt(a * a + b * b); - return [l, c, h]; -}; +module.exports = __nccwpck_require__(83911); -convert.lch.lab = function (lch) { - const l = lch[0]; - const c = lch[1]; - const h = lch[2]; +/***/ }), - const hr = h / 360 * 2 * Math.PI; - const a = c * Math.cos(hr); - const b = c * Math.sin(hr); +/***/ 67823: +/***/ ((__unused_webpack_module, exports) => { - return [l, a, b]; -}; +"use strict"; -convert.rgb.ansi16 = function (args, saturation = null) { - const [r, g, b] = args; - let value = saturation === null ? convert.rgb.hsv(args)[2] : saturation; // Hsv -> ansi16 optimization - value = Math.round(value / 50); +exports.load = function (received, defaults, onto = {}) { + var k, ref, v; - if (value === 0) { - return 30; - } + for (k in defaults) { + v = defaults[k]; + onto[k] = (ref = received[k]) != null ? ref : v; + } + + return onto; +}; - let ansi = 30 - + ((Math.round(b / 255) << 2) - | (Math.round(g / 255) << 1) - | Math.round(r / 255)); +exports.overwrite = function (received, defaults, onto = {}) { + var k, v; - if (value === 2) { - ansi += 60; - } + for (k in received) { + v = received[k]; - return ansi; -}; + if (defaults[k] !== void 0) { + onto[k] = v; + } + } -convert.hsv.ansi16 = function (args) { - // Optimization here; we already know the value and don't need to get - // it converted for us. - return convert.rgb.ansi16(convert.hsv.rgb(args), args[2]); + return onto; }; -convert.rgb.ansi256 = function (args) { - const r = args[0]; - const g = args[1]; - const b = args[2]; +/***/ }), - // We use the extended greyscale palette here, with the exception of - // black and white. normal palette only has 4 greyscale shades. - if (r === g && g === b) { - if (r < 8) { - return 16; - } +/***/ 11174: +/***/ (function(module) { - if (r > 248) { - return 231; - } +/** + * This file contains the Bottleneck library (MIT), compiled to ES2017, and without Clustering support. + * https://github.com/SGrondin/bottleneck + */ +(function (global, factory) { + true ? module.exports = factory() : + 0; +}(this, (function () { 'use strict'; - return Math.round(((r - 8) / 247) * 24) + 232; - } + var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {}; - const ansi = 16 - + (36 * Math.round(r / 255 * 5)) - + (6 * Math.round(g / 255 * 5)) - + Math.round(b / 255 * 5); + function getCjsExportFromNamespace (n) { + return n && n['default'] || n; + } - return ansi; -}; + var load = function(received, defaults, onto = {}) { + var k, ref, v; + for (k in defaults) { + v = defaults[k]; + onto[k] = (ref = received[k]) != null ? ref : v; + } + return onto; + }; -convert.ansi16.rgb = function (args) { - let color = args % 10; + var overwrite = function(received, defaults, onto = {}) { + var k, v; + for (k in received) { + v = received[k]; + if (defaults[k] !== void 0) { + onto[k] = v; + } + } + return onto; + }; - // Handle greyscale - if (color === 0 || color === 7) { - if (args > 50) { - color += 3.5; - } + var parser = { + load: load, + overwrite: overwrite + }; - color = color / 10.5 * 255; + var DLList; - return [color, color, color]; - } + DLList = class DLList { + constructor(incr, decr) { + this.incr = incr; + this.decr = decr; + this._first = null; + this._last = null; + this.length = 0; + } - const mult = (~~(args > 50) + 1) * 0.5; - const r = ((color & 1) * mult) * 255; - const g = (((color >> 1) & 1) * mult) * 255; - const b = (((color >> 2) & 1) * mult) * 255; + push(value) { + var node; + this.length++; + if (typeof this.incr === "function") { + this.incr(); + } + node = { + value, + prev: this._last, + next: null + }; + if (this._last != null) { + this._last.next = node; + this._last = node; + } else { + this._first = this._last = node; + } + return void 0; + } - return [r, g, b]; -}; + shift() { + var value; + if (this._first == null) { + return; + } else { + this.length--; + if (typeof this.decr === "function") { + this.decr(); + } + } + value = this._first.value; + if ((this._first = this._first.next) != null) { + this._first.prev = null; + } else { + this._last = null; + } + return value; + } -convert.ansi256.rgb = function (args) { - // Handle greyscale - if (args >= 232) { - const c = (args - 232) * 10 + 8; - return [c, c, c]; - } + first() { + if (this._first != null) { + return this._first.value; + } + } - args -= 16; + getArray() { + var node, ref, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, ref.value)); + } + return results; + } - let rem; - const r = Math.floor(args / 36) / 5 * 255; - const g = Math.floor((rem = args % 36) / 6) / 5 * 255; - const b = (rem % 6) / 5 * 255; + forEachShift(cb) { + var node; + node = this.shift(); + while (node != null) { + (cb(node), node = this.shift()); + } + return void 0; + } - return [r, g, b]; -}; + debug() { + var node, ref, ref1, ref2, results; + node = this._first; + results = []; + while (node != null) { + results.push((ref = node, node = node.next, { + value: ref.value, + prev: (ref1 = ref.prev) != null ? ref1.value : void 0, + next: (ref2 = ref.next) != null ? ref2.value : void 0 + })); + } + return results; + } -convert.rgb.hex = function (args) { - const integer = ((Math.round(args[0]) & 0xFF) << 16) - + ((Math.round(args[1]) & 0xFF) << 8) - + (Math.round(args[2]) & 0xFF); + }; - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; + var DLList_1 = DLList; -convert.hex.rgb = function (args) { - const match = args.toString(16).match(/[a-f0-9]{6}|[a-f0-9]{3}/i); - if (!match) { - return [0, 0, 0]; - } + var Events; - let colorString = match[0]; + Events = class Events { + constructor(instance) { + this.instance = instance; + this._events = {}; + if ((this.instance.on != null) || (this.instance.once != null) || (this.instance.removeAllListeners != null)) { + throw new Error("An Emitter already exists for this object"); + } + this.instance.on = (name, cb) => { + return this._addListener(name, "many", cb); + }; + this.instance.once = (name, cb) => { + return this._addListener(name, "once", cb); + }; + this.instance.removeAllListeners = (name = null) => { + if (name != null) { + return delete this._events[name]; + } else { + return this._events = {}; + } + }; + } - if (match[0].length === 3) { - colorString = colorString.split('').map(char => { - return char + char; - }).join(''); - } + _addListener(name, status, cb) { + var base; + if ((base = this._events)[name] == null) { + base[name] = []; + } + this._events[name].push({cb, status}); + return this.instance; + } - const integer = parseInt(colorString, 16); - const r = (integer >> 16) & 0xFF; - const g = (integer >> 8) & 0xFF; - const b = integer & 0xFF; + listenerCount(name) { + if (this._events[name] != null) { + return this._events[name].length; + } else { + return 0; + } + } - return [r, g, b]; -}; + async trigger(name, ...args) { + var e, promises; + try { + if (name !== "debug") { + this.trigger("debug", `Event triggered: ${name}`, args); + } + if (this._events[name] == null) { + return; + } + this._events[name] = this._events[name].filter(function(listener) { + return listener.status !== "none"; + }); + promises = this._events[name].map(async(listener) => { + var e, returned; + if (listener.status === "none") { + return; + } + if (listener.status === "once") { + listener.status = "none"; + } + try { + returned = typeof listener.cb === "function" ? listener.cb(...args) : void 0; + if (typeof (returned != null ? returned.then : void 0) === "function") { + return (await returned); + } else { + return returned; + } + } catch (error) { + e = error; + { + this.trigger("error", e); + } + return null; + } + }); + return ((await Promise.all(promises))).find(function(x) { + return x != null; + }); + } catch (error) { + e = error; + { + this.trigger("error", e); + } + return null; + } + } -convert.rgb.hcg = function (rgb) { - const r = rgb[0] / 255; - const g = rgb[1] / 255; - const b = rgb[2] / 255; - const max = Math.max(Math.max(r, g), b); - const min = Math.min(Math.min(r, g), b); - const chroma = (max - min); - let grayscale; - let hue; + }; - if (chroma < 1) { - grayscale = min / (1 - chroma); - } else { - grayscale = 0; - } + var Events_1 = Events; - if (chroma <= 0) { - hue = 0; - } else - if (max === r) { - hue = ((g - b) / chroma) % 6; - } else - if (max === g) { - hue = 2 + (b - r) / chroma; - } else { - hue = 4 + (r - g) / chroma; - } + var DLList$1, Events$1, Queues; - hue /= 6; - hue %= 1; + DLList$1 = DLList_1; - return [hue * 360, chroma * 100, grayscale * 100]; -}; + Events$1 = Events_1; -convert.hsl.hcg = function (hsl) { - const s = hsl[1] / 100; - const l = hsl[2] / 100; + Queues = class Queues { + constructor(num_priorities) { + var i; + this.Events = new Events$1(this); + this._length = 0; + this._lists = (function() { + var j, ref, results; + results = []; + for (i = j = 1, ref = num_priorities; (1 <= ref ? j <= ref : j >= ref); i = 1 <= ref ? ++j : --j) { + results.push(new DLList$1((() => { + return this.incr(); + }), (() => { + return this.decr(); + }))); + } + return results; + }).call(this); + } - const c = l < 0.5 ? (2.0 * s * l) : (2.0 * s * (1.0 - l)); + incr() { + if (this._length++ === 0) { + return this.Events.trigger("leftzero"); + } + } - let f = 0; - if (c < 1.0) { - f = (l - 0.5 * c) / (1.0 - c); - } + decr() { + if (--this._length === 0) { + return this.Events.trigger("zero"); + } + } - return [hsl[0], c * 100, f * 100]; -}; + push(job) { + return this._lists[job.options.priority].push(job); + } -convert.hsv.hcg = function (hsv) { - const s = hsv[1] / 100; - const v = hsv[2] / 100; + queued(priority) { + if (priority != null) { + return this._lists[priority].length; + } else { + return this._length; + } + } - const c = s * v; - let f = 0; + shiftAll(fn) { + return this._lists.forEach(function(list) { + return list.forEachShift(fn); + }); + } - if (c < 1.0) { - f = (v - c) / (1 - c); - } + getFirst(arr = this._lists) { + var j, len, list; + for (j = 0, len = arr.length; j < len; j++) { + list = arr[j]; + if (list.length > 0) { + return list; + } + } + return []; + } - return [hsv[0], c * 100, f * 100]; -}; + shiftLastFrom(priority) { + return this.getFirst(this._lists.slice(priority).reverse()).shift(); + } -convert.hcg.rgb = function (hcg) { - const h = hcg[0] / 360; - const c = hcg[1] / 100; - const g = hcg[2] / 100; + }; - if (c === 0.0) { - return [g * 255, g * 255, g * 255]; - } + var Queues_1 = Queues; - const pure = [0, 0, 0]; - const hi = (h % 1) * 6; - const v = hi % 1; - const w = 1 - v; - let mg = 0; - - /* eslint-disable max-statements-per-line */ - switch (Math.floor(hi)) { - case 0: - pure[0] = 1; pure[1] = v; pure[2] = 0; break; - case 1: - pure[0] = w; pure[1] = 1; pure[2] = 0; break; - case 2: - pure[0] = 0; pure[1] = 1; pure[2] = v; break; - case 3: - pure[0] = 0; pure[1] = w; pure[2] = 1; break; - case 4: - pure[0] = v; pure[1] = 0; pure[2] = 1; break; - default: - pure[0] = 1; pure[1] = 0; pure[2] = w; - } - /* eslint-enable max-statements-per-line */ + var BottleneckError; - mg = (1.0 - c) * g; + BottleneckError = class BottleneckError extends Error {}; - return [ - (c * pure[0] + mg) * 255, - (c * pure[1] + mg) * 255, - (c * pure[2] + mg) * 255 - ]; -}; + var BottleneckError_1 = BottleneckError; -convert.hcg.hsv = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; + var BottleneckError$1, DEFAULT_PRIORITY, Job, NUM_PRIORITIES, parser$1; - const v = c + g * (1.0 - c); - let f = 0; + NUM_PRIORITIES = 10; - if (v > 0.0) { - f = c / v; - } + DEFAULT_PRIORITY = 5; - return [hcg[0], f * 100, v * 100]; -}; + parser$1 = parser; -convert.hcg.hsl = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; + BottleneckError$1 = BottleneckError_1; - const l = g * (1.0 - c) + 0.5 * c; - let s = 0; + Job = class Job { + constructor(task, args, options, jobDefaults, rejectOnDrop, Events, _states, Promise) { + this.task = task; + this.args = args; + this.rejectOnDrop = rejectOnDrop; + this.Events = Events; + this._states = _states; + this.Promise = Promise; + this.options = parser$1.load(options, jobDefaults); + this.options.priority = this._sanitizePriority(this.options.priority); + if (this.options.id === jobDefaults.id) { + this.options.id = `${this.options.id}-${this._randomIndex()}`; + } + this.promise = new this.Promise((_resolve, _reject) => { + this._resolve = _resolve; + this._reject = _reject; + }); + this.retryCount = 0; + } - if (l > 0.0 && l < 0.5) { - s = c / (2 * l); - } else - if (l >= 0.5 && l < 1.0) { - s = c / (2 * (1 - l)); - } + _sanitizePriority(priority) { + var sProperty; + sProperty = ~~priority !== priority ? DEFAULT_PRIORITY : priority; + if (sProperty < 0) { + return 0; + } else if (sProperty > NUM_PRIORITIES - 1) { + return NUM_PRIORITIES - 1; + } else { + return sProperty; + } + } - return [hcg[0], s * 100, l * 100]; -}; + _randomIndex() { + return Math.random().toString(36).slice(2); + } -convert.hcg.hwb = function (hcg) { - const c = hcg[1] / 100; - const g = hcg[2] / 100; - const v = c + g * (1.0 - c); - return [hcg[0], (v - c) * 100, (1 - v) * 100]; -}; + doDrop({error, message = "This job has been dropped by Bottleneck"} = {}) { + if (this._states.remove(this.options.id)) { + if (this.rejectOnDrop) { + this._reject(error != null ? error : new BottleneckError$1(message)); + } + this.Events.trigger("dropped", {args: this.args, options: this.options, task: this.task, promise: this.promise}); + return true; + } else { + return false; + } + } -convert.hwb.hcg = function (hwb) { - const w = hwb[1] / 100; - const b = hwb[2] / 100; - const v = 1 - b; - const c = v - w; - let g = 0; + _assertStatus(expected) { + var status; + status = this._states.jobStatus(this.options.id); + if (!(status === expected || (expected === "DONE" && status === null))) { + throw new BottleneckError$1(`Invalid job status ${status}, expected ${expected}. Please open an issue at https://github.com/SGrondin/bottleneck/issues`); + } + } - if (c < 1) { - g = (v - c) / (1 - c); - } + doReceive() { + this._states.start(this.options.id); + return this.Events.trigger("received", {args: this.args, options: this.options}); + } - return [hwb[0], c * 100, g * 100]; -}; + doQueue(reachedHWM, blocked) { + this._assertStatus("RECEIVED"); + this._states.next(this.options.id); + return this.Events.trigger("queued", {args: this.args, options: this.options, reachedHWM, blocked}); + } -convert.apple.rgb = function (apple) { - return [(apple[0] / 65535) * 255, (apple[1] / 65535) * 255, (apple[2] / 65535) * 255]; -}; + doRun() { + if (this.retryCount === 0) { + this._assertStatus("QUEUED"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + return this.Events.trigger("scheduled", {args: this.args, options: this.options}); + } -convert.rgb.apple = function (rgb) { - return [(rgb[0] / 255) * 65535, (rgb[1] / 255) * 65535, (rgb[2] / 255) * 65535]; -}; + async doExecute(chained, clearGlobalState, run, free) { + var error, eventInfo, passed; + if (this.retryCount === 0) { + this._assertStatus("RUNNING"); + this._states.next(this.options.id); + } else { + this._assertStatus("EXECUTING"); + } + eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; + this.Events.trigger("executing", eventInfo); + try { + passed = (await (chained != null ? chained.schedule(this.options, this.task, ...this.args) : this.task(...this.args))); + if (clearGlobalState()) { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._resolve(passed); + } + } catch (error1) { + error = error1; + return this._onFailure(error, eventInfo, clearGlobalState, run, free); + } + } -convert.gray.rgb = function (args) { - return [args[0] / 100 * 255, args[0] / 100 * 255, args[0] / 100 * 255]; -}; + doExpire(clearGlobalState, run, free) { + var error, eventInfo; + if (this._states.jobStatus(this.options.id === "RUNNING")) { + this._states.next(this.options.id); + } + this._assertStatus("EXECUTING"); + eventInfo = {args: this.args, options: this.options, retryCount: this.retryCount}; + error = new BottleneckError$1(`This job timed out after ${this.options.expiration} ms.`); + return this._onFailure(error, eventInfo, clearGlobalState, run, free); + } -convert.gray.hsl = function (args) { - return [0, 0, args[0]]; -}; + async _onFailure(error, eventInfo, clearGlobalState, run, free) { + var retry, retryAfter; + if (clearGlobalState()) { + retry = (await this.Events.trigger("failed", error, eventInfo)); + if (retry != null) { + retryAfter = ~~retry; + this.Events.trigger("retry", `Retrying ${this.options.id} after ${retryAfter} ms`, eventInfo); + this.retryCount++; + return run(retryAfter); + } else { + this.doDone(eventInfo); + await free(this.options, eventInfo); + this._assertStatus("DONE"); + return this._reject(error); + } + } + } -convert.gray.hsv = convert.gray.hsl; + doDone(eventInfo) { + this._assertStatus("EXECUTING"); + this._states.next(this.options.id); + return this.Events.trigger("done", eventInfo); + } -convert.gray.hwb = function (gray) { - return [0, 100, gray[0]]; -}; + }; -convert.gray.cmyk = function (gray) { - return [0, 0, 0, gray[0]]; -}; + var Job_1 = Job; -convert.gray.lab = function (gray) { - return [gray[0], 0, 0]; -}; + var BottleneckError$2, LocalDatastore, parser$2; -convert.gray.hex = function (gray) { - const val = Math.round(gray[0] / 100 * 255) & 0xFF; - const integer = (val << 16) + (val << 8) + val; + parser$2 = parser; - const string = integer.toString(16).toUpperCase(); - return '000000'.substring(string.length) + string; -}; + BottleneckError$2 = BottleneckError_1; -convert.rgb.gray = function (rgb) { - const val = (rgb[0] + rgb[1] + rgb[2]) / 3; - return [val / 255 * 100]; -}; + LocalDatastore = class LocalDatastore { + constructor(instance, storeOptions, storeInstanceOptions) { + this.instance = instance; + this.storeOptions = storeOptions; + this.clientId = this.instance._randomIndex(); + parser$2.load(storeInstanceOptions, storeInstanceOptions, this); + this._nextRequest = this._lastReservoirRefresh = this._lastReservoirIncrease = Date.now(); + this._running = 0; + this._done = 0; + this._unblockTime = 0; + this.ready = this.Promise.resolve(); + this.clients = {}; + this._startHeartbeat(); + } + _startHeartbeat() { + var base; + if ((this.heartbeat == null) && (((this.storeOptions.reservoirRefreshInterval != null) && (this.storeOptions.reservoirRefreshAmount != null)) || ((this.storeOptions.reservoirIncreaseInterval != null) && (this.storeOptions.reservoirIncreaseAmount != null)))) { + return typeof (base = (this.heartbeat = setInterval(() => { + var amount, incr, maximum, now, reservoir; + now = Date.now(); + if ((this.storeOptions.reservoirRefreshInterval != null) && now >= this._lastReservoirRefresh + this.storeOptions.reservoirRefreshInterval) { + this._lastReservoirRefresh = now; + this.storeOptions.reservoir = this.storeOptions.reservoirRefreshAmount; + this.instance._drainAll(this.computeCapacity()); + } + if ((this.storeOptions.reservoirIncreaseInterval != null) && now >= this._lastReservoirIncrease + this.storeOptions.reservoirIncreaseInterval) { + ({ + reservoirIncreaseAmount: amount, + reservoirIncreaseMaximum: maximum, + reservoir + } = this.storeOptions); + this._lastReservoirIncrease = now; + incr = maximum != null ? Math.min(amount, maximum - reservoir) : amount; + if (incr > 0) { + this.storeOptions.reservoir += incr; + return this.instance._drainAll(this.computeCapacity()); + } + } + }, this.heartbeatInterval))).unref === "function" ? base.unref() : void 0; + } else { + return clearInterval(this.heartbeat); + } + } -/***/ }), + async __publish__(message) { + await this.yieldLoop(); + return this.instance.Events.trigger("message", message.toString()); + } -/***/ 86931: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + async __disconnect__(flush) { + await this.yieldLoop(); + clearInterval(this.heartbeat); + return this.Promise.resolve(); + } -const conversions = __nccwpck_require__(97391); -const route = __nccwpck_require__(30880); + yieldLoop(t = 0) { + return new this.Promise(function(resolve, reject) { + return setTimeout(resolve, t); + }); + } -const convert = {}; + computePenalty() { + var ref; + return (ref = this.storeOptions.penalty) != null ? ref : (15 * this.storeOptions.minTime) || 5000; + } -const models = Object.keys(conversions); + async __updateSettings__(options) { + await this.yieldLoop(); + parser$2.overwrite(options, options, this.storeOptions); + this._startHeartbeat(); + this.instance._drainAll(this.computeCapacity()); + return true; + } -function wrapRaw(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; - if (arg0 === undefined || arg0 === null) { - return arg0; - } + async __running__() { + await this.yieldLoop(); + return this._running; + } - if (arg0.length > 1) { - args = arg0; - } + async __queued__() { + await this.yieldLoop(); + return this.instance.queued(); + } - return fn(args); - }; + async __done__() { + await this.yieldLoop(); + return this._done; + } - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } + async __groupCheck__(time) { + await this.yieldLoop(); + return (this._nextRequest + this.timeout) < time; + } - return wrappedFn; -} + computeCapacity() { + var maxConcurrent, reservoir; + ({maxConcurrent, reservoir} = this.storeOptions); + if ((maxConcurrent != null) && (reservoir != null)) { + return Math.min(maxConcurrent - this._running, reservoir); + } else if (maxConcurrent != null) { + return maxConcurrent - this._running; + } else if (reservoir != null) { + return reservoir; + } else { + return null; + } + } -function wrapRounded(fn) { - const wrappedFn = function (...args) { - const arg0 = args[0]; + conditionsCheck(weight) { + var capacity; + capacity = this.computeCapacity(); + return (capacity == null) || weight <= capacity; + } - if (arg0 === undefined || arg0 === null) { - return arg0; - } + async __incrementReservoir__(incr) { + var reservoir; + await this.yieldLoop(); + reservoir = this.storeOptions.reservoir += incr; + this.instance._drainAll(this.computeCapacity()); + return reservoir; + } - if (arg0.length > 1) { - args = arg0; - } + async __currentReservoir__() { + await this.yieldLoop(); + return this.storeOptions.reservoir; + } - const result = fn(args); + isBlocked(now) { + return this._unblockTime >= now; + } - // We're assuming the result is an array here. - // see notice in conversions.js; don't use box types - // in conversion functions. - if (typeof result === 'object') { - for (let len = result.length, i = 0; i < len; i++) { - result[i] = Math.round(result[i]); - } - } + check(weight, now) { + return this.conditionsCheck(weight) && (this._nextRequest - now) <= 0; + } - return result; - }; + async __check__(weight) { + var now; + await this.yieldLoop(); + now = Date.now(); + return this.check(weight, now); + } - // Preserve .conversion property if there is one - if ('conversion' in fn) { - wrappedFn.conversion = fn.conversion; - } + async __register__(index, weight, expiration) { + var now, wait; + await this.yieldLoop(); + now = Date.now(); + if (this.conditionsCheck(weight)) { + this._running += weight; + if (this.storeOptions.reservoir != null) { + this.storeOptions.reservoir -= weight; + } + wait = Math.max(this._nextRequest - now, 0); + this._nextRequest = now + wait + this.storeOptions.minTime; + return { + success: true, + wait, + reservoir: this.storeOptions.reservoir + }; + } else { + return { + success: false + }; + } + } - return wrappedFn; -} + strategyIsBlock() { + return this.storeOptions.strategy === 3; + } -models.forEach(fromModel => { - convert[fromModel] = {}; + async __submit__(queueLength, weight) { + var blocked, now, reachedHWM; + await this.yieldLoop(); + if ((this.storeOptions.maxConcurrent != null) && weight > this.storeOptions.maxConcurrent) { + throw new BottleneckError$2(`Impossible to add a job having a weight of ${weight} to a limiter having a maxConcurrent setting of ${this.storeOptions.maxConcurrent}`); + } + now = Date.now(); + reachedHWM = (this.storeOptions.highWater != null) && queueLength === this.storeOptions.highWater && !this.check(weight, now); + blocked = this.strategyIsBlock() && (reachedHWM || this.isBlocked(now)); + if (blocked) { + this._unblockTime = now + this.computePenalty(); + this._nextRequest = this._unblockTime + this.storeOptions.minTime; + this.instance._dropAllQueued(); + } + return { + reachedHWM, + blocked, + strategy: this.storeOptions.strategy + }; + } - Object.defineProperty(convert[fromModel], 'channels', {value: conversions[fromModel].channels}); - Object.defineProperty(convert[fromModel], 'labels', {value: conversions[fromModel].labels}); + async __free__(index, weight) { + await this.yieldLoop(); + this._running -= weight; + this._done += weight; + this.instance._drainAll(this.computeCapacity()); + return { + running: this._running + }; + } - const routes = route(fromModel); - const routeModels = Object.keys(routes); + }; - routeModels.forEach(toModel => { - const fn = routes[toModel]; + var LocalDatastore_1 = LocalDatastore; - convert[fromModel][toModel] = wrapRounded(fn); - convert[fromModel][toModel].raw = wrapRaw(fn); - }); -}); + var BottleneckError$3, States; -module.exports = convert; + BottleneckError$3 = BottleneckError_1; + States = class States { + constructor(status1) { + this.status = status1; + this._jobs = {}; + this.counts = this.status.map(function() { + return 0; + }); + } -/***/ }), + next(id) { + var current, next; + current = this._jobs[id]; + next = current + 1; + if ((current != null) && next < this.status.length) { + this.counts[current]--; + this.counts[next]++; + return this._jobs[id]++; + } else if (current != null) { + this.counts[current]--; + return delete this._jobs[id]; + } + } -/***/ 30880: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + start(id) { + var initial; + initial = 0; + this._jobs[id] = initial; + return this.counts[initial]++; + } -const conversions = __nccwpck_require__(97391); + remove(id) { + var current; + current = this._jobs[id]; + if (current != null) { + this.counts[current]--; + delete this._jobs[id]; + } + return current != null; + } -/* - This function routes a model to all other models. + jobStatus(id) { + var ref; + return (ref = this.status[this._jobs[id]]) != null ? ref : null; + } - all functions that are routed have a property `.conversion` attached - to the returned synthetic function. This property is an array - of strings, each with the steps in between the 'from' and 'to' - color models (inclusive). + statusJobs(status) { + var k, pos, ref, results, v; + if (status != null) { + pos = this.status.indexOf(status); + if (pos < 0) { + throw new BottleneckError$3(`status must be one of ${this.status.join(', ')}`); + } + ref = this._jobs; + results = []; + for (k in ref) { + v = ref[k]; + if (v === pos) { + results.push(k); + } + } + return results; + } else { + return Object.keys(this._jobs); + } + } - conversions that are not possible simply are not included. -*/ + statusCounts() { + return this.counts.reduce(((acc, v, i) => { + acc[this.status[i]] = v; + return acc; + }), {}); + } -function buildGraph() { - const graph = {}; - // https://jsperf.com/object-keys-vs-for-in-with-closure/3 - const models = Object.keys(conversions); - - for (let len = models.length, i = 0; i < len; i++) { - graph[models[i]] = { - // http://jsperf.com/1-vs-infinity - // micro-opt, but this is simple. - distance: -1, - parent: null - }; - } + }; - return graph; -} + var States_1 = States; -// https://en.wikipedia.org/wiki/Breadth-first_search -function deriveBFS(fromModel) { - const graph = buildGraph(); - const queue = [fromModel]; // Unshift -> queue -> pop + var DLList$2, Sync; - graph[fromModel].distance = 0; + DLList$2 = DLList_1; - while (queue.length) { - const current = queue.pop(); - const adjacents = Object.keys(conversions[current]); + Sync = class Sync { + constructor(name, Promise) { + this.schedule = this.schedule.bind(this); + this.name = name; + this.Promise = Promise; + this._running = 0; + this._queue = new DLList$2(); + } - for (let len = adjacents.length, i = 0; i < len; i++) { - const adjacent = adjacents[i]; - const node = graph[adjacent]; + isEmpty() { + return this._queue.length === 0; + } - if (node.distance === -1) { - node.distance = graph[current].distance + 1; - node.parent = current; - queue.unshift(adjacent); - } - } - } + async _tryToRun() { + var args, cb, error, reject, resolve, returned, task; + if ((this._running < 1) && this._queue.length > 0) { + this._running++; + ({task, args, resolve, reject} = this._queue.shift()); + cb = (await (async function() { + try { + returned = (await task(...args)); + return function() { + return resolve(returned); + }; + } catch (error1) { + error = error1; + return function() { + return reject(error); + }; + } + })()); + this._running--; + this._tryToRun(); + return cb(); + } + } - return graph; -} + schedule(task, ...args) { + var promise, reject, resolve; + resolve = reject = null; + promise = new this.Promise(function(_resolve, _reject) { + resolve = _resolve; + return reject = _reject; + }); + this._queue.push({task, args, resolve, reject}); + this._tryToRun(); + return promise; + } -function link(from, to) { - return function (args) { - return to(from(args)); }; -} - -function wrapConversion(toModel, graph) { - const path = [graph[toModel].parent, toModel]; - let fn = conversions[graph[toModel].parent][toModel]; - - let cur = graph[toModel].parent; - while (graph[cur].parent) { - path.unshift(graph[cur].parent); - fn = link(conversions[graph[cur].parent][cur], fn); - cur = graph[cur].parent; - } - - fn.conversion = path; - return fn; -} - -module.exports = function (fromModel) { - const graph = deriveBFS(fromModel); - const conversion = {}; - const models = Object.keys(graph); - for (let len = models.length, i = 0; i < len; i++) { - const toModel = models[i]; - const node = graph[toModel]; - - if (node.parent === null) { - // No possible conversion, or this node is the source model. - continue; - } - - conversion[toModel] = wrapConversion(toModel, graph); - } + var Sync_1 = Sync; - return conversion; -}; + var version = "2.19.5"; + var version$1 = { + version: version + }; + var version$2 = /*#__PURE__*/Object.freeze({ + version: version, + default: version$1 + }); + var require$$2 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -/***/ }), + var require$$3 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -/***/ 78510: -/***/ ((module) => { + var require$$4 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); -"use strict"; + var Events$2, Group, IORedisConnection$1, RedisConnection$1, Scripts$1, parser$3; + parser$3 = parser; -module.exports = { - "aliceblue": [240, 248, 255], - "antiquewhite": [250, 235, 215], - "aqua": [0, 255, 255], - "aquamarine": [127, 255, 212], - "azure": [240, 255, 255], - "beige": [245, 245, 220], - "bisque": [255, 228, 196], - "black": [0, 0, 0], - "blanchedalmond": [255, 235, 205], - "blue": [0, 0, 255], - "blueviolet": [138, 43, 226], - "brown": [165, 42, 42], - "burlywood": [222, 184, 135], - "cadetblue": [95, 158, 160], - "chartreuse": [127, 255, 0], - "chocolate": [210, 105, 30], - "coral": [255, 127, 80], - "cornflowerblue": [100, 149, 237], - "cornsilk": [255, 248, 220], - "crimson": [220, 20, 60], - "cyan": [0, 255, 255], - "darkblue": [0, 0, 139], - "darkcyan": [0, 139, 139], - "darkgoldenrod": [184, 134, 11], - "darkgray": [169, 169, 169], - "darkgreen": [0, 100, 0], - "darkgrey": [169, 169, 169], - "darkkhaki": [189, 183, 107], - "darkmagenta": [139, 0, 139], - "darkolivegreen": [85, 107, 47], - "darkorange": [255, 140, 0], - "darkorchid": [153, 50, 204], - "darkred": [139, 0, 0], - "darksalmon": [233, 150, 122], - "darkseagreen": [143, 188, 143], - "darkslateblue": [72, 61, 139], - "darkslategray": [47, 79, 79], - "darkslategrey": [47, 79, 79], - "darkturquoise": [0, 206, 209], - "darkviolet": [148, 0, 211], - "deeppink": [255, 20, 147], - "deepskyblue": [0, 191, 255], - "dimgray": [105, 105, 105], - "dimgrey": [105, 105, 105], - "dodgerblue": [30, 144, 255], - "firebrick": [178, 34, 34], - "floralwhite": [255, 250, 240], - "forestgreen": [34, 139, 34], - "fuchsia": [255, 0, 255], - "gainsboro": [220, 220, 220], - "ghostwhite": [248, 248, 255], - "gold": [255, 215, 0], - "goldenrod": [218, 165, 32], - "gray": [128, 128, 128], - "green": [0, 128, 0], - "greenyellow": [173, 255, 47], - "grey": [128, 128, 128], - "honeydew": [240, 255, 240], - "hotpink": [255, 105, 180], - "indianred": [205, 92, 92], - "indigo": [75, 0, 130], - "ivory": [255, 255, 240], - "khaki": [240, 230, 140], - "lavender": [230, 230, 250], - "lavenderblush": [255, 240, 245], - "lawngreen": [124, 252, 0], - "lemonchiffon": [255, 250, 205], - "lightblue": [173, 216, 230], - "lightcoral": [240, 128, 128], - "lightcyan": [224, 255, 255], - "lightgoldenrodyellow": [250, 250, 210], - "lightgray": [211, 211, 211], - "lightgreen": [144, 238, 144], - "lightgrey": [211, 211, 211], - "lightpink": [255, 182, 193], - "lightsalmon": [255, 160, 122], - "lightseagreen": [32, 178, 170], - "lightskyblue": [135, 206, 250], - "lightslategray": [119, 136, 153], - "lightslategrey": [119, 136, 153], - "lightsteelblue": [176, 196, 222], - "lightyellow": [255, 255, 224], - "lime": [0, 255, 0], - "limegreen": [50, 205, 50], - "linen": [250, 240, 230], - "magenta": [255, 0, 255], - "maroon": [128, 0, 0], - "mediumaquamarine": [102, 205, 170], - "mediumblue": [0, 0, 205], - "mediumorchid": [186, 85, 211], - "mediumpurple": [147, 112, 219], - "mediumseagreen": [60, 179, 113], - "mediumslateblue": [123, 104, 238], - "mediumspringgreen": [0, 250, 154], - "mediumturquoise": [72, 209, 204], - "mediumvioletred": [199, 21, 133], - "midnightblue": [25, 25, 112], - "mintcream": [245, 255, 250], - "mistyrose": [255, 228, 225], - "moccasin": [255, 228, 181], - "navajowhite": [255, 222, 173], - "navy": [0, 0, 128], - "oldlace": [253, 245, 230], - "olive": [128, 128, 0], - "olivedrab": [107, 142, 35], - "orange": [255, 165, 0], - "orangered": [255, 69, 0], - "orchid": [218, 112, 214], - "palegoldenrod": [238, 232, 170], - "palegreen": [152, 251, 152], - "paleturquoise": [175, 238, 238], - "palevioletred": [219, 112, 147], - "papayawhip": [255, 239, 213], - "peachpuff": [255, 218, 185], - "peru": [205, 133, 63], - "pink": [255, 192, 203], - "plum": [221, 160, 221], - "powderblue": [176, 224, 230], - "purple": [128, 0, 128], - "rebeccapurple": [102, 51, 153], - "red": [255, 0, 0], - "rosybrown": [188, 143, 143], - "royalblue": [65, 105, 225], - "saddlebrown": [139, 69, 19], - "salmon": [250, 128, 114], - "sandybrown": [244, 164, 96], - "seagreen": [46, 139, 87], - "seashell": [255, 245, 238], - "sienna": [160, 82, 45], - "silver": [192, 192, 192], - "skyblue": [135, 206, 235], - "slateblue": [106, 90, 205], - "slategray": [112, 128, 144], - "slategrey": [112, 128, 144], - "snow": [255, 250, 250], - "springgreen": [0, 255, 127], - "steelblue": [70, 130, 180], - "tan": [210, 180, 140], - "teal": [0, 128, 128], - "thistle": [216, 191, 216], - "tomato": [255, 99, 71], - "turquoise": [64, 224, 208], - "violet": [238, 130, 238], - "wheat": [245, 222, 179], - "white": [255, 255, 255], - "whitesmoke": [245, 245, 245], - "yellow": [255, 255, 0], - "yellowgreen": [154, 205, 50] -}; + Events$2 = Events_1; + RedisConnection$1 = require$$2; -/***/ }), + IORedisConnection$1 = require$$3; -/***/ 43595: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + Scripts$1 = require$$4; -/* + Group = (function() { + class Group { + constructor(limiterOptions = {}) { + this.deleteKey = this.deleteKey.bind(this); + this.limiterOptions = limiterOptions; + parser$3.load(this.limiterOptions, this.defaults, this); + this.Events = new Events$2(this); + this.instances = {}; + this.Bottleneck = Bottleneck_1; + this._startAutoCleanup(); + this.sharedConnection = this.connection != null; + if (this.connection == null) { + if (this.limiterOptions.datastore === "redis") { + this.connection = new RedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); + } else if (this.limiterOptions.datastore === "ioredis") { + this.connection = new IORedisConnection$1(Object.assign({}, this.limiterOptions, {Events: this.Events})); + } + } + } -The MIT License (MIT) + key(key = "") { + var ref; + return (ref = this.instances[key]) != null ? ref : (() => { + var limiter; + limiter = this.instances[key] = new this.Bottleneck(Object.assign(this.limiterOptions, { + id: `${this.id}-${key}`, + timeout: this.timeout, + connection: this.connection + })); + this.Events.trigger("created", limiter, key); + return limiter; + })(); + } -Original Library - - Copyright (c) Marak Squires + async deleteKey(key = "") { + var deleted, instance; + instance = this.instances[key]; + if (this.connection) { + deleted = (await this.connection.__runCommand__(['del', ...Scripts$1.allKeys(`${this.id}-${key}`)])); + } + if (instance != null) { + delete this.instances[key]; + await instance.disconnect(); + } + return (instance != null) || deleted > 0; + } -Additional functionality - - Copyright (c) Sindre Sorhus (sindresorhus.com) + limiters() { + var k, ref, results, v; + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + results.push({ + key: k, + limiter: v + }); + } + return results; + } -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: + keys() { + return Object.keys(this.instances); + } -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. + async clusterKeys() { + var cursor, end, found, i, k, keys, len, next, start; + if (this.connection == null) { + return this.Promise.resolve(this.keys()); + } + keys = []; + cursor = null; + start = `b_${this.id}-`.length; + end = "_settings".length; + while (cursor !== 0) { + [next, found] = (await this.connection.__runCommand__(["scan", cursor != null ? cursor : 0, "match", `b_${this.id}-*_settings`, "count", 10000])); + cursor = ~~next; + for (i = 0, len = found.length; i < len; i++) { + k = found[i]; + keys.push(k.slice(start, -end)); + } + } + return keys; + } -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. + _startAutoCleanup() { + var base; + clearInterval(this.interval); + return typeof (base = (this.interval = setInterval(async() => { + var e, k, ref, results, time, v; + time = Date.now(); + ref = this.instances; + results = []; + for (k in ref) { + v = ref[k]; + try { + if ((await v._store.__groupCheck__(time))) { + results.push(this.deleteKey(k)); + } else { + results.push(void 0); + } + } catch (error) { + e = error; + results.push(v.Events.trigger("error", e)); + } + } + return results; + }, this.timeout / 2))).unref === "function" ? base.unref() : void 0; + } -*/ + updateSettings(options = {}) { + parser$3.overwrite(options, this.defaults, this); + parser$3.overwrite(options, options, this.limiterOptions); + if (options.timeout != null) { + return this._startAutoCleanup(); + } + } -var colors = {}; -module['exports'] = colors; + disconnect(flush = true) { + var ref; + if (!this.sharedConnection) { + return (ref = this.connection) != null ? ref.disconnect(flush) : void 0; + } + } -colors.themes = {}; + } + Group.prototype.defaults = { + timeout: 1000 * 60 * 5, + connection: null, + Promise: Promise, + id: "group-key" + }; -var util = __nccwpck_require__(31669); -var ansiStyles = colors.styles = __nccwpck_require__(73104); -var defineProps = Object.defineProperties; -var newLineRegex = new RegExp(/[\r\n]+/g); + return Group; -colors.supportsColor = __nccwpck_require__(10662).supportsColor; + }).call(commonjsGlobal); -if (typeof colors.enabled === 'undefined') { - colors.enabled = colors.supportsColor() !== false; -} + var Group_1 = Group; -colors.enable = function() { - colors.enabled = true; -}; + var Batcher, Events$3, parser$4; -colors.disable = function() { - colors.enabled = false; -}; + parser$4 = parser; -colors.stripColors = colors.strip = function(str) { - return ('' + str).replace(/\x1B\[\d+m/g, ''); -}; + Events$3 = Events_1; -// eslint-disable-next-line no-unused-vars -var stylize = colors.stylize = function stylize(str, style) { - if (!colors.enabled) { - return str+''; - } + Batcher = (function() { + class Batcher { + constructor(options = {}) { + this.options = options; + parser$4.load(this.options, this.defaults, this); + this.Events = new Events$3(this); + this._arr = []; + this._resetPromise(); + this._lastFlush = Date.now(); + } - var styleMap = ansiStyles[style]; + _resetPromise() { + return this._promise = new this.Promise((res, rej) => { + return this._resolve = res; + }); + } - // Stylize should work for non-ANSI styles, too - if(!styleMap && style in colors){ - // Style maps like trap operate as functions on strings; - // they don't have properties like open or close. - return colors[style](str); - } + _flush() { + clearTimeout(this._timeout); + this._lastFlush = Date.now(); + this._resolve(); + this.Events.trigger("batch", this._arr); + this._arr = []; + return this._resetPromise(); + } - return styleMap.open + str + styleMap.close; -}; + add(data) { + var ret; + this._arr.push(data); + ret = this._promise; + if (this._arr.length === this.maxSize) { + this._flush(); + } else if ((this.maxTime != null) && this._arr.length === 1) { + this._timeout = setTimeout(() => { + return this._flush(); + }, this.maxTime); + } + return ret; + } -var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; -var escapeStringRegexp = function(str) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - return str.replace(matchOperatorsRe, '\\$&'); -}; + } + Batcher.prototype.defaults = { + maxTime: null, + maxSize: null, + Promise: Promise + }; -function build(_styles) { - var builder = function builder() { - return applyStyle.apply(builder, arguments); - }; - builder._styles = _styles; - // __proto__ is used because we must return a function, but there is - // no way to create a function with a different prototype. - builder.__proto__ = proto; - return builder; -} + return Batcher; -var styles = (function() { - var ret = {}; - ansiStyles.grey = ansiStyles.gray; - Object.keys(ansiStyles).forEach(function(key) { - ansiStyles[key].closeRe = - new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); - ret[key] = { - get: function() { - return build(this._styles.concat(key)); - }, - }; - }); - return ret; -})(); + }).call(commonjsGlobal); -var proto = defineProps(function colors() {}, styles); + var Batcher_1 = Batcher; -function applyStyle() { - var args = Array.prototype.slice.call(arguments); + var require$$4$1 = () => console.log('You must import the full version of Bottleneck in order to use this feature.'); - var str = args.map(function(arg) { - // Use weak equality check so we can colorize null/undefined in safe mode - if (arg != null && arg.constructor === String) { - return arg; - } else { - return util.inspect(arg); - } - }).join(' '); + var require$$8 = getCjsExportFromNamespace(version$2); - if (!colors.enabled || !str) { - return str; - } + var Bottleneck, DEFAULT_PRIORITY$1, Events$4, Job$1, LocalDatastore$1, NUM_PRIORITIES$1, Queues$1, RedisDatastore$1, States$1, Sync$1, parser$5, + splice = [].splice; - var newLinesPresent = str.indexOf('\n') != -1; + NUM_PRIORITIES$1 = 10; - var nestedStyles = this._styles; + DEFAULT_PRIORITY$1 = 5; - var i = nestedStyles.length; - while (i--) { - var code = ansiStyles[nestedStyles[i]]; - str = code.open + str.replace(code.closeRe, code.open) + code.close; - if (newLinesPresent) { - str = str.replace(newLineRegex, function(match) { - return code.close + match + code.open; - }); - } - } + parser$5 = parser; - return str; -} + Queues$1 = Queues_1; -colors.setTheme = function(theme) { - if (typeof theme === 'string') { - console.log('colors.setTheme now only accepts an object, not a string. ' + - 'If you are trying to set a theme from a file, it is now your (the ' + - 'caller\'s) responsibility to require the file. The old syntax ' + - 'looked like colors.setTheme(__dirname + ' + - '\'/../themes/generic-logging.js\'); The new syntax looks like '+ - 'colors.setTheme(require(__dirname + ' + - '\'/../themes/generic-logging.js\'));'); - return; - } - for (var style in theme) { - (function(style) { - colors[style] = function(str) { - if (typeof theme[style] === 'object') { - var out = str; - for (var i in theme[style]) { - out = colors[theme[style][i]](out); - } - return out; - } - return colors[theme[style]](str); - }; - })(style); - } -}; + Job$1 = Job_1; -function init() { - var ret = {}; - Object.keys(styles).forEach(function(name) { - ret[name] = { - get: function() { - return build([name]); - }, - }; - }); - return ret; -} + LocalDatastore$1 = LocalDatastore_1; -var sequencer = function sequencer(map, str) { - var exploded = str.split(''); - exploded = exploded.map(map); - return exploded.join(''); -}; + RedisDatastore$1 = require$$4$1; -// custom formatter methods -colors.trap = __nccwpck_require__(31302); -colors.zalgo = __nccwpck_require__(45610); + Events$4 = Events_1; -// maps -colors.maps = {}; -colors.maps.america = __nccwpck_require__(76936)(colors); -colors.maps.zebra = __nccwpck_require__(12989)(colors); -colors.maps.rainbow = __nccwpck_require__(75210)(colors); -colors.maps.random = __nccwpck_require__(13441)(colors); + States$1 = States_1; -for (var map in colors.maps) { - (function(map) { - colors[map] = function(str) { - return sequencer(colors.maps[map], str); - }; - })(map); -} + Sync$1 = Sync_1; -defineProps(colors, init()); + Bottleneck = (function() { + class Bottleneck { + constructor(options = {}, ...invalid) { + var storeInstanceOptions, storeOptions; + this._addToQueue = this._addToQueue.bind(this); + this._validateOptions(options, invalid); + parser$5.load(options, this.instanceDefaults, this); + this._queues = new Queues$1(NUM_PRIORITIES$1); + this._scheduled = {}; + this._states = new States$1(["RECEIVED", "QUEUED", "RUNNING", "EXECUTING"].concat(this.trackDoneStatus ? ["DONE"] : [])); + this._limiter = null; + this.Events = new Events$4(this); + this._submitLock = new Sync$1("submit", this.Promise); + this._registerLock = new Sync$1("register", this.Promise); + storeOptions = parser$5.load(options, this.storeDefaults, {}); + this._store = (function() { + if (this.datastore === "redis" || this.datastore === "ioredis" || (this.connection != null)) { + storeInstanceOptions = parser$5.load(options, this.redisStoreDefaults, {}); + return new RedisDatastore$1(this, storeOptions, storeInstanceOptions); + } else if (this.datastore === "local") { + storeInstanceOptions = parser$5.load(options, this.localStoreDefaults, {}); + return new LocalDatastore$1(this, storeOptions, storeInstanceOptions); + } else { + throw new Bottleneck.prototype.BottleneckError(`Invalid datastore type: ${this.datastore}`); + } + }).call(this); + this._queues.on("leftzero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.ref === "function" ? ref.ref() : void 0 : void 0; + }); + this._queues.on("zero", () => { + var ref; + return (ref = this._store.heartbeat) != null ? typeof ref.unref === "function" ? ref.unref() : void 0 : void 0; + }); + } + _validateOptions(options, invalid) { + if (!((options != null) && typeof options === "object" && invalid.length === 0)) { + throw new Bottleneck.prototype.BottleneckError("Bottleneck v2 takes a single object argument. Refer to https://github.com/SGrondin/bottleneck#upgrading-to-v2 if you're upgrading from Bottleneck v1."); + } + } -/***/ }), + ready() { + return this._store.ready; + } -/***/ 31302: -/***/ ((module) => { + clients() { + return this._store.clients; + } -module['exports'] = function runTheTrap(text, options) { - var result = ''; - text = text || 'Run the trap, drop the bass'; - text = text.split(''); - var trap = { - a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'], - b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'], - c: ['\u00a9', '\u023b', '\u03fe'], - d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'], - e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc', - '\u0a6c'], - f: ['\u04fa'], - g: ['\u0262'], - h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'], - i: ['\u0f0f'], - j: ['\u0134'], - k: ['\u0138', '\u04a0', '\u04c3', '\u051e'], - l: ['\u0139'], - m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'], - n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'], - o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd', - '\u06dd', '\u0e4f'], - p: ['\u01f7', '\u048e'], - q: ['\u09cd'], - r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'], - s: ['\u00a7', '\u03de', '\u03df', '\u03e8'], - t: ['\u0141', '\u0166', '\u0373'], - u: ['\u01b1', '\u054d'], - v: ['\u05d8'], - w: ['\u0428', '\u0460', '\u047c', '\u0d70'], - x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'], - y: ['\u00a5', '\u04b0', '\u04cb'], - z: ['\u01b5', '\u0240'], - }; - text.forEach(function(c) { - c = c.toLowerCase(); - var chars = trap[c] || [' ']; - var rand = Math.floor(Math.random() * chars.length); - if (typeof trap[c] !== 'undefined') { - result += trap[c][rand]; - } else { - result += c; - } - }); - return result; -}; + channel() { + return `b_${this.id}`; + } + channel_client() { + return `b_${this.id}_${this._store.clientId}`; + } -/***/ }), + publish(message) { + return this._store.__publish__(message); + } -/***/ 45610: -/***/ ((module) => { + disconnect(flush = true) { + return this._store.__disconnect__(flush); + } -// please no -module['exports'] = function zalgo(text, options) { - text = text || ' he is here '; - var soul = { - 'up': [ - '̍', '̎', '̄', '̅', - '̿', '̑', '̆', '̐', - '͒', '͗', '͑', '̇', - '̈', '̊', '͂', '̓', - '̈', '͊', '͋', '͌', - '̃', '̂', '̌', '͐', - '̀', '́', '̋', '̏', - '̒', '̓', '̔', '̽', - '̉', 'ͣ', 'ͤ', 'ͥ', - 'ͦ', 'ͧ', 'ͨ', 'ͩ', - 'ͪ', 'ͫ', 'ͬ', 'ͭ', - 'ͮ', 'ͯ', '̾', '͛', - '͆', '̚', - ], - 'down': [ - '̖', '̗', '̘', '̙', - '̜', '̝', '̞', '̟', - '̠', '̤', '̥', '̦', - '̩', '̪', '̫', '̬', - '̭', '̮', '̯', '̰', - '̱', '̲', '̳', '̹', - '̺', '̻', '̼', 'ͅ', - '͇', '͈', '͉', '͍', - '͎', '͓', '͔', '͕', - '͖', '͙', '͚', '̣', - ], - 'mid': [ - '̕', '̛', '̀', '́', - '͘', '̡', '̢', '̧', - '̨', '̴', '̵', '̶', - '͜', '͝', '͞', - '͟', '͠', '͢', '̸', - '̷', '͡', ' ҉', - ], - }; - var all = [].concat(soul.up, soul.down, soul.mid); + chain(_limiter) { + this._limiter = _limiter; + return this; + } - function randomNumber(range) { - var r = Math.floor(Math.random() * range); - return r; - } + queued(priority) { + return this._queues.queued(priority); + } - function isChar(character) { - var bool = false; - all.filter(function(i) { - bool = (i === character); - }); - return bool; - } + clusterQueued() { + return this._store.__queued__(); + } + empty() { + return this.queued() === 0 && this._submitLock.isEmpty(); + } - function heComes(text, options) { - var result = ''; - var counts; - var l; - options = options || {}; - options['up'] = - typeof options['up'] !== 'undefined' ? options['up'] : true; - options['mid'] = - typeof options['mid'] !== 'undefined' ? options['mid'] : true; - options['down'] = - typeof options['down'] !== 'undefined' ? options['down'] : true; - options['size'] = - typeof options['size'] !== 'undefined' ? options['size'] : 'maxi'; - text = text.split(''); - for (l in text) { - if (isChar(l)) { - continue; - } - result = result + text[l]; - counts = {'up': 0, 'down': 0, 'mid': 0}; - switch (options.size) { - case 'mini': - counts.up = randomNumber(8); - counts.mid = randomNumber(2); - counts.down = randomNumber(8); - break; - case 'maxi': - counts.up = randomNumber(16) + 3; - counts.mid = randomNumber(4) + 1; - counts.down = randomNumber(64) + 3; - break; - default: - counts.up = randomNumber(8) + 1; - counts.mid = randomNumber(6) / 2; - counts.down = randomNumber(8) + 1; - break; - } + running() { + return this._store.__running__(); + } - var arr = ['up', 'mid', 'down']; - for (var d in arr) { - var index = arr[d]; - for (var i = 0; i <= counts[index]; i++) { - if (options[index]) { - result = result + soul[index][randomNumber(soul[index].length)]; - } - } - } - } - return result; - } - // don't summon him - return heComes(text, options); -}; + done() { + return this._store.__done__(); + } + jobStatus(id) { + return this._states.jobStatus(id); + } + jobs(status) { + return this._states.statusJobs(status); + } -/***/ }), + counts() { + return this._states.statusCounts(); + } -/***/ 76936: -/***/ ((module) => { + _randomIndex() { + return Math.random().toString(36).slice(2); + } -module['exports'] = function(colors) { - return function(letter, i, exploded) { - if (letter === ' ') return letter; - switch (i%3) { - case 0: return colors.red(letter); - case 1: return colors.white(letter); - case 2: return colors.blue(letter); - } - }; -}; + check(weight = 1) { + return this._store.__check__(weight); + } + _clearGlobalState(index) { + if (this._scheduled[index] != null) { + clearTimeout(this._scheduled[index].expiration); + delete this._scheduled[index]; + return true; + } else { + return false; + } + } -/***/ }), + async _free(index, job, options, eventInfo) { + var e, running; + try { + ({running} = (await this._store.__free__(index, options.weight))); + this.Events.trigger("debug", `Freed ${options.id}`, eventInfo); + if (running === 0 && this.empty()) { + return this.Events.trigger("idle"); + } + } catch (error1) { + e = error1; + return this.Events.trigger("error", e); + } + } -/***/ 75210: -/***/ ((module) => { + _run(index, job, wait) { + var clearGlobalState, free, run; + job.doRun(); + clearGlobalState = this._clearGlobalState.bind(this, index); + run = this._run.bind(this, index, job); + free = this._free.bind(this, index, job); + return this._scheduled[index] = { + timeout: setTimeout(() => { + return job.doExecute(this._limiter, clearGlobalState, run, free); + }, wait), + expiration: job.options.expiration != null ? setTimeout(function() { + return job.doExpire(clearGlobalState, run, free); + }, wait + job.options.expiration) : void 0, + job: job + }; + } -module['exports'] = function(colors) { - // RoY G BiV - var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; - return function(letter, i, exploded) { - if (letter === ' ') { - return letter; - } else { - return colors[rainbowColors[i++ % rainbowColors.length]](letter); - } - }; -}; + _drainOne(capacity) { + return this._registerLock.schedule(() => { + var args, index, next, options, queue; + if (this.queued() === 0) { + return this.Promise.resolve(null); + } + queue = this._queues.getFirst(); + ({options, args} = next = queue.first()); + if ((capacity != null) && options.weight > capacity) { + return this.Promise.resolve(null); + } + this.Events.trigger("debug", `Draining ${options.id}`, {args, options}); + index = this._randomIndex(); + return this._store.__register__(index, options.weight, options.expiration).then(({success, wait, reservoir}) => { + var empty; + this.Events.trigger("debug", `Drained ${options.id}`, {success, args, options}); + if (success) { + queue.shift(); + empty = this.empty(); + if (empty) { + this.Events.trigger("empty"); + } + if (reservoir === 0) { + this.Events.trigger("depleted", empty); + } + this._run(index, next, wait); + return this.Promise.resolve(options.weight); + } else { + return this.Promise.resolve(null); + } + }); + }); + } + _drainAll(capacity, total = 0) { + return this._drainOne(capacity).then((drained) => { + var newCapacity; + if (drained != null) { + newCapacity = capacity != null ? capacity - drained : capacity; + return this._drainAll(newCapacity, total + drained); + } else { + return this.Promise.resolve(total); + } + }).catch((e) => { + return this.Events.trigger("error", e); + }); + } + _dropAllQueued(message) { + return this._queues.shiftAll(function(job) { + return job.doDrop({message}); + }); + } -/***/ }), + stop(options = {}) { + var done, waitForExecuting; + options = parser$5.load(options, this.stopDefaults); + waitForExecuting = (at) => { + var finished; + finished = () => { + var counts; + counts = this._states.counts; + return (counts[0] + counts[1] + counts[2] + counts[3]) === at; + }; + return new this.Promise((resolve, reject) => { + if (finished()) { + return resolve(); + } else { + return this.on("done", () => { + if (finished()) { + this.removeAllListeners("done"); + return resolve(); + } + }); + } + }); + }; + done = options.dropWaitingJobs ? (this._run = function(index, next) { + return next.doDrop({ + message: options.dropErrorMessage + }); + }, this._drainOne = () => { + return this.Promise.resolve(null); + }, this._registerLock.schedule(() => { + return this._submitLock.schedule(() => { + var k, ref, v; + ref = this._scheduled; + for (k in ref) { + v = ref[k]; + if (this.jobStatus(v.job.options.id) === "RUNNING") { + clearTimeout(v.timeout); + clearTimeout(v.expiration); + v.job.doDrop({ + message: options.dropErrorMessage + }); + } + } + this._dropAllQueued(options.dropErrorMessage); + return waitForExecuting(0); + }); + })) : this.schedule({ + priority: NUM_PRIORITIES$1 - 1, + weight: 0 + }, () => { + return waitForExecuting(1); + }); + this._receive = function(job) { + return job._reject(new Bottleneck.prototype.BottleneckError(options.enqueueErrorMessage)); + }; + this.stop = () => { + return this.Promise.reject(new Bottleneck.prototype.BottleneckError("stop() has already been called")); + }; + return done; + } -/***/ 13441: -/***/ ((module) => { + async _addToQueue(job) { + var args, blocked, error, options, reachedHWM, shifted, strategy; + ({args, options} = job); + try { + ({reachedHWM, blocked, strategy} = (await this._store.__submit__(this.queued(), options.weight))); + } catch (error1) { + error = error1; + this.Events.trigger("debug", `Could not queue ${options.id}`, {args, options, error}); + job.doDrop({error}); + return false; + } + if (blocked) { + job.doDrop(); + return true; + } else if (reachedHWM) { + shifted = strategy === Bottleneck.prototype.strategy.LEAK ? this._queues.shiftLastFrom(options.priority) : strategy === Bottleneck.prototype.strategy.OVERFLOW_PRIORITY ? this._queues.shiftLastFrom(options.priority + 1) : strategy === Bottleneck.prototype.strategy.OVERFLOW ? job : void 0; + if (shifted != null) { + shifted.doDrop(); + } + if ((shifted == null) || strategy === Bottleneck.prototype.strategy.OVERFLOW) { + if (shifted == null) { + job.doDrop(); + } + return reachedHWM; + } + } + job.doQueue(reachedHWM, blocked); + this._queues.push(job); + await this._drainAll(); + return reachedHWM; + } -module['exports'] = function(colors) { - var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', - 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed', - 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta']; - return function(letter, i, exploded) { - return letter === ' ' ? letter : - colors[ - available[Math.round(Math.random() * (available.length - 2))] - ](letter); - }; -}; + _receive(job) { + if (this._states.jobStatus(job.options.id) != null) { + job._reject(new Bottleneck.prototype.BottleneckError(`A job with the same id already exists (id=${job.options.id})`)); + return false; + } else { + job.doReceive(); + return this._submitLock.schedule(this._addToQueue, job); + } + } + submit(...args) { + var cb, fn, job, options, ref, ref1, task; + if (typeof args[0] === "function") { + ref = args, [fn, ...args] = ref, [cb] = splice.call(args, -1); + options = parser$5.load({}, this.jobDefaults); + } else { + ref1 = args, [options, fn, ...args] = ref1, [cb] = splice.call(args, -1); + options = parser$5.load(options, this.jobDefaults); + } + task = (...args) => { + return new this.Promise(function(resolve, reject) { + return fn(...args, function(...args) { + return (args[0] != null ? reject : resolve)(args); + }); + }); + }; + job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + job.promise.then(function(args) { + return typeof cb === "function" ? cb(...args) : void 0; + }).catch(function(args) { + if (Array.isArray(args)) { + return typeof cb === "function" ? cb(...args) : void 0; + } else { + return typeof cb === "function" ? cb(args) : void 0; + } + }); + return this._receive(job); + } -/***/ }), + schedule(...args) { + var job, options, task; + if (typeof args[0] === "function") { + [task, ...args] = args; + options = {}; + } else { + [options, task, ...args] = args; + } + job = new Job$1(task, args, options, this.jobDefaults, this.rejectOnDrop, this.Events, this._states, this.Promise); + this._receive(job); + return job.promise; + } -/***/ 12989: -/***/ ((module) => { + wrap(fn) { + var schedule, wrapped; + schedule = this.schedule.bind(this); + wrapped = function(...args) { + return schedule(fn.bind(this), ...args); + }; + wrapped.withOptions = function(options, ...args) { + return schedule(options, fn, ...args); + }; + return wrapped; + } -module['exports'] = function(colors) { - return function(letter, i, exploded) { - return i % 2 === 0 ? letter : colors.inverse(letter); - }; -}; + async updateSettings(options = {}) { + await this._store.__updateSettings__(parser$5.overwrite(options, this.storeDefaults)); + parser$5.overwrite(options, this.instanceDefaults, this); + return this; + } + currentReservoir() { + return this._store.__currentReservoir__(); + } -/***/ }), + incrementReservoir(incr = 0) { + return this._store.__incrementReservoir__(incr); + } -/***/ 73104: -/***/ ((module) => { + } + Bottleneck.default = Bottleneck; -/* -The MIT License (MIT) + Bottleneck.Events = Events$4; -Copyright (c) Sindre Sorhus (sindresorhus.com) + Bottleneck.version = Bottleneck.prototype.version = require$$8.version; -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: + Bottleneck.strategy = Bottleneck.prototype.strategy = { + LEAK: 1, + OVERFLOW: 2, + OVERFLOW_PRIORITY: 4, + BLOCK: 3 + }; -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. + Bottleneck.BottleneckError = Bottleneck.prototype.BottleneckError = BottleneckError_1; -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. + Bottleneck.Group = Bottleneck.prototype.Group = Group_1; -*/ + Bottleneck.RedisConnection = Bottleneck.prototype.RedisConnection = require$$2; -var styles = {}; -module['exports'] = styles; + Bottleneck.IORedisConnection = Bottleneck.prototype.IORedisConnection = require$$3; -var codes = { - reset: [0, 0], + Bottleneck.Batcher = Bottleneck.prototype.Batcher = Batcher_1; - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29], + Bottleneck.prototype.jobDefaults = { + priority: DEFAULT_PRIORITY$1, + weight: 1, + expiration: null, + id: "" + }; - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - gray: [90, 39], - grey: [90, 39], + Bottleneck.prototype.storeDefaults = { + maxConcurrent: null, + minTime: 0, + highWater: null, + strategy: Bottleneck.prototype.strategy.LEAK, + penalty: null, + reservoir: null, + reservoirRefreshInterval: null, + reservoirRefreshAmount: null, + reservoirIncreaseInterval: null, + reservoirIncreaseAmount: null, + reservoirIncreaseMaximum: null + }; - brightRed: [91, 39], - brightGreen: [92, 39], - brightYellow: [93, 39], - brightBlue: [94, 39], - brightMagenta: [95, 39], - brightCyan: [96, 39], - brightWhite: [97, 39], + Bottleneck.prototype.localStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 250 + }; - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - bgGray: [100, 49], - bgGrey: [100, 49], + Bottleneck.prototype.redisStoreDefaults = { + Promise: Promise, + timeout: null, + heartbeatInterval: 5000, + clientTimeout: 10000, + Redis: null, + clientOptions: {}, + clusterNodes: null, + clearDatastore: false, + connection: null + }; - bgBrightRed: [101, 49], - bgBrightGreen: [102, 49], - bgBrightYellow: [103, 49], - bgBrightBlue: [104, 49], - bgBrightMagenta: [105, 49], - bgBrightCyan: [106, 49], - bgBrightWhite: [107, 49], + Bottleneck.prototype.instanceDefaults = { + datastore: "local", + connection: null, + id: "", + rejectOnDrop: true, + trackDoneStatus: false, + Promise: Promise + }; - // legacy styles for colors pre v1.0.0 - blackBG: [40, 49], - redBG: [41, 49], - greenBG: [42, 49], - yellowBG: [43, 49], - blueBG: [44, 49], - magentaBG: [45, 49], - cyanBG: [46, 49], - whiteBG: [47, 49], + Bottleneck.prototype.stopDefaults = { + enqueueErrorMessage: "This limiter has been stopped and cannot accept new jobs.", + dropWaitingJobs: true, + dropErrorMessage: "This limiter has been stopped." + }; -}; + return Bottleneck; -Object.keys(codes).forEach(function(key) { - var val = codes[key]; - var style = styles[key] = []; - style.open = '\u001b[' + val[0] + 'm'; - style.close = '\u001b[' + val[1] + 'm'; -}); + }).call(commonjsGlobal); + + var Bottleneck_1 = Bottleneck; + + var lib = Bottleneck_1; + + return lib; + +}))); + + +/***/ }), + +/***/ 72358: +/***/ ((module) => { + +module.exports = function btoa(str) { + return new Buffer(str).toString('base64') +} /***/ }), -/***/ 10223: -/***/ ((module) => { +/***/ 9239: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/* -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) +/*jshint node:true */ -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: +var Buffer = __nccwpck_require__(64293).Buffer; // browserify +var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. +module.exports = bufferEq; -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. -*/ +function bufferEq(a, b) { + // shortcutting on type is necessary for correctness + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + return false; + } + // buffer sizes should be well-known information, so despite this + // shortcutting, it doesn't leak any information about the *contents* of the + // buffers. + if (a.length !== b.length) { + return false; + } -module.exports = function(flag, argv) { - argv = argv || process.argv; + var c = 0; + for (var i = 0; i < a.length; i++) { + /*jshint bitwise:false */ + c |= a[i] ^ b[i]; // XOR + } + return c === 0; +} - var terminatorPos = argv.indexOf('--'); - var prefix = /^-{1,2}/.test(flag) ? '' : '--'; - var pos = argv.indexOf(prefix + flag); +bufferEq.install = function() { + Buffer.prototype.equal = SlowBuffer.prototype.equal = function equal(that) { + return bufferEq(this, that); + }; +}; - return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +var origBufEqual = Buffer.prototype.equal; +var origSlowBufEqual = SlowBuffer.prototype.equal; +bufferEq.restore = function() { + Buffer.prototype.equal = origBufEqual; + SlowBuffer.prototype.equal = origSlowBufEqual; }; /***/ }), -/***/ 10662: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 86966: +/***/ ((module) => { "use strict"; -/* -The MIT License (MIT) +/*! + * bytes + * Copyright(c) 2012-2014 TJ Holowaychuk + * Copyright(c) 2015 Jed Watson + * MIT Licensed + */ -Copyright (c) Sindre Sorhus (sindresorhus.com) -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. +/** + * Module exports. + * @public + */ -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. +module.exports = bytes; +module.exports.format = format; +module.exports.parse = parse; -*/ +/** + * Module variables. + * @private + */ +var formatThousandsRegExp = /\B(?=(\d{3})+(?!\d))/g; +var formatDecimalsRegExp = /(?:\.0*|(\.[^0]+)0+)$/; -var os = __nccwpck_require__(12087); -var hasFlag = __nccwpck_require__(10223); +var map = { + b: 1, + kb: 1 << 10, + mb: 1 << 20, + gb: 1 << 30, + tb: Math.pow(1024, 4), + pb: Math.pow(1024, 5), +}; -var env = process.env; +var parseRegExp = /^((-|\+)?(\d+(?:\.\d+)?)) *(kb|mb|gb|tb|pb)$/i; -var forceColor = void 0; -if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { - forceColor = false; -} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') - || hasFlag('color=always')) { - forceColor = true; -} -if ('FORCE_COLOR' in env) { - forceColor = env.FORCE_COLOR.length === 0 - || parseInt(env.FORCE_COLOR, 10) !== 0; -} +/** + * Convert the given value in bytes into a string or parse to string to an integer in bytes. + * + * @param {string|number} value + * @param {{ + * case: [string], + * decimalPlaces: [number] + * fixedDecimals: [boolean] + * thousandsSeparator: [string] + * unitSeparator: [string] + * }} [options] bytes options. + * + * @returns {string|number|null} + */ -function translateLevel(level) { - if (level === 0) { - return false; +function bytes(value, options) { + if (typeof value === 'string') { + return parse(value); } - return { - level: level, - hasBasic: true, - has256: level >= 2, - has16m: level >= 3, - }; -} - -function supportsColor(stream) { - if (forceColor === false) { - return 0; + if (typeof value === 'number') { + return format(value, options); } - if (hasFlag('color=16m') || hasFlag('color=full') - || hasFlag('color=truecolor')) { - return 3; - } + return null; +} - if (hasFlag('color=256')) { - return 2; - } +/** + * Format the given value in bytes into a string. + * + * If the value is negative, it is kept as such. If it is a float, + * it is rounded. + * + * @param {number} value + * @param {object} [options] + * @param {number} [options.decimalPlaces=2] + * @param {number} [options.fixedDecimals=false] + * @param {string} [options.thousandsSeparator=] + * @param {string} [options.unit=] + * @param {string} [options.unitSeparator=] + * + * @returns {string|null} + * @public + */ - if (stream && !stream.isTTY && forceColor !== true) { - return 0; +function format(value, options) { + if (!Number.isFinite(value)) { + return null; } - var min = forceColor ? 1 : 0; + var mag = Math.abs(value); + var thousandsSeparator = (options && options.thousandsSeparator) || ''; + var unitSeparator = (options && options.unitSeparator) || ''; + var decimalPlaces = (options && options.decimalPlaces !== undefined) ? options.decimalPlaces : 2; + var fixedDecimals = Boolean(options && options.fixedDecimals); + var unit = (options && options.unit) || ''; - if (process.platform === 'win32') { - // Node.js 7.5.0 is the first version of Node.js to include a patch to - // libuv that enables 256 color output on Windows. Anything earlier and it - // won't work. However, here we target Node.js 8 at minimum as it is an LTS - // release, and Node.js 7 is not. Windows 10 build 10586 is the first - // Windows release that supports 256 colors. Windows 10 build 14931 is the - // first release that supports 16m/TrueColor. - var osRelease = os.release().split('.'); - if (Number(process.versions.node.split('.')[0]) >= 8 - && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { - return Number(osRelease[2]) >= 14931 ? 3 : 2; + if (!unit || !map[unit.toLowerCase()]) { + if (mag >= map.pb) { + unit = 'PB'; + } else if (mag >= map.tb) { + unit = 'TB'; + } else if (mag >= map.gb) { + unit = 'GB'; + } else if (mag >= map.mb) { + unit = 'MB'; + } else if (mag >= map.kb) { + unit = 'KB'; + } else { + unit = 'B'; } - - return 1; } - if ('CI' in env) { - if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) { - return sign in env; - }) || env.CI_NAME === 'codeship') { - return 1; - } + var val = value / map[unit.toLowerCase()]; + var str = val.toFixed(decimalPlaces); - return min; + if (!fixedDecimals) { + str = str.replace(formatDecimalsRegExp, '$1'); } - if ('TEAMCITY_VERSION' in env) { - return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0 - ); + if (thousandsSeparator) { + str = str.replace(formatThousandsRegExp, thousandsSeparator); } - if ('TERM_PROGRAM' in env) { - var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); + return str + unitSeparator + unit; +} - switch (env.TERM_PROGRAM) { - case 'iTerm.app': - return version >= 3 ? 3 : 2; - case 'Hyper': - return 3; - case 'Apple_Terminal': - return 2; - // No default - } - } +/** + * Parse the string value into an integer in bytes. + * + * If no unit is given, it is assumed the value is in bytes. + * + * @param {number|string} val + * + * @returns {number|null} + * @public + */ - if (/-256(color)?$/i.test(env.TERM)) { - return 2; +function parse(val) { + if (typeof val === 'number' && !isNaN(val)) { + return val; } - if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { - return 1; + if (typeof val !== 'string') { + return null; } - if ('COLORTERM' in env) { - return 1; - } + // Test if the string passed is valid + var results = parseRegExp.exec(val); + var floatValue; + var unit = 'b'; - if (env.TERM === 'dumb') { - return min; + if (!results) { + // Nothing could be extracted from the given string + floatValue = parseInt(val, 10); + unit = 'b' + } else { + // Retrieve the value and the unit + floatValue = parseFloat(results[1]); + unit = results[4].toLowerCase(); } - return min; -} - -function getSupportLevel(stream) { - var level = supportsColor(stream); - return translateLevel(level); + return Math.floor(map[unit] * floatValue); } -module.exports = { - supportsColor: getSupportLevel, - stdout: getSupportLevel(process.stdout), - stderr: getSupportLevel(process.stderr), -}; - /***/ }), -/***/ 41997: +/***/ 28803: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// -// Remark: Requiring this file will use the "safe" colors API, -// which will not touch String.prototype. -// -// var colors = require('colors/safe'); -// colors.red("foo") -// -// -var colors = __nccwpck_require__(43595); -module['exports'] = colors; - - -/***/ }), - -/***/ 89296: -/***/ (function(module) { - -/* global define */ -(function (root, factory) { - /* istanbul ignore next */ - if (typeof define === 'function' && define.amd) { - define([], factory); - } else if (true) { - module.exports = factory(); - } else {} -}(this, function () { - - var semver = /^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i; - - function indexOrEnd(str, q) { - return str.indexOf(q) === -1 ? str.length : str.indexOf(q); - } - - function split(v) { - var c = v.replace(/^v/, '').replace(/\+.*$/, ''); - var patchIndex = indexOrEnd(c, '-'); - var arr = c.substring(0, patchIndex).split('.'); - arr.push(c.substring(patchIndex + 1)); - return arr; - } - - function tryParse(v) { - return isNaN(Number(v)) ? v : Number(v); - } +"use strict"; - function validate(version) { - if (typeof version !== 'string') { - throw new TypeError('Invalid argument expected string'); - } - if (!semver.test(version)) { - throw new Error('Invalid argument not valid semver (\''+version+'\' received)'); - } - } - function compareVersions(v1, v2) { - [v1, v2].forEach(validate); +var GetIntrinsic = __nccwpck_require__(74538); - var s1 = split(v1); - var s2 = split(v2); +var callBind = __nccwpck_require__(62977); - for (var i = 0; i < Math.max(s1.length - 1, s2.length - 1); i++) { - var n1 = parseInt(s1[i] || 0, 10); - var n2 = parseInt(s2[i] || 0, 10); +var $indexOf = callBind(GetIntrinsic('String.prototype.indexOf')); - if (n1 > n2) return 1; - if (n2 > n1) return -1; - } +module.exports = function callBoundIntrinsic(name, allowMissing) { + var intrinsic = GetIntrinsic(name, !!allowMissing); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBind(intrinsic); + } + return intrinsic; +}; - var sp1 = s1[s1.length - 1]; - var sp2 = s2[s2.length - 1]; - if (sp1 && sp2) { - var p1 = sp1.split('.').map(tryParse); - var p2 = sp2.split('.').map(tryParse); +/***/ }), - for (i = 0; i < Math.max(p1.length, p2.length); i++) { - if (p1[i] === undefined || typeof p2[i] === 'string' && typeof p1[i] === 'number') return -1; - if (p2[i] === undefined || typeof p1[i] === 'string' && typeof p2[i] === 'number') return 1; +/***/ 62977: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (p1[i] > p2[i]) return 1; - if (p2[i] > p1[i]) return -1; - } - } else if (sp1 || sp2) { - return sp1 ? -1 : 1; - } +"use strict"; - return 0; - }; - var allowedOperators = [ - '>', - '>=', - '=', - '<', - '<=' - ]; +var bind = __nccwpck_require__(88334); +var GetIntrinsic = __nccwpck_require__(74538); - var operatorResMap = { - '>': [1], - '>=': [0, 1], - '=': [0], - '<=': [-1, 0], - '<': [-1] - }; +var $apply = GetIntrinsic('%Function.prototype.apply%'); +var $call = GetIntrinsic('%Function.prototype.call%'); +var $reflectApply = GetIntrinsic('%Reflect.apply%', true) || bind.call($call, $apply); - function validateOperator(op) { - if (typeof op !== 'string') { - throw new TypeError('Invalid operator type, expected string but got ' + typeof op); - } - if (allowedOperators.indexOf(op) === -1) { - throw new TypeError('Invalid operator, expected one of ' + allowedOperators.join('|')); - } - } +var $gOPD = GetIntrinsic('%Object.getOwnPropertyDescriptor%', true); +var $defineProperty = GetIntrinsic('%Object.defineProperty%', true); +var $max = GetIntrinsic('%Math.max%'); - compareVersions.validate = function(version) { - return typeof version === 'string' && semver.test(version); - } +if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = null; + } +} - compareVersions.compare = function (v1, v2, operator) { - // Validate operator - validateOperator(operator); +module.exports = function callBind(originalFunction) { + var func = $reflectApply(bind, $call, arguments); + if ($gOPD && $defineProperty) { + var desc = $gOPD(func, 'length'); + if (desc.configurable) { + // original length, plus the receiver, minus any additional arguments (after the receiver) + $defineProperty( + func, + 'length', + { value: 1 + $max(0, originalFunction.length - (arguments.length - 1)) } + ); + } + } + return func; +}; - // since result of compareVersions can only be -1 or 0 or 1 - // a simple map can be used to replace switch - var res = compareVersions(v1, v2); - return operatorResMap[operator].indexOf(res) > -1; - } +var applyBind = function applyBind() { + return $reflectApply(bind, $apply, arguments); +}; - return compareVersions; -})); +if ($defineProperty) { + $defineProperty(module.exports, 'apply', { value: applyBind }); +} else { + module.exports.apply = applyBind; +} /***/ }), -/***/ 53921: +/***/ 27972: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/*! - * content-disposition - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module exports. - * @public - */ - -module.exports = contentDisposition -module.exports.parse = parse - -/** - * Module dependencies. - * @private - */ -var basename = __nccwpck_require__(85622).basename -var Buffer = __nccwpck_require__(21867).Buffer +const os = __nccwpck_require__(12087); -/** - * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") - * @private - */ +const extractPathRegex = /\s+at.*(?:\(|\s)(.*)\)?/; +const pathRegex = /^(?:(?:(?:node|(?:internal\/[\w/]*|.*node_modules\/(?:babel-polyfill|pirates)\/.*)?\w+)\.js:\d+:\d+)|native)/; +const homeDir = typeof os.homedir === 'undefined' ? '' : os.homedir(); -var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex +module.exports = (stack, options) => { + options = Object.assign({pretty: false}, options); -/** - * RegExp to match percent encoding escape. - * @private - */ + return stack.replace(/\\/g, '/') + .split('\n') + .filter(line => { + const pathMatches = line.match(extractPathRegex); + if (pathMatches === null || !pathMatches[1]) { + return true; + } -var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ -var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g + const match = pathMatches[1]; -/** - * RegExp to match non-latin1 characters. - * @private - */ + // Electron + if ( + match.includes('.app/Contents/Resources/electron.asar') || + match.includes('.app/Contents/Resources/default_app.asar') + ) { + return false; + } -var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g + return !pathRegex.test(match); + }) + .filter(line => line.trim() !== '') + .map(line => { + if (options.pretty) { + return line.replace(extractPathRegex, (m, p1) => m.replace(p1, p1.replace(homeDir, '~'))); + } -/** - * RegExp to match quoted-pair in RFC 2616 - * - * quoted-pair = "\" CHAR - * CHAR = - * @private - */ + return line; + }) + .join('\n'); +}; -var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex -/** - * RegExp to match chars that must be quoted-pair in RFC 2616 - * @private - */ +/***/ }), -var QUOTE_REGEXP = /([\\"])/g +/***/ 2101: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * RegExp for various RFC 2616 grammar - * - * parameter = token "=" ( token | quoted-string ) - * token = 1* - * separators = "(" | ")" | "<" | ">" | "@" - * | "," | ";" | ":" | "\" | <"> - * | "/" | "[" | "]" | "?" | "=" - * | "{" | "}" | SP | HT - * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) - * qdtext = > - * quoted-pair = "\" CHAR - * CHAR = - * TEXT = - * LWS = [CRLF] 1*( SP | HT ) - * CRLF = CR LF - * CR = - * LF = - * SP = - * HT = - * CTL = - * OCTET = - * @private - */ +module.exports = __nccwpck_require__(16136); -var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex -var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ -var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ +/***/ }), -/** - * RegExp for various RFC 5987 grammar - * - * ext-value = charset "'" [ language ] "'" value-chars - * charset = "UTF-8" / "ISO-8859-1" / mime-charset - * mime-charset = 1*mime-charsetc - * mime-charsetc = ALPHA / DIGIT - * / "!" / "#" / "$" / "%" / "&" - * / "+" / "-" / "^" / "_" / "`" - * / "{" / "}" / "~" - * language = ( 2*3ALPHA [ extlang ] ) - * / 4ALPHA - * / 5*8ALPHA - * extlang = *3( "-" 3ALPHA ) - * value-chars = *( pct-encoded / attr-char ) - * pct-encoded = "%" HEXDIG HEXDIG - * attr-char = ALPHA / DIGIT - * / "!" / "#" / "$" / "&" / "+" / "-" / "." - * / "^" / "_" / "`" / "|" / "~" - * @private - */ +/***/ 66168: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ +const utils = __nccwpck_require__(98911); -/** - * RegExp for various RFC 6266 grammar - * - * disposition-type = "inline" | "attachment" | disp-ext-type - * disp-ext-type = token - * disposition-parm = filename-parm | disp-ext-parm - * filename-parm = "filename" "=" value - * | "filename*" "=" ext-value - * disp-ext-parm = token "=" value - * | ext-token "=" ext-value - * ext-token = - * @private - */ +class Cell { + /** + * A representation of a cell within the table. + * Implementations must have `init` and `draw` methods, + * as well as `colSpan`, `rowSpan`, `desiredHeight` and `desiredWidth` properties. + * @param options + * @constructor + */ + constructor(options) { + this.setOptions(options); -var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex + /** + * Each cell will have it's `x` and `y` values set by the `layout-manager` prior to + * `init` being called; + * @type {Number} + */ + this.x = null; + this.y = null; + } -/** - * Create an attachment Content-Disposition header. - * - * @param {string} [filename] - * @param {object} [options] - * @param {string} [options.type=attachment] - * @param {string|boolean} [options.fallback=true] - * @return {string} - * @public - */ + setOptions(options) { + if (['boolean', 'number', 'string'].indexOf(typeof options) !== -1) { + options = { content: '' + options }; + } + options = options || {}; + this.options = options; + let content = options.content; + if (['boolean', 'number', 'string'].indexOf(typeof content) !== -1) { + this.content = String(content); + } else if (!content) { + this.content = ''; + } else { + throw new Error('Content needs to be a primitive, got: ' + typeof content); + } + this.colSpan = options.colSpan || 1; + this.rowSpan = options.rowSpan || 1; + } -function contentDisposition (filename, options) { - var opts = options || {} + mergeTableOptions(tableOptions, cells) { + this.cells = cells; - // get type - var type = opts.type || 'attachment' + let optionsChars = this.options.chars || {}; + let tableChars = tableOptions.chars; + let chars = (this.chars = {}); + CHAR_NAMES.forEach(function (name) { + setOption(optionsChars, tableChars, name, chars); + }); - // get parameters - var params = createparams(filename, opts.fallback) + this.truncate = this.options.truncate || tableOptions.truncate; - // format into string - return format(new ContentDisposition(type, params)) -} + let style = (this.options.style = this.options.style || {}); + let tableStyle = tableOptions.style; + setOption(style, tableStyle, 'padding-left', this); + setOption(style, tableStyle, 'padding-right', this); + this.head = style.head || tableStyle.head; + this.border = style.border || tableStyle.border; -/** - * Create parameters object from filename and fallback. - * - * @param {string} [filename] - * @param {string|boolean} [fallback=true] - * @return {object} - * @private - */ + let fixedWidth = tableOptions.colWidths[this.x]; + if (tableOptions.wordWrap && fixedWidth) { + fixedWidth -= this.paddingLeft + this.paddingRight; + if (this.colSpan) { + let i = 1; + while (i < this.colSpan) { + fixedWidth += tableOptions.colWidths[this.x + i]; + i++; + } + } + this.lines = utils.colorizeLines(utils.wordWrap(fixedWidth, this.content)); + } else { + this.lines = utils.colorizeLines(this.content.split('\n')); + } -function createparams (filename, fallback) { - if (filename === undefined) { - return + this.desiredWidth = utils.strlen(this.content) + this.paddingLeft + this.paddingRight; + this.desiredHeight = this.lines.length; } - var params = {} + /** + * Initializes the Cells data structure. + * + * @param tableOptions - A fully populated set of tableOptions. + * In addition to the standard default values, tableOptions must have fully populated the + * `colWidths` and `rowWidths` arrays. Those arrays must have lengths equal to the number + * of columns or rows (respectively) in this table, and each array item must be a Number. + * + */ + init(tableOptions) { + let x = this.x; + let y = this.y; + this.widths = tableOptions.colWidths.slice(x, x + this.colSpan); + this.heights = tableOptions.rowHeights.slice(y, y + this.rowSpan); + this.width = this.widths.reduce(sumPlusOne, -1); + this.height = this.heights.reduce(sumPlusOne, -1); - if (typeof filename !== 'string') { - throw new TypeError('filename must be a string') - } + this.hAlign = this.options.hAlign || tableOptions.colAligns[x]; + this.vAlign = this.options.vAlign || tableOptions.rowAligns[y]; - // fallback defaults to true - if (fallback === undefined) { - fallback = true + this.drawRight = x + this.colSpan == tableOptions.colWidths.length; } - if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { - throw new TypeError('fallback must be a string or boolean') + /** + * Draws the given line of the cell. + * This default implementation defers to methods `drawTop`, `drawBottom`, `drawLine` and `drawEmpty`. + * @param lineNum - can be `top`, `bottom` or a numerical line number. + * @param spanningCell - will be a number if being called from a RowSpanCell, and will represent how + * many rows below it's being called from. Otherwise it's undefined. + * @returns {String} The representation of this line. + */ + draw(lineNum, spanningCell) { + if (lineNum == 'top') return this.drawTop(this.drawRight); + if (lineNum == 'bottom') return this.drawBottom(this.drawRight); + let padLen = Math.max(this.height - this.lines.length, 0); + let padTop; + switch (this.vAlign) { + case 'center': + padTop = Math.ceil(padLen / 2); + break; + case 'bottom': + padTop = padLen; + break; + default: + padTop = 0; + } + if (lineNum < padTop || lineNum >= padTop + this.lines.length) { + return this.drawEmpty(this.drawRight, spanningCell); + } + let forceTruncation = this.lines.length > this.height && lineNum + 1 >= this.height; + return this.drawLine(lineNum - padTop, this.drawRight, forceTruncation, spanningCell); } - if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { - throw new TypeError('fallback must be ISO-8859-1 string') + /** + * Renders the top line of the cell. + * @param drawRight - true if this method should render the right edge of the cell. + * @returns {String} + */ + drawTop(drawRight) { + let content = []; + if (this.cells) { + //TODO: cells should always exist - some tests don't fill it in though + this.widths.forEach(function (width, index) { + content.push(this._topLeftChar(index)); + content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], width)); + }, this); + } else { + content.push(this._topLeftChar(0)); + content.push(utils.repeat(this.chars[this.y == 0 ? 'top' : 'mid'], this.width)); + } + if (drawRight) { + content.push(this.chars[this.y == 0 ? 'topRight' : 'rightMid']); + } + return this.wrapWithStyleColors('border', content.join('')); } - // restrict to file base name - var name = basename(filename) + _topLeftChar(offset) { + let x = this.x + offset; + let leftChar; + if (this.y == 0) { + leftChar = x == 0 ? 'topLeft' : offset == 0 ? 'topMid' : 'top'; + } else { + if (x == 0) { + leftChar = 'leftMid'; + } else { + leftChar = offset == 0 ? 'midMid' : 'bottomMid'; + if (this.cells) { + //TODO: cells should always exist - some tests don't fill it in though + let spanAbove = this.cells[this.y - 1][x] instanceof Cell.ColSpanCell; + if (spanAbove) { + leftChar = offset == 0 ? 'topMid' : 'mid'; + } + if (offset == 0) { + let i = 1; + while (this.cells[this.y][x - i] instanceof Cell.ColSpanCell) { + i++; + } + if (this.cells[this.y][x - i] instanceof Cell.RowSpanCell) { + leftChar = 'leftMid'; + } + } + } + } + } + return this.chars[leftChar]; + } - // determine if name is suitable for quoted string - var isQuotedString = TEXT_REGEXP.test(name) + wrapWithStyleColors(styleProperty, content) { + if (this[styleProperty] && this[styleProperty].length) { + try { + let colors = __nccwpck_require__(41997); + for (let i = this[styleProperty].length - 1; i >= 0; i--) { + colors = colors[this[styleProperty][i]]; + } + return colors(content); + } catch (e) { + return content; + } + } else { + return content; + } + } - // generate fallback name - var fallbackName = typeof fallback !== 'string' - ? fallback && getlatin1(name) - : basename(fallback) - var hasFallback = typeof fallbackName === 'string' && fallbackName !== name + /** + * Renders a line of text. + * @param lineNum - Which line of text to render. This is not necessarily the line within the cell. + * There may be top-padding above the first line of text. + * @param drawRight - true if this method should render the right edge of the cell. + * @param forceTruncationSymbol - `true` if the rendered text should end with the truncation symbol even + * if the text fits. This is used when the cell is vertically truncated. If `false` the text should + * only include the truncation symbol if the text will not fit horizontally within the cell width. + * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined. + * @returns {String} + */ + drawLine(lineNum, drawRight, forceTruncationSymbol, spanningCell) { + let left = this.chars[this.x == 0 ? 'left' : 'middle']; + if (this.x && spanningCell && this.cells) { + let cellLeft = this.cells[this.y + spanningCell][this.x - 1]; + while (cellLeft instanceof ColSpanCell) { + cellLeft = this.cells[cellLeft.y][cellLeft.x - 1]; + } + if (!(cellLeft instanceof RowSpanCell)) { + left = this.chars['rightMid']; + } + } + let leftPadding = utils.repeat(' ', this.paddingLeft); + let right = drawRight ? this.chars['right'] : ''; + let rightPadding = utils.repeat(' ', this.paddingRight); + let line = this.lines[lineNum]; + let len = this.width - (this.paddingLeft + this.paddingRight); + if (forceTruncationSymbol) line += this.truncate || '…'; + let content = utils.truncate(line, len, this.truncate); + content = utils.pad(content, len, ' ', this.hAlign); + content = leftPadding + content + rightPadding; + return this.stylizeLine(left, content, right); + } - // set extended filename parameter - if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { - params['filename*'] = name + stylizeLine(left, content, right) { + left = this.wrapWithStyleColors('border', left); + right = this.wrapWithStyleColors('border', right); + if (this.y === 0) { + content = this.wrapWithStyleColors('head', content); + } + return left + content + right; } - // set filename parameter - if (isQuotedString || hasFallback) { - params.filename = hasFallback - ? fallbackName - : name + /** + * Renders the bottom line of the cell. + * @param drawRight - true if this method should render the right edge of the cell. + * @returns {String} + */ + drawBottom(drawRight) { + let left = this.chars[this.x == 0 ? 'bottomLeft' : 'bottomMid']; + let content = utils.repeat(this.chars.bottom, this.width); + let right = drawRight ? this.chars['bottomRight'] : ''; + return this.wrapWithStyleColors('border', left + content + right); } - return params + /** + * Renders a blank line of text within the cell. Used for top and/or bottom padding. + * @param drawRight - true if this method should render the right edge of the cell. + * @param spanningCell - a number of if being called from a RowSpanCell. (how many rows below). otherwise undefined. + * @returns {String} + */ + drawEmpty(drawRight, spanningCell) { + let left = this.chars[this.x == 0 ? 'left' : 'middle']; + if (this.x && spanningCell && this.cells) { + let cellLeft = this.cells[this.y + spanningCell][this.x - 1]; + while (cellLeft instanceof ColSpanCell) { + cellLeft = this.cells[cellLeft.y][cellLeft.x - 1]; + } + if (!(cellLeft instanceof RowSpanCell)) { + left = this.chars['rightMid']; + } + } + let right = drawRight ? this.chars['right'] : ''; + let content = utils.repeat(' ', this.width); + return this.stylizeLine(left, content, right); + } } -/** - * Format object to Content-Disposition header. - * - * @param {object} obj - * @param {string} obj.type - * @param {object} [obj.parameters] - * @return {string} - * @private - */ - -function format (obj) { - var parameters = obj.parameters - var type = obj.type +class ColSpanCell { + /** + * A Cell that doesn't do anything. It just draws empty lines. + * Used as a placeholder in column spanning. + * @constructor + */ + constructor() {} - if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { - throw new TypeError('invalid type') + draw() { + return ''; } - // start with normalized type - var string = String(type).toLowerCase() + init() {} - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() + mergeTableOptions() {} +} - for (var i = 0; i < params.length; i++) { - param = params[i] +class RowSpanCell { + /** + * A placeholder Cell for a Cell that spans multiple rows. + * It delegates rendering to the original cell, but adds the appropriate offset. + * @param originalCell + * @constructor + */ + constructor(originalCell) { + this.originalCell = originalCell; + } - var val = param.substr(-1) === '*' - ? ustring(parameters[param]) - : qstring(parameters[param]) + init(tableOptions) { + let y = this.y; + let originalY = this.originalCell.y; + this.cellOffset = y - originalY; + this.offset = findDimension(tableOptions.rowHeights, originalY, this.cellOffset); + } - string += '; ' + param + '=' + val + draw(lineNum) { + if (lineNum == 'top') { + return this.originalCell.draw(this.offset, this.cellOffset); } + if (lineNum == 'bottom') { + return this.originalCell.draw('bottom'); + } + return this.originalCell.draw(this.offset + 1 + lineNum); } - return string + mergeTableOptions() {} } -/** - * Decode a RFC 6987 field value (gracefully). - * - * @param {string} str - * @return {string} - * @private - */ - -function decodefield (str) { - var match = EXT_VALUE_REGEXP.exec(str) - - if (!match) { - throw new TypeError('invalid extended field value') +// HELPER FUNCTIONS +function setOption(objA, objB, nameB, targetObj) { + let nameA = nameB.split('-'); + if (nameA.length > 1) { + nameA[1] = nameA[1].charAt(0).toUpperCase() + nameA[1].substr(1); + nameA = nameA.join(''); + targetObj[nameA] = objA[nameA] || objA[nameB] || objB[nameA] || objB[nameB]; + } else { + targetObj[nameB] = objA[nameB] || objB[nameB]; } +} - var charset = match[1].toLowerCase() - var encoded = match[2] - var value +function findDimension(dimensionTable, startingIndex, span) { + let ret = dimensionTable[startingIndex]; + for (let i = 1; i < span; i++) { + ret += 1 + dimensionTable[startingIndex + i]; + } + return ret; +} - // to binary string - var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) +function sumPlusOne(a, b) { + return a + b + 1; +} - switch (charset) { - case 'iso-8859-1': - value = getlatin1(binary) - break - case 'utf-8': - value = Buffer.from(binary, 'binary').toString('utf8') - break - default: - throw new TypeError('unsupported charset in extended field') - } +let CHAR_NAMES = [ + 'top', + 'top-mid', + 'top-left', + 'top-right', + 'bottom', + 'bottom-mid', + 'bottom-left', + 'bottom-right', + 'left', + 'left-mid', + 'mid', + 'mid-mid', + 'right', + 'right-mid', + 'middle', +]; +module.exports = Cell; +module.exports.ColSpanCell = ColSpanCell; +module.exports.RowSpanCell = RowSpanCell; - return value -} -/** - * Get ISO-8859-1 version of string. - * - * @param {string} val - * @return {string} - * @private - */ +/***/ }), -function getlatin1 (val) { - // simple Unicode -> ISO-8859-1 transformation - return String(val).replace(NON_LATIN1_REGEXP, '?') -} +/***/ 93875: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Parse Content-Disposition header string. - * - * @param {string} string - * @return {object} - * @public - */ +const objectAssign = __nccwpck_require__(17426); +const Cell = __nccwpck_require__(66168); +const { ColSpanCell, RowSpanCell } = Cell; -function parse (string) { - if (!string || typeof string !== 'string') { - throw new TypeError('argument string is required') +(function () { + function layoutTable(table) { + table.forEach(function (row, rowIndex) { + row.forEach(function (cell, columnIndex) { + cell.y = rowIndex; + cell.x = columnIndex; + for (let y = rowIndex; y >= 0; y--) { + let row2 = table[y]; + let xMax = y === rowIndex ? columnIndex : row2.length; + for (let x = 0; x < xMax; x++) { + let cell2 = row2[x]; + while (cellsConflict(cell, cell2)) { + cell.x++; + } + } + } + }); + }); } - var match = DISPOSITION_TYPE_REGEXP.exec(string) + function maxWidth(table) { + let mw = 0; + table.forEach(function (row) { + row.forEach(function (cell) { + mw = Math.max(mw, cell.x + (cell.colSpan || 1)); + }); + }); + return mw; + } - if (!match) { - throw new TypeError('invalid type format') + function maxHeight(table) { + return table.length; } - // normalize type - var index = match[0].length - var type = match[1].toLowerCase() + function cellsConflict(cell1, cell2) { + let yMin1 = cell1.y; + let yMax1 = cell1.y - 1 + (cell1.rowSpan || 1); + let yMin2 = cell2.y; + let yMax2 = cell2.y - 1 + (cell2.rowSpan || 1); + let yConflict = !(yMin1 > yMax2 || yMin2 > yMax1); - var key - var names = [] - var params = {} - var value + let xMin1 = cell1.x; + let xMax1 = cell1.x - 1 + (cell1.colSpan || 1); + let xMin2 = cell2.x; + let xMax2 = cell2.x - 1 + (cell2.colSpan || 1); + let xConflict = !(xMin1 > xMax2 || xMin2 > xMax1); - // calculate index to start at - index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' - ? index - 1 - : index + return yConflict && xConflict; + } - // match parameters - while ((match = PARAM_REGEXP.exec(string))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') + function conflictExists(rows, x, y) { + let i_max = Math.min(rows.length - 1, y); + let cell = { x: x, y: y }; + for (let i = 0; i <= i_max; i++) { + let row = rows[i]; + for (let j = 0; j < row.length; j++) { + if (cellsConflict(cell, row[j])) { + return true; + } + } } + return false; + } - index += match[0].length - key = match[1].toLowerCase() - value = match[2] - - if (names.indexOf(key) !== -1) { - throw new TypeError('invalid duplicate parameter') + function allBlank(rows, y, xMin, xMax) { + for (let x = xMin; x < xMax; x++) { + if (conflictExists(rows, x, y)) { + return false; + } } + return true; + } - names.push(key) - - if (key.indexOf('*') + 1 === key.length) { - // decode extended value - key = key.slice(0, -1) - value = decodefield(value) + function addRowSpanCells(table) { + table.forEach(function (row, rowIndex) { + row.forEach(function (cell) { + for (let i = 1; i < cell.rowSpan; i++) { + let rowSpanCell = new RowSpanCell(cell); + rowSpanCell.x = cell.x; + rowSpanCell.y = cell.y + i; + rowSpanCell.colSpan = cell.colSpan; + insertCell(rowSpanCell, table[rowIndex + i]); + } + }); + }); + } - // overwrite existing value - params[key] = value - continue + function addColSpanCells(cellRows) { + for (let rowIndex = cellRows.length - 1; rowIndex >= 0; rowIndex--) { + let cellColumns = cellRows[rowIndex]; + for (let columnIndex = 0; columnIndex < cellColumns.length; columnIndex++) { + let cell = cellColumns[columnIndex]; + for (let k = 1; k < cell.colSpan; k++) { + let colSpanCell = new ColSpanCell(); + colSpanCell.x = cell.x + k; + colSpanCell.y = cell.y; + cellColumns.splice(columnIndex + 1, 0, colSpanCell); + } + } } + } - if (typeof params[key] === 'string') { - continue + function insertCell(cell, row) { + let x = 0; + while (x < row.length && row[x].x < cell.x) { + x++; } + row.splice(x, 0, cell); + } - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') + function fillInTable(table) { + let h_max = maxHeight(table); + let w_max = maxWidth(table); + for (let y = 0; y < h_max; y++) { + for (let x = 0; x < w_max; x++) { + if (!conflictExists(table, x, y)) { + let opts = { x: x, y: y, colSpan: 1, rowSpan: 1 }; + x++; + while (x < w_max && !conflictExists(table, x, y)) { + opts.colSpan++; + x++; + } + let y2 = y + 1; + while (y2 < h_max && allBlank(table, y2, opts.x, opts.x + opts.colSpan)) { + opts.rowSpan++; + y2++; + } + + let cell = new Cell(opts); + cell.x = opts.x; + cell.y = opts.y; + insertCell(cell, table[y]); + } + } } + } - params[key] = value + function generateCells(rows) { + return rows.map(function (row) { + if (!Array.isArray(row)) { + let key = Object.keys(row)[0]; + row = row[key]; + if (Array.isArray(row)) { + row = row.slice(); + row.unshift(key); + } else { + row = [key, row]; + } + } + return row.map(function (cell) { + return new Cell(cell); + }); + }); } - if (index !== -1 && index !== string.length) { - throw new TypeError('invalid parameter format') + function makeTableLayout(rows) { + let cellRows = generateCells(rows); + layoutTable(cellRows); + fillInTable(cellRows); + addRowSpanCells(cellRows); + addColSpanCells(cellRows); + return cellRows; } - return new ContentDisposition(type, params) -} + module.exports = { + makeTableLayout: makeTableLayout, + layoutTable: layoutTable, + addRowSpanCells: addRowSpanCells, + maxWidth: maxWidth, + fillInTable: fillInTable, + computeWidths: makeComputeWidths('colSpan', 'desiredWidth', 'x', 1), + computeHeights: makeComputeWidths('rowSpan', 'desiredHeight', 'y', 1), + }; +})(); -/** - * Percent decode a single character. - * - * @param {string} str - * @param {string} hex - * @return {string} - * @private - */ +function makeComputeWidths(colSpan, desiredWidth, x, forcedMin) { + return function (vals, table) { + let result = []; + let spanners = []; + table.forEach(function (row) { + row.forEach(function (cell) { + if ((cell[colSpan] || 1) > 1) { + spanners.push(cell); + } else { + result[cell[x]] = Math.max(result[cell[x]] || 0, cell[desiredWidth] || 0, forcedMin); + } + }); + }); -function pdecode (str, hex) { - return String.fromCharCode(parseInt(hex, 16)) -} + vals.forEach(function (val, index) { + if (typeof val === 'number') { + result[index] = val; + } + }); -/** - * Percent encode a single character. - * - * @param {string} char - * @return {string} - * @private - */ + //spanners.forEach(function(cell){ + for (let k = spanners.length - 1; k >= 0; k--) { + let cell = spanners[k]; + let span = cell[colSpan]; + let col = cell[x]; + let existingWidth = result[col]; + let editableCols = typeof vals[col] === 'number' ? 0 : 1; + for (let i = 1; i < span; i++) { + existingWidth += 1 + result[col + i]; + if (typeof vals[col + i] !== 'number') { + editableCols++; + } + } + if (cell[desiredWidth] > existingWidth) { + let i = 0; + while (editableCols > 0 && cell[desiredWidth] > existingWidth) { + if (typeof vals[col + i] !== 'number') { + let dif = Math.round((cell[desiredWidth] - existingWidth) / editableCols); + existingWidth += dif; + result[col + i] += dif; + editableCols--; + } + i++; + } + } + } -function pencode (char) { - return '%' + String(char) - .charCodeAt(0) - .toString(16) - .toUpperCase() + objectAssign(vals, result); + for (let j = 0; j < vals.length; j++) { + vals[j] = Math.max(forcedMin, vals[j] || 0); + } + }; } -/** - * Quote a string for HTTP. - * - * @param {string} val - * @return {string} - * @private - */ -function qstring (val) { - var str = String(val) +/***/ }), - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} +/***/ 16136: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Encode a Unicode string for HTTP (RFC 5987). - * - * @param {string} val - * @return {string} - * @private - */ +const utils = __nccwpck_require__(98911); +const tableLayout = __nccwpck_require__(93875); -function ustring (val) { - var str = String(val) +class Table extends Array { + constructor(options) { + super(); - // percent encode as UTF-8 - var encoded = encodeURIComponent(str) - .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) + this.options = utils.mergeOptions(options); + } - return 'UTF-8\'\'' + encoded -} + toString() { + let array = this; + let headersPresent = this.options.head && this.options.head.length; + if (headersPresent) { + array = [this.options.head]; + if (this.length) { + array.push.apply(array, this); + } + } else { + this.options.style.head = []; + } -/** - * Class for parsed Content-Disposition header for v8 optimization - * - * @public - * @param {string} type - * @param {object} parameters - * @constructor - */ + let cells = tableLayout.makeTableLayout(array); -function ContentDisposition (type, parameters) { - this.type = type - this.parameters = parameters -} + cells.forEach(function (row) { + row.forEach(function (cell) { + cell.mergeTableOptions(this.options, cells); + }, this); + }, this); + tableLayout.computeWidths(this.options.colWidths, cells); + tableLayout.computeHeights(this.options.rowHeights, cells); -/***/ }), + cells.forEach(function (row) { + row.forEach(function (cell) { + cell.init(this.options); + }, this); + }, this); -/***/ 99915: -/***/ ((__unused_webpack_module, exports) => { + let result = []; -"use strict"; -/*! - * content-type - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ + for (let rowIndex = 0; rowIndex < cells.length; rowIndex++) { + let row = cells[rowIndex]; + let heightOfRow = this.options.rowHeights[rowIndex]; + if (rowIndex === 0 || !this.options.style.compact || (rowIndex == 1 && headersPresent)) { + doDraw(row, 'top', result); + } + for (let lineNum = 0; lineNum < heightOfRow; lineNum++) { + doDraw(row, lineNum, result); + } -/** - * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 - * - * parameter = token "=" ( token / quoted-string ) - * token = 1*tchar - * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" - * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" - * / DIGIT / ALPHA - * ; any VCHAR, except delimiters - * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE - * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text - * obs-text = %x80-FF - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - */ -var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g -var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ -var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + if (rowIndex + 1 == cells.length) { + doDraw(row, 'bottom', result); + } + } -/** - * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 - * - * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) - * obs-text = %x80-FF - */ -var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g + return result.join('\n'); + } -/** - * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 - */ -var QUOTE_REGEXP = /([\\"])/g + get width() { + let str = this.toString().split('\n'); + return str[0].length; + } +} -/** - * RegExp to match type in RFC 7231 sec 3.1.1.1 - * - * media-type = type "/" subtype - * type = token - * subtype = token - */ -var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ +function doDraw(row, lineNum, result) { + let line = []; + row.forEach(function (cell) { + line.push(cell.draw(lineNum)); + }); + let str = line.join(''); + if (str.length) result.push(str); +} -/** - * Module exports. - * @public - */ +module.exports = Table; -exports.format = format -exports.parse = parse -/** - * Format object to media type. - * - * @param {object} obj - * @return {string} - * @public - */ +/***/ }), -function format (obj) { - if (!obj || typeof obj !== 'object') { - throw new TypeError('argument obj is required') - } +/***/ 98911: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var parameters = obj.parameters - var type = obj.type +const objectAssign = __nccwpck_require__(17426); +const stringWidth = __nccwpck_require__(42577); - if (!type || !TYPE_REGEXP.test(type)) { - throw new TypeError('invalid type') +function codeRegex(capture) { + return capture ? /\u001b\[((?:\d*;){0,5}\d*)m/g : /\u001b\[(?:\d*;){0,5}\d*m/g; +} + +function strlen(str) { + let code = codeRegex(); + let stripped = ('' + str).replace(code, ''); + let split = stripped.split('\n'); + return split.reduce(function (memo, s) { + return stringWidth(s) > memo ? stringWidth(s) : memo; + }, 0); +} + +function repeat(str, times) { + return Array(times + 1).join(str); +} + +function pad(str, len, pad, dir) { + let length = strlen(str); + if (len + 1 >= length) { + let padlen = len - length; + switch (dir) { + case 'right': { + str = repeat(pad, padlen) + str; + break; + } + case 'center': { + let right = Math.ceil(padlen / 2); + let left = padlen - right; + str = repeat(pad, left) + str + repeat(pad, right); + break; + } + default: { + str = str + repeat(pad, padlen); + break; + } + } } + return str; +} - var string = type +let codeCache = {}; - // append parameters - if (parameters && typeof parameters === 'object') { - var param - var params = Object.keys(parameters).sort() +function addToCodeCache(name, on, off) { + on = '\u001b[' + on + 'm'; + off = '\u001b[' + off + 'm'; + codeCache[on] = { set: name, to: true }; + codeCache[off] = { set: name, to: false }; + codeCache[name] = { on: on, off: off }; +} - for (var i = 0; i < params.length; i++) { - param = params[i] +//https://github.com/Marak/colors.js/blob/master/lib/styles.js +addToCodeCache('bold', 1, 22); +addToCodeCache('italics', 3, 23); +addToCodeCache('underline', 4, 24); +addToCodeCache('inverse', 7, 27); +addToCodeCache('strikethrough', 9, 29); - if (!TOKEN_REGEXP.test(param)) { - throw new TypeError('invalid parameter name') +function updateState(state, controlChars) { + let controlCode = controlChars[1] ? parseInt(controlChars[1].split(';')[0]) : 0; + if ((controlCode >= 30 && controlCode <= 39) || (controlCode >= 90 && controlCode <= 97)) { + state.lastForegroundAdded = controlChars[0]; + return; + } + if ((controlCode >= 40 && controlCode <= 49) || (controlCode >= 100 && controlCode <= 107)) { + state.lastBackgroundAdded = controlChars[0]; + return; + } + if (controlCode === 0) { + for (let i in state) { + /* istanbul ignore else */ + if (Object.prototype.hasOwnProperty.call(state, i)) { + delete state[i]; } - - string += '; ' + param + '=' + qstring(parameters[param]) } + return; + } + let info = codeCache[controlChars[0]]; + if (info) { + state[info.set] = info.to; } - - return string } -/** - * Parse media type to object. - * - * @param {string|object} string - * @return {Object} - * @public - */ - -function parse (string) { - if (!string) { - throw new TypeError('argument string is required') +function readState(line) { + let code = codeRegex(true); + let controlChars = code.exec(line); + let state = {}; + while (controlChars !== null) { + updateState(state, controlChars); + controlChars = code.exec(line); } + return state; +} - // support req/res-like objects as argument - var header = typeof string === 'object' - ? getcontenttype(string) - : string +function unwindState(state, ret) { + let lastBackgroundAdded = state.lastBackgroundAdded; + let lastForegroundAdded = state.lastForegroundAdded; - if (typeof header !== 'string') { - throw new TypeError('argument string is required to be a string') - } + delete state.lastBackgroundAdded; + delete state.lastForegroundAdded; - var index = header.indexOf(';') - var type = index !== -1 - ? header.substr(0, index).trim() - : header.trim() + Object.keys(state).forEach(function (key) { + if (state[key]) { + ret += codeCache[key].off; + } + }); - if (!TYPE_REGEXP.test(type)) { - throw new TypeError('invalid media type') + if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { + ret += '\u001b[49m'; + } + if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { + ret += '\u001b[39m'; } - var obj = new ContentType(type.toLowerCase()) - - // parse parameters - if (index !== -1) { - var key - var match - var value - - PARAM_REGEXP.lastIndex = index - - while ((match = PARAM_REGEXP.exec(header))) { - if (match.index !== index) { - throw new TypeError('invalid parameter format') - } + return ret; +} - index += match[0].length - key = match[1].toLowerCase() - value = match[2] +function rewindState(state, ret) { + let lastBackgroundAdded = state.lastBackgroundAdded; + let lastForegroundAdded = state.lastForegroundAdded; - if (value[0] === '"') { - // remove quotes and escapes - value = value - .substr(1, value.length - 2) - .replace(QESC_REGEXP, '$1') - } + delete state.lastBackgroundAdded; + delete state.lastForegroundAdded; - obj.parameters[key] = value + Object.keys(state).forEach(function (key) { + if (state[key]) { + ret = codeCache[key].on + ret; } + }); - if (index !== header.length) { - throw new TypeError('invalid parameter format') - } + if (lastBackgroundAdded && lastBackgroundAdded != '\u001b[49m') { + ret = lastBackgroundAdded + ret; + } + if (lastForegroundAdded && lastForegroundAdded != '\u001b[39m') { + ret = lastForegroundAdded + ret; } - return obj + return ret; } -/** - * Get content-type from req/res objects. - * - * @param {object} - * @return {Object} - * @private - */ - -function getcontenttype (obj) { - var header - - if (typeof obj.getHeader === 'function') { - // res-like - header = obj.getHeader('content-type') - } else if (typeof obj.headers === 'object') { - // req-like - header = obj.headers && obj.headers['content-type'] +function truncateWidth(str, desiredLength) { + if (str.length === strlen(str)) { + return str.substr(0, desiredLength); } - if (typeof header !== 'string') { - throw new TypeError('content-type header is missing from object') + while (strlen(str) > desiredLength) { + str = str.slice(0, -1); } - return header + return str; } -/** - * Quote a string if necessary. - * - * @param {string} val - * @return {string} - * @private - */ - -function qstring (val) { - var str = String(val) +function truncateWidthWithAnsi(str, desiredLength) { + let code = codeRegex(true); + let split = str.split(codeRegex()); + let splitIndex = 0; + let retLen = 0; + let ret = ''; + let myArray; + let state = {}; - // no need to quote tokens - if (TOKEN_REGEXP.test(str)) { - return str - } + while (retLen < desiredLength) { + myArray = code.exec(str); + let toAdd = split[splitIndex]; + splitIndex++; + if (retLen + strlen(toAdd) > desiredLength) { + toAdd = truncateWidth(toAdd, desiredLength - retLen); + } + ret += toAdd; + retLen += strlen(toAdd); - if (str.length > 0 && !TEXT_REGEXP.test(str)) { - throw new TypeError('invalid parameter value') + if (retLen < desiredLength) { + if (!myArray) { + break; + } // full-width chars may cause a whitespace which cannot be filled + ret += myArray[0]; + updateState(state, myArray); + } } - return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' -} - -/** - * Class to represent a content type. - * @private - */ -function ContentType (type) { - this.parameters = Object.create(null) - this.type = type + return unwindState(state, ret); } +function truncate(str, desiredLength, truncateChar) { + truncateChar = truncateChar || '…'; + let lengthOfStr = strlen(str); + if (lengthOfStr <= desiredLength) { + return str; + } + desiredLength -= strlen(truncateChar); -/***/ }), + let ret = truncateWidthWithAnsi(str, desiredLength); -/***/ 61579: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return ret + truncateChar; +} -/** - * Module dependencies. - */ +function defaultOptions() { + return { + chars: { + top: '─', + 'top-mid': '┬', + 'top-left': '┌', + 'top-right': '┐', + bottom: '─', + 'bottom-mid': '┴', + 'bottom-left': '└', + 'bottom-right': '┘', + left: '│', + 'left-mid': '├', + mid: '─', + 'mid-mid': '┼', + right: '│', + 'right-mid': '┤', + middle: '│', + }, + truncate: '…', + colWidths: [], + rowHeights: [], + colAligns: [], + rowAligns: [], + style: { + 'padding-left': 1, + 'padding-right': 1, + head: ['red'], + border: ['grey'], + compact: false, + }, + head: [], + }; +} -var crypto = __nccwpck_require__(76417); +function mergeOptions(options, defaults) { + options = options || {}; + defaults = defaults || defaultOptions(); + let ret = objectAssign({}, defaults, options); + ret.chars = objectAssign({}, defaults.chars, options.chars); + ret.style = objectAssign({}, defaults.style, options.style); + return ret; +} -/** - * Sign the given `val` with `secret`. - * - * @param {String} val - * @param {String} secret - * @return {String} - * @api private - */ +function wordWrap(maxLength, input) { + let lines = []; + let split = input.split(/(\s+)/g); + let line = []; + let lineLength = 0; + let whitespace; + for (let i = 0; i < split.length; i += 2) { + let word = split[i]; + let newLength = lineLength + strlen(word); + if (lineLength > 0 && whitespace) { + newLength += whitespace.length; + } + if (newLength > maxLength) { + if (lineLength !== 0) { + lines.push(line.join('')); + } + line = [word]; + lineLength = strlen(word); + } else { + line.push(whitespace || '', word); + lineLength = newLength; + } + whitespace = split[i + 1]; + } + if (lineLength) { + lines.push(line.join('')); + } + return lines; +} -exports.sign = function(val, secret){ - if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); - if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); - return val + '.' + crypto - .createHmac('sha256', secret) - .update(val) - .digest('base64') - .replace(/\=+$/, ''); -}; +function multiLineWordWrap(maxLength, input) { + let output = []; + input = input.split('\n'); + for (let i = 0; i < input.length; i++) { + output.push.apply(output, wordWrap(maxLength, input[i])); + } + return output; +} -/** - * Unsign and decode the given `val` with `secret`, - * returning `false` if the signature is invalid. - * - * @param {String} val - * @param {String} secret - * @return {String|Boolean} - * @api private - */ +function colorizeLines(input) { + let state = {}; + let output = []; + for (let i = 0; i < input.length; i++) { + let line = rewindState(state, input[i]); + state = readState(line); + let temp = objectAssign({}, state); + output.push(unwindState(temp, line)); + } + return output; +} -exports.unsign = function(val, secret){ - if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); - if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); - var str = val.slice(0, val.lastIndexOf('.')) - , mac = exports.sign(str, secret); - - return sha1(mac) == sha1(val) ? str : false; +module.exports = { + strlen: strlen, + repeat: repeat, + pad: pad, + truncate: truncate, + mergeOptions: mergeOptions, + wordWrap: multiLineWordWrap, + colorizeLines: colorizeLines, }; -/** - * Private - */ - -function sha1(str){ - return crypto.createHash('sha1').update(str).digest('hex'); -} - /***/ }), -/***/ 93658: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; -/*! - * cookie - * Copyright(c) 2012-2014 Roman Shtylman - * Copyright(c) 2015 Douglas Christopher Wilson - * MIT Licensed - */ - - - -/** - * Module exports. - * @public - */ - -exports.parse = parse; -exports.serialize = serialize; - -/** - * Module variables. - * @private - */ - -var decode = decodeURIComponent; -var encode = encodeURIComponent; -var pairSplitRegExp = /; */; +/***/ 48481: +/***/ ((module) => { -/** - * RegExp to match field-content in RFC 7230 sec 3.2 +/* + * Copyright 2001-2010 Georges Menie (www.menie.org) + * Copyright 2010 Salvatore Sanfilippo (adapted to Redis coding style) + * Copyright 2015 Zihua Li (http://zihua.li) (ported to JavaScript) + * Copyright 2016 Mike Diarmid (http://github.com/salakar) (re-write for performance, ~700% perf inc) + * All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are met: * - * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] - * field-vchar = VCHAR / obs-text - * obs-text = %x80-FF + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * * Neither the name of the University of California, Berkeley nor the + * names of its contributors may be used to endorse or promote products + * derived from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY + * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED + * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE + * DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY + * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES + * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; + * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND + * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS + * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; - -/** - * Parse a cookie header. +/* CRC16 implementation according to CCITT standards. * - * Parse the given cookie header string into an object - * The object has the various cookies as keys(names) => values + * Note by @antirez: this is actually the XMODEM CRC 16 algorithm, using the + * following parameters: * - * @param {string} str - * @param {object} [options] - * @return {object} - * @public + * Name : "XMODEM", also known as "ZMODEM", "CRC-16/ACORN" + * Width : 16 bit + * Poly : 1021 (That is actually x^16 + x^12 + x^5 + 1) + * Initialization : 0000 + * Reflect Input byte : False + * Reflect Output CRC : False + * Xor constant to output CRC : 0000 + * Output for "123456789" : 31C3 */ -function parse(str, options) { - if (typeof str !== 'string') { - throw new TypeError('argument str must be a string'); - } - - var obj = {} - var opt = options || {}; - var pairs = str.split(pairSplitRegExp); - var dec = opt.decode || decode; - - for (var i = 0; i < pairs.length; i++) { - var pair = pairs[i]; - var eq_idx = pair.indexOf('='); - - // skip things that don't look like key=value - if (eq_idx < 0) { - continue; - } - - var key = pair.substr(0, eq_idx).trim() - var val = pair.substr(++eq_idx, pair.length).trim(); +var lookup = [ + 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, + 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, + 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, + 0x9339, 0x8318, 0xb37b, 0xa35a, 0xd3bd, 0xc39c, 0xf3ff, 0xe3de, + 0x2462, 0x3443, 0x0420, 0x1401, 0x64e6, 0x74c7, 0x44a4, 0x5485, + 0xa56a, 0xb54b, 0x8528, 0x9509, 0xe5ee, 0xf5cf, 0xc5ac, 0xd58d, + 0x3653, 0x2672, 0x1611, 0x0630, 0x76d7, 0x66f6, 0x5695, 0x46b4, + 0xb75b, 0xa77a, 0x9719, 0x8738, 0xf7df, 0xe7fe, 0xd79d, 0xc7bc, + 0x48c4, 0x58e5, 0x6886, 0x78a7, 0x0840, 0x1861, 0x2802, 0x3823, + 0xc9cc, 0xd9ed, 0xe98e, 0xf9af, 0x8948, 0x9969, 0xa90a, 0xb92b, + 0x5af5, 0x4ad4, 0x7ab7, 0x6a96, 0x1a71, 0x0a50, 0x3a33, 0x2a12, + 0xdbfd, 0xcbdc, 0xfbbf, 0xeb9e, 0x9b79, 0x8b58, 0xbb3b, 0xab1a, + 0x6ca6, 0x7c87, 0x4ce4, 0x5cc5, 0x2c22, 0x3c03, 0x0c60, 0x1c41, + 0xedae, 0xfd8f, 0xcdec, 0xddcd, 0xad2a, 0xbd0b, 0x8d68, 0x9d49, + 0x7e97, 0x6eb6, 0x5ed5, 0x4ef4, 0x3e13, 0x2e32, 0x1e51, 0x0e70, + 0xff9f, 0xefbe, 0xdfdd, 0xcffc, 0xbf1b, 0xaf3a, 0x9f59, 0x8f78, + 0x9188, 0x81a9, 0xb1ca, 0xa1eb, 0xd10c, 0xc12d, 0xf14e, 0xe16f, + 0x1080, 0x00a1, 0x30c2, 0x20e3, 0x5004, 0x4025, 0x7046, 0x6067, + 0x83b9, 0x9398, 0xa3fb, 0xb3da, 0xc33d, 0xd31c, 0xe37f, 0xf35e, + 0x02b1, 0x1290, 0x22f3, 0x32d2, 0x4235, 0x5214, 0x6277, 0x7256, + 0xb5ea, 0xa5cb, 0x95a8, 0x8589, 0xf56e, 0xe54f, 0xd52c, 0xc50d, + 0x34e2, 0x24c3, 0x14a0, 0x0481, 0x7466, 0x6447, 0x5424, 0x4405, + 0xa7db, 0xb7fa, 0x8799, 0x97b8, 0xe75f, 0xf77e, 0xc71d, 0xd73c, + 0x26d3, 0x36f2, 0x0691, 0x16b0, 0x6657, 0x7676, 0x4615, 0x5634, + 0xd94c, 0xc96d, 0xf90e, 0xe92f, 0x99c8, 0x89e9, 0xb98a, 0xa9ab, + 0x5844, 0x4865, 0x7806, 0x6827, 0x18c0, 0x08e1, 0x3882, 0x28a3, + 0xcb7d, 0xdb5c, 0xeb3f, 0xfb1e, 0x8bf9, 0x9bd8, 0xabbb, 0xbb9a, + 0x4a75, 0x5a54, 0x6a37, 0x7a16, 0x0af1, 0x1ad0, 0x2ab3, 0x3a92, + 0xfd2e, 0xed0f, 0xdd6c, 0xcd4d, 0xbdaa, 0xad8b, 0x9de8, 0x8dc9, + 0x7c26, 0x6c07, 0x5c64, 0x4c45, 0x3ca2, 0x2c83, 0x1ce0, 0x0cc1, + 0xef1f, 0xff3e, 0xcf5d, 0xdf7c, 0xaf9b, 0xbfba, 0x8fd9, 0x9ff8, + 0x6e17, 0x7e36, 0x4e55, 0x5e74, 0x2e93, 0x3eb2, 0x0ed1, 0x1ef0 +]; - // quoted values - if ('"' == val[0]) { - val = val.slice(1, -1); - } +/** + * Convert a string to a UTF8 array - faster than via buffer + * @param str + * @returns {Array} + */ +var toUTF8Array = function toUTF8Array(str) { + var char; + var i = 0; + var p = 0; + var utf8 = []; + var len = str.length; - // only assign once - if (undefined == obj[key]) { - obj[key] = tryDecode(val, dec); + for (; i < len; i++) { + char = str.charCodeAt(i); + if (char < 128) { + utf8[p++] = char; + } else if (char < 2048) { + utf8[p++] = (char >> 6) | 192; + utf8[p++] = (char & 63) | 128; + } else if ( + ((char & 0xFC00) === 0xD800) && (i + 1) < str.length && + ((str.charCodeAt(i + 1) & 0xFC00) === 0xDC00)) { + char = 0x10000 + ((char & 0x03FF) << 10) + (str.charCodeAt(++i) & 0x03FF); + utf8[p++] = (char >> 18) | 240; + utf8[p++] = ((char >> 12) & 63) | 128; + utf8[p++] = ((char >> 6) & 63) | 128; + utf8[p++] = (char & 63) | 128; + } else { + utf8[p++] = (char >> 12) | 224; + utf8[p++] = ((char >> 6) & 63) | 128; + utf8[p++] = (char & 63) | 128; } } - return obj; -} + return utf8; +}; /** - * Serialize data into a cookie header. - * - * Serialize the a name value pair into a cookie string suitable for - * http headers. An optional options object specified cookie parameters. - * - * serialize('foo', 'bar', { httpOnly: true }) - * => "foo=bar; httpOnly" - * - * @param {string} name - * @param {string} val - * @param {object} [options] - * @return {string} - * @public + * Convert a string into a redis slot hash. + * @param str + * @returns {number} */ +var generate = module.exports = function generate(str) { + var char; + var i = 0; + var start = -1; + var result = 0; + var resultHash = 0; + var utf8 = typeof str === 'string' ? toUTF8Array(str) : str; + var len = utf8.length; -function serialize(name, val, options) { - var opt = options || {}; - var enc = opt.encode || encode; - - if (typeof enc !== 'function') { - throw new TypeError('option encode is invalid'); - } - - if (!fieldContentRegExp.test(name)) { - throw new TypeError('argument name is invalid'); - } - - var value = enc(val); + while (i < len) { + char = utf8[i++]; + if (start === -1) { + if (char === 0x7B) { + start = i; + } + } else if (char !== 0x7D) { + resultHash = lookup[(char ^ (resultHash >> 8)) & 0xFF] ^ (resultHash << 8); + } else if (i - 1 !== start) { + return resultHash & 0x3FFF; + } - if (value && !fieldContentRegExp.test(value)) { - throw new TypeError('argument val is invalid'); + result = lookup[(char ^ (result >> 8)) & 0xFF] ^ (result << 8); } - var str = name + '=' + value; - - if (null != opt.maxAge) { - var maxAge = opt.maxAge - 0; - if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); - str += '; Max-Age=' + Math.floor(maxAge); - } + return result & 0x3FFF; +}; - if (opt.domain) { - if (!fieldContentRegExp.test(opt.domain)) { - throw new TypeError('option domain is invalid'); - } +/** + * Convert an array of multiple strings into a redis slot hash. + * Returns -1 if one of the keys is not for the same slot as the others + * @param keys + * @returns {number} + */ +module.exports.generateMulti = function generateMulti(keys) { + var i = 1; + var len = keys.length; + var base = generate(keys[0]); - str += '; Domain=' + opt.domain; + while (i < len) { + if (generate(keys[i++]) !== base) return -1; } - if (opt.path) { - if (!fieldContentRegExp.test(opt.path)) { - throw new TypeError('option path is invalid'); - } - - str += '; Path=' + opt.path; - } + return base; +}; - if (opt.expires) { - if (typeof opt.expires.toUTCString !== 'function') { - throw new TypeError('option expires is invalid'); - } - str += '; Expires=' + opt.expires.toUTCString(); - } +/***/ }), - if (opt.httpOnly) { - str += '; HttpOnly'; - } +/***/ 43595: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (opt.secure) { - str += '; Secure'; - } +/* - if (opt.sameSite) { - var sameSite = typeof opt.sameSite === 'string' - ? opt.sameSite.toLowerCase() : opt.sameSite; +The MIT License (MIT) - switch (sameSite) { - case true: - str += '; SameSite=Strict'; - break; - case 'lax': - str += '; SameSite=Lax'; - break; - case 'strict': - str += '; SameSite=Strict'; - break; - case 'none': - str += '; SameSite=None'; - break; - default: - throw new TypeError('option sameSite is invalid'); - } - } +Original Library + - Copyright (c) Marak Squires - return str; -} +Additional functionality + - Copyright (c) Sindre Sorhus (sindresorhus.com) -/** - * Try decoding a string using a decoding function. - * - * @param {string} str - * @param {function} decode - * @private - */ +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: -function tryDecode(str, decode) { - try { - return decode(str); - } catch (e) { - return str; - } -} +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. -/***/ }), +*/ -/***/ 65507: -/***/ ((__unused_webpack_module, exports) => { +var colors = {}; +module['exports'] = colors; -/* jshint node: true */ -(function () { - "use strict"; +colors.themes = {}; - function CookieAccessInfo(domain, path, secure, script) { - if (this instanceof CookieAccessInfo) { - this.domain = domain || undefined; - this.path = path || "/"; - this.secure = !!secure; - this.script = !!script; - return this; - } - return new CookieAccessInfo(domain, path, secure, script); - } - CookieAccessInfo.All = Object.freeze(Object.create(null)); - exports.CookieAccessInfo = CookieAccessInfo; +var util = __nccwpck_require__(31669); +var ansiStyles = colors.styles = __nccwpck_require__(73104); +var defineProps = Object.defineProperties; +var newLineRegex = new RegExp(/[\r\n]+/g); - function Cookie(cookiestr, request_domain, request_path) { - if (cookiestr instanceof Cookie) { - return cookiestr; - } - if (this instanceof Cookie) { - this.name = null; - this.value = null; - this.expiration_date = Infinity; - this.path = String(request_path || "/"); - this.explicit_path = false; - this.domain = request_domain || null; - this.explicit_domain = false; - this.secure = false; //how to define default? - this.noscript = false; //httponly - if (cookiestr) { - this.parse(cookiestr, request_domain, request_path); - } - return this; - } - return new Cookie(cookiestr, request_domain, request_path); - } - exports.Cookie = Cookie; +colors.supportsColor = __nccwpck_require__(10662).supportsColor; - Cookie.prototype.toString = function toString() { - var str = [this.name + "=" + this.value]; - if (this.expiration_date !== Infinity) { - str.push("expires=" + (new Date(this.expiration_date)).toGMTString()); - } - if (this.domain) { - str.push("domain=" + this.domain); - } - if (this.path) { - str.push("path=" + this.path); - } - if (this.secure) { - str.push("secure"); - } - if (this.noscript) { - str.push("httponly"); - } - return str.join("; "); - }; +if (typeof colors.enabled === 'undefined') { + colors.enabled = colors.supportsColor() !== false; +} - Cookie.prototype.toValueString = function toValueString() { - return this.name + "=" + this.value; - }; +colors.enable = function() { + colors.enabled = true; +}; - var cookie_str_splitter = /[:](?=\s*[a-zA-Z0-9_\-]+\s*[=])/g; - Cookie.prototype.parse = function parse(str, request_domain, request_path) { - if (this instanceof Cookie) { - var parts = str.split(";").filter(function (value) { - return !!value; - }); - var i; +colors.disable = function() { + colors.enabled = false; +}; - var pair = parts[0].match(/([^=]+)=([\s\S]*)/); - if (!pair) { - console.warn("Invalid cookie header encountered. Header: '"+str+"'"); - return; - } +colors.stripColors = colors.strip = function(str) { + return ('' + str).replace(/\x1B\[\d+m/g, ''); +}; - var key = pair[1]; - var value = pair[2]; - if ( typeof key !== 'string' || key.length === 0 || typeof value !== 'string' ) { - console.warn("Unable to extract values from cookie header. Cookie: '"+str+"'"); - return; - } +// eslint-disable-next-line no-unused-vars +var stylize = colors.stylize = function stylize(str, style) { + if (!colors.enabled) { + return str+''; + } - this.name = key; - this.value = value; + var styleMap = ansiStyles[style]; - for (i = 1; i < parts.length; i += 1) { - pair = parts[i].match(/([^=]+)(?:=([\s\S]*))?/); - key = pair[1].trim().toLowerCase(); - value = pair[2]; - switch (key) { - case "httponly": - this.noscript = true; - break; - case "expires": - this.expiration_date = value ? - Number(Date.parse(value)) : - Infinity; - break; - case "path": - this.path = value ? - value.trim() : - ""; - this.explicit_path = true; - break; - case "domain": - this.domain = value ? - value.trim() : - ""; - this.explicit_domain = !!this.domain; - break; - case "secure": - this.secure = true; - break; - } - } + // Stylize should work for non-ANSI styles, too + if(!styleMap && style in colors){ + // Style maps like trap operate as functions on strings; + // they don't have properties like open or close. + return colors[style](str); + } - if (!this.explicit_path) { - this.path = request_path || "/"; - } - if (!this.explicit_domain) { - this.domain = request_domain; - } + return styleMap.open + str + styleMap.close; +}; - return this; - } - return new Cookie().parse(str, request_domain, request_path); - }; +var matchOperatorsRe = /[|\\{}()[\]^$+*?.]/g; +var escapeStringRegexp = function(str) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + return str.replace(matchOperatorsRe, '\\$&'); +}; - Cookie.prototype.matches = function matches(access_info) { - if (access_info === CookieAccessInfo.All) { - return true; - } - if (this.noscript && access_info.script || - this.secure && !access_info.secure || - !this.collidesWith(access_info)) { - return false; - } - return true; - }; +function build(_styles) { + var builder = function builder() { + return applyStyle.apply(builder, arguments); + }; + builder._styles = _styles; + // __proto__ is used because we must return a function, but there is + // no way to create a function with a different prototype. + builder.__proto__ = proto; + return builder; +} - Cookie.prototype.collidesWith = function collidesWith(access_info) { - if ((this.path && !access_info.path) || (this.domain && !access_info.domain)) { - return false; - } - if (this.path && access_info.path.indexOf(this.path) !== 0) { - return false; - } - if (this.explicit_path && access_info.path.indexOf( this.path ) !== 0) { - return false; - } - var access_domain = access_info.domain && access_info.domain.replace(/^[\.]/,''); - var cookie_domain = this.domain && this.domain.replace(/^[\.]/,''); - if (cookie_domain === access_domain) { - return true; - } - if (cookie_domain) { - if (!this.explicit_domain) { - return false; // we already checked if the domains were exactly the same - } - var wildcard = access_domain.indexOf(cookie_domain); - if (wildcard === -1 || wildcard !== access_domain.length - cookie_domain.length) { - return false; - } - return true; - } - return true; +var styles = (function() { + var ret = {}; + ansiStyles.grey = ansiStyles.gray; + Object.keys(ansiStyles).forEach(function(key) { + ansiStyles[key].closeRe = + new RegExp(escapeStringRegexp(ansiStyles[key].close), 'g'); + ret[key] = { + get: function() { + return build(this._styles.concat(key)); + }, }; + }); + return ret; +})(); - function CookieJar() { - var cookies, cookies_list, collidable_cookie; - if (this instanceof CookieJar) { - cookies = Object.create(null); //name: [Cookie] +var proto = defineProps(function colors() {}, styles); - this.setCookie = function setCookie(cookie, request_domain, request_path) { - var remove, i; - cookie = new Cookie(cookie, request_domain, request_path); - //Delete the cookie if the set is past the current time - remove = cookie.expiration_date <= Date.now(); - if (cookies[cookie.name] !== undefined) { - cookies_list = cookies[cookie.name]; - for (i = 0; i < cookies_list.length; i += 1) { - collidable_cookie = cookies_list[i]; - if (collidable_cookie.collidesWith(cookie)) { - if (remove) { - cookies_list.splice(i, 1); - if (cookies_list.length === 0) { - delete cookies[cookie.name]; - } - return false; - } - cookies_list[i] = cookie; - return cookie; - } - } - if (remove) { - return false; - } - cookies_list.push(cookie); - return cookie; - } - if (remove) { - return false; - } - cookies[cookie.name] = [cookie]; - return cookies[cookie.name]; - }; - //returns a cookie - this.getCookie = function getCookie(cookie_name, access_info) { - var cookie, i; - cookies_list = cookies[cookie_name]; - if (!cookies_list) { - return; - } - for (i = 0; i < cookies_list.length; i += 1) { - cookie = cookies_list[i]; - if (cookie.expiration_date <= Date.now()) { - if (cookies_list.length === 0) { - delete cookies[cookie.name]; - } - continue; - } +function applyStyle() { + var args = Array.prototype.slice.call(arguments); - if (cookie.matches(access_info)) { - return cookie; - } - } - }; - //returns a list of cookies - this.getCookies = function getCookies(access_info) { - var matches = [], cookie_name, cookie; - for (cookie_name in cookies) { - cookie = this.getCookie(cookie_name, access_info); - if (cookie) { - matches.push(cookie); - } - } - matches.toString = function toString() { - return matches.join(":"); - }; - matches.toValueString = function toValueString() { - return matches.map(function (c) { - return c.toValueString(); - }).join(';'); - }; - return matches; - }; + var str = args.map(function(arg) { + // Use weak equality check so we can colorize null/undefined in safe mode + if (arg != null && arg.constructor === String) { + return arg; + } else { + return util.inspect(arg); + } + }).join(' '); - return this; - } - return new CookieJar(); + if (!colors.enabled || !str) { + return str; + } + + var newLinesPresent = str.indexOf('\n') != -1; + + var nestedStyles = this._styles; + + var i = nestedStyles.length; + while (i--) { + var code = ansiStyles[nestedStyles[i]]; + str = code.open + str.replace(code.closeRe, code.open) + code.close; + if (newLinesPresent) { + str = str.replace(newLineRegex, function(match) { + return code.close + match + code.open; + }); } - exports.CookieJar = CookieJar; + } - //returns list of cookies that were set correctly. Cookies that are expired and removed are not returned. - CookieJar.prototype.setCookies = function setCookies(cookies, request_domain, request_path) { - cookies = Array.isArray(cookies) ? - cookies : - cookies.split(cookie_str_splitter); - var successful = [], - i, - cookie; - cookies = cookies.map(function(item){ - return new Cookie(item, request_domain, request_path); - }); - for (i = 0; i < cookies.length; i += 1) { - cookie = cookies[i]; - if (this.setCookie(cookie, request_domain, request_path)) { - successful.push(cookie); - } + return str; +} + +colors.setTheme = function(theme) { + if (typeof theme === 'string') { + console.log('colors.setTheme now only accepts an object, not a string. ' + + 'If you are trying to set a theme from a file, it is now your (the ' + + 'caller\'s) responsibility to require the file. The old syntax ' + + 'looked like colors.setTheme(__dirname + ' + + '\'/../themes/generic-logging.js\'); The new syntax looks like '+ + 'colors.setTheme(require(__dirname + ' + + '\'/../themes/generic-logging.js\'));'); + return; + } + for (var style in theme) { + (function(style) { + colors[style] = function(str) { + if (typeof theme[style] === 'object') { + var out = str; + for (var i in theme[style]) { + out = colors[theme[style][i]](out); + } + return out; } - return successful; + return colors[theme[style]](str); + }; + })(style); + } +}; + +function init() { + var ret = {}; + Object.keys(styles).forEach(function(name) { + ret[name] = { + get: function() { + return build([name]); + }, }; -}()); + }); + return ret; +} +var sequencer = function sequencer(map, str) { + var exploded = str.split(''); + exploded = exploded.map(map); + return exploded.join(''); +}; -/***/ }), +// custom formatter methods +colors.trap = __nccwpck_require__(31302); +colors.zalgo = __nccwpck_require__(45610); -/***/ 51512: -/***/ (function(module) { +// maps +colors.maps = {}; +colors.maps.america = __nccwpck_require__(76936)(colors); +colors.maps.zebra = __nccwpck_require__(12989)(colors); +colors.maps.rainbow = __nccwpck_require__(75210)(colors); +colors.maps.random = __nccwpck_require__(13441)(colors); -/* - * Date Format 1.2.3 - * (c) 2007-2009 Steven Levithan - * MIT license - * - * Includes enhancements by Scott Trenda - * and Kris Kowal - * - * Accepts a date, a mask, or a date and a mask. - * Returns a formatted version of the given date. - * The date defaults to the current date/time. - * The mask defaults to dateFormat.masks.default. - */ +for (var map in colors.maps) { + (function(map) { + colors[map] = function(str) { + return sequencer(colors.maps[map], str); + }; + })(map); +} -(function(global) { - 'use strict'; +defineProps(colors, init()); - var dateFormat = (function() { - var token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZWN]|"[^"]*"|'[^']*'/g; - var timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g; - var timezoneClip = /[^-+\dA-Z]/g; - - // Regexes and supporting functions are cached through closure - return function (date, mask, utc, gmt) { - - // You can't provide utc if you skip other args (use the 'UTC:' mask prefix) - if (arguments.length === 1 && kindOf(date) === 'string' && !/\d/.test(date)) { - mask = date; - date = undefined; - } - - date = date || new Date; - - if(!(date instanceof Date)) { - date = new Date(date); - } - - if (isNaN(date)) { - throw TypeError('Invalid date'); - } - - mask = String(dateFormat.masks[mask] || mask || dateFormat.masks['default']); - - // Allow setting the utc/gmt argument via the mask - var maskSlice = mask.slice(0, 4); - if (maskSlice === 'UTC:' || maskSlice === 'GMT:') { - mask = mask.slice(4); - utc = true; - if (maskSlice === 'GMT:') { - gmt = true; - } - } - - var _ = utc ? 'getUTC' : 'get'; - var d = date[_ + 'Date'](); - var D = date[_ + 'Day'](); - var m = date[_ + 'Month'](); - var y = date[_ + 'FullYear'](); - var H = date[_ + 'Hours'](); - var M = date[_ + 'Minutes'](); - var s = date[_ + 'Seconds'](); - var L = date[_ + 'Milliseconds'](); - var o = utc ? 0 : date.getTimezoneOffset(); - var W = getWeek(date); - var N = getDayOfWeek(date); - var flags = { - d: d, - dd: pad(d), - ddd: dateFormat.i18n.dayNames[D], - dddd: dateFormat.i18n.dayNames[D + 7], - m: m + 1, - mm: pad(m + 1), - mmm: dateFormat.i18n.monthNames[m], - mmmm: dateFormat.i18n.monthNames[m + 12], - yy: String(y).slice(2), - yyyy: y, - h: H % 12 || 12, - hh: pad(H % 12 || 12), - H: H, - HH: pad(H), - M: M, - MM: pad(M), - s: s, - ss: pad(s), - l: pad(L, 3), - L: pad(Math.round(L / 10)), - t: H < 12 ? dateFormat.i18n.timeNames[0] : dateFormat.i18n.timeNames[1], - tt: H < 12 ? dateFormat.i18n.timeNames[2] : dateFormat.i18n.timeNames[3], - T: H < 12 ? dateFormat.i18n.timeNames[4] : dateFormat.i18n.timeNames[5], - TT: H < 12 ? dateFormat.i18n.timeNames[6] : dateFormat.i18n.timeNames[7], - Z: gmt ? 'GMT' : utc ? 'UTC' : (String(date).match(timezone) || ['']).pop().replace(timezoneClip, ''), - o: (o > 0 ? '-' : '+') + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4), - S: ['th', 'st', 'nd', 'rd'][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10], - W: W, - N: N - }; - - return mask.replace(token, function (match) { - if (match in flags) { - return flags[match]; - } - return match.slice(1, match.length - 1); - }); - }; - })(); - dateFormat.masks = { - 'default': 'ddd mmm dd yyyy HH:MM:ss', - 'shortDate': 'm/d/yy', - 'mediumDate': 'mmm d, yyyy', - 'longDate': 'mmmm d, yyyy', - 'fullDate': 'dddd, mmmm d, yyyy', - 'shortTime': 'h:MM TT', - 'mediumTime': 'h:MM:ss TT', - 'longTime': 'h:MM:ss TT Z', - 'isoDate': 'yyyy-mm-dd', - 'isoTime': 'HH:MM:ss', - 'isoDateTime': 'yyyy-mm-dd\'T\'HH:MM:sso', - 'isoUtcDateTime': 'UTC:yyyy-mm-dd\'T\'HH:MM:ss\'Z\'', - 'expiresHeaderFormat': 'ddd, dd mmm yyyy HH:MM:ss Z' +/***/ }), + +/***/ 31302: +/***/ ((module) => { + +module['exports'] = function runTheTrap(text, options) { + var result = ''; + text = text || 'Run the trap, drop the bass'; + text = text.split(''); + var trap = { + a: ['\u0040', '\u0104', '\u023a', '\u0245', '\u0394', '\u039b', '\u0414'], + b: ['\u00df', '\u0181', '\u0243', '\u026e', '\u03b2', '\u0e3f'], + c: ['\u00a9', '\u023b', '\u03fe'], + d: ['\u00d0', '\u018a', '\u0500', '\u0501', '\u0502', '\u0503'], + e: ['\u00cb', '\u0115', '\u018e', '\u0258', '\u03a3', '\u03be', '\u04bc', + '\u0a6c'], + f: ['\u04fa'], + g: ['\u0262'], + h: ['\u0126', '\u0195', '\u04a2', '\u04ba', '\u04c7', '\u050a'], + i: ['\u0f0f'], + j: ['\u0134'], + k: ['\u0138', '\u04a0', '\u04c3', '\u051e'], + l: ['\u0139'], + m: ['\u028d', '\u04cd', '\u04ce', '\u0520', '\u0521', '\u0d69'], + n: ['\u00d1', '\u014b', '\u019d', '\u0376', '\u03a0', '\u048a'], + o: ['\u00d8', '\u00f5', '\u00f8', '\u01fe', '\u0298', '\u047a', '\u05dd', + '\u06dd', '\u0e4f'], + p: ['\u01f7', '\u048e'], + q: ['\u09cd'], + r: ['\u00ae', '\u01a6', '\u0210', '\u024c', '\u0280', '\u042f'], + s: ['\u00a7', '\u03de', '\u03df', '\u03e8'], + t: ['\u0141', '\u0166', '\u0373'], + u: ['\u01b1', '\u054d'], + v: ['\u05d8'], + w: ['\u0428', '\u0460', '\u047c', '\u0d70'], + x: ['\u04b2', '\u04fe', '\u04fc', '\u04fd'], + y: ['\u00a5', '\u04b0', '\u04cb'], + z: ['\u01b5', '\u0240'], }; + text.forEach(function(c) { + c = c.toLowerCase(); + var chars = trap[c] || [' ']; + var rand = Math.floor(Math.random() * chars.length); + if (typeof trap[c] !== 'undefined') { + result += trap[c][rand]; + } else { + result += c; + } + }); + return result; +}; + + +/***/ }), - // Internationalization strings - dateFormat.i18n = { - dayNames: [ - 'Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', - 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday' +/***/ 45610: +/***/ ((module) => { + +// please no +module['exports'] = function zalgo(text, options) { + text = text || ' he is here '; + var soul = { + 'up': [ + '̍', '̎', '̄', '̅', + '̿', '̑', '̆', '̐', + '͒', '͗', '͑', '̇', + '̈', '̊', '͂', '̓', + '̈', '͊', '͋', '͌', + '̃', '̂', '̌', '͐', + '̀', '́', '̋', '̏', + '̒', '̓', '̔', '̽', + '̉', 'ͣ', 'ͤ', 'ͥ', + 'ͦ', 'ͧ', 'ͨ', 'ͩ', + 'ͪ', 'ͫ', 'ͬ', 'ͭ', + 'ͮ', 'ͯ', '̾', '͛', + '͆', '̚', + ], + 'down': [ + '̖', '̗', '̘', '̙', + '̜', '̝', '̞', '̟', + '̠', '̤', '̥', '̦', + '̩', '̪', '̫', '̬', + '̭', '̮', '̯', '̰', + '̱', '̲', '̳', '̹', + '̺', '̻', '̼', 'ͅ', + '͇', '͈', '͉', '͍', + '͎', '͓', '͔', '͕', + '͖', '͙', '͚', '̣', ], - monthNames: [ - 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec', - 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' + 'mid': [ + '̕', '̛', '̀', '́', + '͘', '̡', '̢', '̧', + '̨', '̴', '̵', '̶', + '͜', '͝', '͞', + '͟', '͠', '͢', '̸', + '̷', '͡', ' ҉', ], - timeNames: [ - 'a', 'p', 'am', 'pm', 'A', 'P', 'AM', 'PM' - ] }; + var all = [].concat(soul.up, soul.down, soul.mid); -function pad(val, len) { - val = String(val); - len = len || 2; - while (val.length < len) { - val = '0' + val; + function randomNumber(range) { + var r = Math.floor(Math.random() * range); + return r; + } + + function isChar(character) { + var bool = false; + all.filter(function(i) { + bool = (i === character); + }); + return bool; } - return val; -} -/** - * Get the ISO 8601 week number - * Based on comments from - * http://techblog.procurios.nl/k/n618/news/view/33796/14863/Calculate-ISO-8601-week-and-year-in-javascript.html - * - * @param {Object} `date` - * @return {Number} - */ -function getWeek(date) { - // Remove time components of date - var targetThursday = new Date(date.getFullYear(), date.getMonth(), date.getDate()); - // Change date to Thursday same week - targetThursday.setDate(targetThursday.getDate() - ((targetThursday.getDay() + 6) % 7) + 3); + function heComes(text, options) { + var result = ''; + var counts; + var l; + options = options || {}; + options['up'] = + typeof options['up'] !== 'undefined' ? options['up'] : true; + options['mid'] = + typeof options['mid'] !== 'undefined' ? options['mid'] : true; + options['down'] = + typeof options['down'] !== 'undefined' ? options['down'] : true; + options['size'] = + typeof options['size'] !== 'undefined' ? options['size'] : 'maxi'; + text = text.split(''); + for (l in text) { + if (isChar(l)) { + continue; + } + result = result + text[l]; + counts = {'up': 0, 'down': 0, 'mid': 0}; + switch (options.size) { + case 'mini': + counts.up = randomNumber(8); + counts.mid = randomNumber(2); + counts.down = randomNumber(8); + break; + case 'maxi': + counts.up = randomNumber(16) + 3; + counts.mid = randomNumber(4) + 1; + counts.down = randomNumber(64) + 3; + break; + default: + counts.up = randomNumber(8) + 1; + counts.mid = randomNumber(6) / 2; + counts.down = randomNumber(8) + 1; + break; + } - // Take January 4th as it is always in week 1 (see ISO 8601) - var firstThursday = new Date(targetThursday.getFullYear(), 0, 4); + var arr = ['up', 'mid', 'down']; + for (var d in arr) { + var index = arr[d]; + for (var i = 0; i <= counts[index]; i++) { + if (options[index]) { + result = result + soul[index][randomNumber(soul[index].length)]; + } + } + } + } + return result; + } + // don't summon him + return heComes(text, options); +}; - // Change date to Thursday same week - firstThursday.setDate(firstThursday.getDate() - ((firstThursday.getDay() + 6) % 7) + 3); - // Check if daylight-saving-time-switch occurred and correct for it - var ds = targetThursday.getTimezoneOffset() - firstThursday.getTimezoneOffset(); - targetThursday.setHours(targetThursday.getHours() - ds); - // Number of weeks between target Thursday and first Thursday - var weekDiff = (targetThursday - firstThursday) / (86400000*7); - return 1 + Math.floor(weekDiff); -} +/***/ }), -/** - * Get ISO-8601 numeric representation of the day of the week - * 1 (for Monday) through 7 (for Sunday) - * - * @param {Object} `date` - * @return {Number} - */ -function getDayOfWeek(date) { - var dow = date.getDay(); - if(dow === 0) { - dow = 7; - } - return dow; -} +/***/ 76936: +/***/ ((module) => { -/** - * kind-of shortcut - * @param {*} val - * @return {String} - */ -function kindOf(val) { - if (val === null) { - return 'null'; - } +module['exports'] = function(colors) { + return function(letter, i, exploded) { + if (letter === ' ') return letter; + switch (i%3) { + case 0: return colors.red(letter); + case 1: return colors.white(letter); + case 2: return colors.blue(letter); + } + }; +}; - if (val === undefined) { - return 'undefined'; - } - if (typeof val !== 'object') { - return typeof val; - } +/***/ }), - if (Array.isArray(val)) { - return 'array'; - } +/***/ 75210: +/***/ ((module) => { - return {}.toString.call(val) - .slice(8, -1).toLowerCase(); +module['exports'] = function(colors) { + // RoY G BiV + var rainbowColors = ['red', 'yellow', 'green', 'blue', 'magenta']; + return function(letter, i, exploded) { + if (letter === ' ') { + return letter; + } else { + return colors[rainbowColors[i++ % rainbowColors.length]](letter); + } + }; }; - if (typeof define === 'function' && define.amd) { - define(function () { - return dateFormat; - }); - } else if (true) { - module.exports = dateFormat; - } else {} -})(this); +/***/ }), + +/***/ 13441: +/***/ ((module) => { + +module['exports'] = function(colors) { + var available = ['underline', 'inverse', 'grey', 'yellow', 'red', 'green', + 'blue', 'white', 'cyan', 'magenta', 'brightYellow', 'brightRed', + 'brightGreen', 'brightBlue', 'brightWhite', 'brightCyan', 'brightMagenta']; + return function(letter, i, exploded) { + return letter === ' ' ? letter : + colors[ + available[Math.round(Math.random() * (available.length - 2))] + ](letter); + }; +}; /***/ }), -/***/ 84697: +/***/ 12989: /***/ ((module) => { -/** - * Helpers. - */ +module['exports'] = function(colors) { + return function(letter, i, exploded) { + return i % 2 === 0 ? letter : colors.inverse(letter); + }; +}; -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var w = d * 7; -var y = d * 365.25; -/** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] - * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public - */ +/***/ }), -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isFinite(val)) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); -}; +/***/ 73104: +/***/ ((module) => { -/** - * Parse the given `str` and return milliseconds. - * - * @param {String} str - * @return {Number} - * @api private - */ +/* +The MIT License (MIT) -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'weeks': - case 'week': - case 'w': - return n * w; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} +Copyright (c) Sindre Sorhus (sindresorhus.com) -/** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +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: -function fmtShort(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return Math.round(ms / d) + 'd'; - } - if (msAbs >= h) { - return Math.round(ms / h) + 'h'; - } - if (msAbs >= m) { - return Math.round(ms / m) + 'm'; - } - if (msAbs >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. + +*/ -function fmtLong(ms) { - var msAbs = Math.abs(ms); - if (msAbs >= d) { - return plural(ms, msAbs, d, 'day'); - } - if (msAbs >= h) { - return plural(ms, msAbs, h, 'hour'); - } - if (msAbs >= m) { - return plural(ms, msAbs, m, 'minute'); - } - if (msAbs >= s) { - return plural(ms, msAbs, s, 'second'); - } - return ms + ' ms'; -} +var styles = {}; +module['exports'] = styles; -/** - * Pluralization helper. - */ +var codes = { + reset: [0, 0], -function plural(ms, msAbs, n, name) { - var isPlural = msAbs >= n * 1.5; - return Math.round(ms / n) + ' ' + name + (isPlural ? 's' : ''); -} + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29], + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + gray: [90, 39], + grey: [90, 39], -/***/ }), + brightRed: [91, 39], + brightGreen: [92, 39], + brightYellow: [93, 39], + brightBlue: [94, 39], + brightMagenta: [95, 39], + brightCyan: [96, 39], + brightWhite: [97, 39], -/***/ 28222: -/***/ ((module, exports, __nccwpck_require__) => { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + bgGray: [100, 49], + bgGrey: [100, 49], -/* eslint-env browser */ + bgBrightRed: [101, 49], + bgBrightGreen: [102, 49], + bgBrightYellow: [103, 49], + bgBrightBlue: [104, 49], + bgBrightMagenta: [105, 49], + bgBrightCyan: [106, 49], + bgBrightWhite: [107, 49], -/** - * This is the web browser implementation of `debug()`. - */ + // legacy styles for colors pre v1.0.0 + blackBG: [40, 49], + redBG: [41, 49], + greenBG: [42, 49], + yellowBG: [43, 49], + blueBG: [44, 49], + magentaBG: [45, 49], + cyanBG: [46, 49], + whiteBG: [47, 49], -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = localstorage(); -exports.destroy = (() => { - let warned = false; +}; - return () => { - if (!warned) { - warned = true; - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } - }; -})(); +Object.keys(codes).forEach(function(key) { + var val = codes[key]; + var style = styles[key] = []; + style.open = '\u001b[' + val[0] + 'm'; + style.close = '\u001b[' + val[1] + 'm'; +}); -/** - * Colors. - */ -exports.colors = [ - '#0000CC', - '#0000FF', - '#0033CC', - '#0033FF', - '#0066CC', - '#0066FF', - '#0099CC', - '#0099FF', - '#00CC00', - '#00CC33', - '#00CC66', - '#00CC99', - '#00CCCC', - '#00CCFF', - '#3300CC', - '#3300FF', - '#3333CC', - '#3333FF', - '#3366CC', - '#3366FF', - '#3399CC', - '#3399FF', - '#33CC00', - '#33CC33', - '#33CC66', - '#33CC99', - '#33CCCC', - '#33CCFF', - '#6600CC', - '#6600FF', - '#6633CC', - '#6633FF', - '#66CC00', - '#66CC33', - '#9900CC', - '#9900FF', - '#9933CC', - '#9933FF', - '#99CC00', - '#99CC33', - '#CC0000', - '#CC0033', - '#CC0066', - '#CC0099', - '#CC00CC', - '#CC00FF', - '#CC3300', - '#CC3333', - '#CC3366', - '#CC3399', - '#CC33CC', - '#CC33FF', - '#CC6600', - '#CC6633', - '#CC9900', - '#CC9933', - '#CCCC00', - '#CCCC33', - '#FF0000', - '#FF0033', - '#FF0066', - '#FF0099', - '#FF00CC', - '#FF00FF', - '#FF3300', - '#FF3333', - '#FF3366', - '#FF3399', - '#FF33CC', - '#FF33FF', - '#FF6600', - '#FF6633', - '#FF9900', - '#FF9933', - '#FFCC00', - '#FFCC33' -]; +/***/ }), -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ +/***/ 10223: +/***/ ((module) => { -// eslint-disable-next-line complexity -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { - return true; - } +"use strict"; +/* +MIT License - // Internet Explorer and Edge do not support colors. - if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { - return false; - } +Copyright (c) Sindre Sorhus (sindresorhus.com) - // Is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // Is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // Is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // Double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} +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: -/** - * Colorize log arguments if enabled. - * - * @api public - */ +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. -function formatArgs(args) { - args[0] = (this.useColors ? '%c' : '') + - this.namespace + - (this.useColors ? ' %c' : ' ') + - args[0] + - (this.useColors ? '%c ' : ' ') + - '+' + module.exports.humanize(this.diff); +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. +*/ - if (!this.useColors) { - return; - } - const c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit'); - // The final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - let index = 0; - let lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, match => { - if (match === '%%') { - return; - } - index++; - if (match === '%c') { - // We only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); +module.exports = function(flag, argv) { + argv = argv || process.argv; - args.splice(lastC, 0, c); -} + var terminatorPos = argv.indexOf('--'); + var prefix = /^-{1,2}/.test(flag) ? '' : '--'; + var pos = argv.indexOf(prefix + flag); -/** - * Invokes `console.debug()` when available. - * No-op when `console.debug` is not a "function". - * If `console.debug` is not available, falls back - * to `console.log`. - * - * @api public - */ -exports.log = console.debug || console.log || (() => {}); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ -function save(namespaces) { - try { - if (namespaces) { - exports.storage.setItem('debug', namespaces); - } else { - exports.storage.removeItem('debug'); - } - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ -function load() { - let r; - try { - r = exports.storage.getItem('debug'); - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } +/***/ }), - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } +/***/ 10662: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return r; -} +"use strict"; +/* +The MIT License (MIT) -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ +Copyright (c) Sindre Sorhus (sindresorhus.com) -function localstorage() { - try { - // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context - // The Browser also has localStorage in the global context. - return localStorage; - } catch (error) { - // Swallow - // XXX (@Qix-) should we be logging these? - } -} +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: -module.exports = __nccwpck_require__(46243)(exports); +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. -const {formatters} = module.exports; +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. -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ +*/ -formatters.j = function (v) { - try { - return JSON.stringify(v); - } catch (error) { - return '[UnexpectedJSONParseError]: ' + error.message; - } -}; -/***/ }), +var os = __nccwpck_require__(12087); +var hasFlag = __nccwpck_require__(10223); -/***/ 46243: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var env = process.env; +var forceColor = void 0; +if (hasFlag('no-color') || hasFlag('no-colors') || hasFlag('color=false')) { + forceColor = false; +} else if (hasFlag('color') || hasFlag('colors') || hasFlag('color=true') + || hasFlag('color=always')) { + forceColor = true; +} +if ('FORCE_COLOR' in env) { + forceColor = env.FORCE_COLOR.length === 0 + || parseInt(env.FORCE_COLOR, 10) !== 0; +} -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - */ +function translateLevel(level) { + if (level === 0) { + return false; + } -function setup(env) { - createDebug.debug = createDebug; - createDebug.default = createDebug; - createDebug.coerce = coerce; - createDebug.disable = disable; - createDebug.enable = enable; - createDebug.enabled = enabled; - createDebug.humanize = __nccwpck_require__(84697); - createDebug.destroy = destroy; + return { + level: level, + hasBasic: true, + has256: level >= 2, + has16m: level >= 3, + }; +} - Object.keys(env).forEach(key => { - createDebug[key] = env[key]; - }); +function supportsColor(stream) { + if (forceColor === false) { + return 0; + } - /** - * The currently active debug mode names, and names to skip. - */ + if (hasFlag('color=16m') || hasFlag('color=full') + || hasFlag('color=truecolor')) { + return 3; + } - createDebug.names = []; - createDebug.skips = []; + if (hasFlag('color=256')) { + return 2; + } - /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - createDebug.formatters = {}; + if (stream && !stream.isTTY && forceColor !== true) { + return 0; + } - /** - * Selects a color for a debug namespace - * @param {String} namespace The namespace string for the for the debug instance to be colored - * @return {Number|String} An ANSI color code for the given namespace - * @api private - */ - function selectColor(namespace) { - let hash = 0; + var min = forceColor ? 1 : 0; - for (let i = 0; i < namespace.length; i++) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } + if (process.platform === 'win32') { + // Node.js 7.5.0 is the first version of Node.js to include a patch to + // libuv that enables 256 color output on Windows. Anything earlier and it + // won't work. However, here we target Node.js 8 at minimum as it is an LTS + // release, and Node.js 7 is not. Windows 10 build 10586 is the first + // Windows release that supports 256 colors. Windows 10 build 14931 is the + // first release that supports 16m/TrueColor. + var osRelease = os.release().split('.'); + if (Number(process.versions.node.split('.')[0]) >= 8 + && Number(osRelease[0]) >= 10 && Number(osRelease[2]) >= 10586) { + return Number(osRelease[2]) >= 14931 ? 3 : 2; + } - return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; - } - createDebug.selectColor = selectColor; + return 1; + } - /** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - function createDebug(namespace) { - let prevTime; - let enableOverride = null; + if ('CI' in env) { + if (['TRAVIS', 'CIRCLECI', 'APPVEYOR', 'GITLAB_CI'].some(function(sign) { + return sign in env; + }) || env.CI_NAME === 'codeship') { + return 1; + } - function debug(...args) { - // Disabled? - if (!debug.enabled) { - return; - } + return min; + } - const self = debug; + if ('TEAMCITY_VERSION' in env) { + return (/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(env.TEAMCITY_VERSION) ? 1 : 0 + ); + } + + if ('TERM_PROGRAM' in env) { + var version = parseInt((env.TERM_PROGRAM_VERSION || '').split('.')[0], 10); - // Set `diff` timestamp - const curr = Number(new Date()); - const ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; + switch (env.TERM_PROGRAM) { + case 'iTerm.app': + return version >= 3 ? 3 : 2; + case 'Hyper': + return 3; + case 'Apple_Terminal': + return 2; + // No default + } + } - args[0] = createDebug.coerce(args[0]); + if (/-256(color)?$/i.test(env.TERM)) { + return 2; + } - if (typeof args[0] !== 'string') { - // Anything else let's inspect with %O - args.unshift('%O'); - } + if (/^screen|^xterm|^vt100|^rxvt|color|ansi|cygwin|linux/i.test(env.TERM)) { + return 1; + } - // Apply any `formatters` transformations - let index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { - // If we encounter an escaped % then don't increase the array index - if (match === '%%') { - return '%'; - } - index++; - const formatter = createDebug.formatters[format]; - if (typeof formatter === 'function') { - const val = args[index]; - match = formatter.call(self, val); + if ('COLORTERM' in env) { + return 1; + } - // Now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); + if (env.TERM === 'dumb') { + return min; + } - // Apply env-specific formatting (colors, etc.) - createDebug.formatArgs.call(self, args); + return min; +} - const logFn = self.log || createDebug.log; - logFn.apply(self, args); - } +function getSupportLevel(stream) { + var level = supportsColor(stream); + return translateLevel(level); +} - debug.namespace = namespace; - debug.useColors = createDebug.useColors(); - debug.color = createDebug.selectColor(namespace); - debug.extend = extend; - debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. +module.exports = { + supportsColor: getSupportLevel, + stdout: getSupportLevel(process.stdout), + stderr: getSupportLevel(process.stderr), +}; - Object.defineProperty(debug, 'enabled', { - enumerable: true, - configurable: false, - get: () => enableOverride === null ? createDebug.enabled(namespace) : enableOverride, - set: v => { - enableOverride = v; - } - }); - // Env-specific initialization logic for debug instances - if (typeof createDebug.init === 'function') { - createDebug.init(debug); - } +/***/ }), - return debug; - } +/***/ 41997: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function extend(namespace, delimiter) { - const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); - newDebug.log = this.log; - return newDebug; - } +// +// Remark: Requiring this file will use the "safe" colors API, +// which will not touch String.prototype. +// +// var colors = require('colors/safe'); +// colors.red("foo") +// +// +var colors = __nccwpck_require__(43595); +module['exports'] = colors; - /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - function enable(namespaces) { - createDebug.save(namespaces); - createDebug.names = []; - createDebug.skips = []; +/***/ }), - let i; - const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - const len = split.length; +/***/ 85443: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - for (i = 0; i < len; i++) { - if (!split[i]) { - // ignore empty strings - continue; - } +var util = __nccwpck_require__(31669); +var Stream = __nccwpck_require__(92413).Stream; +var DelayedStream = __nccwpck_require__(18611); - namespaces = split[i].replace(/\*/g, '.*?'); +module.exports = CombinedStream; +function CombinedStream() { + this.writable = false; + this.readable = true; + this.dataSize = 0; + this.maxDataSize = 2 * 1024 * 1024; + this.pauseStreams = true; - if (namespaces[0] === '-') { - createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - createDebug.names.push(new RegExp('^' + namespaces + '$')); - } - } - } + this._released = false; + this._streams = []; + this._currentStream = null; + this._insideLoop = false; + this._pendingNext = false; +} +util.inherits(CombinedStream, Stream); - /** - * Disable debug output. - * - * @return {String} namespaces - * @api public - */ - function disable() { - const namespaces = [ - ...createDebug.names.map(toNamespace), - ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) - ].join(','); - createDebug.enable(''); - return namespaces; - } +CombinedStream.create = function(options) { + var combinedStream = new this(); - /** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - function enabled(name) { - if (name[name.length - 1] === '*') { - return true; - } + options = options || {}; + for (var option in options) { + combinedStream[option] = options[option]; + } - let i; - let len; + return combinedStream; +}; - for (i = 0, len = createDebug.skips.length; i < len; i++) { - if (createDebug.skips[i].test(name)) { - return false; - } - } +CombinedStream.isStreamLike = function(stream) { + return (typeof stream !== 'function') + && (typeof stream !== 'string') + && (typeof stream !== 'boolean') + && (typeof stream !== 'number') + && (!Buffer.isBuffer(stream)); +}; - for (i = 0, len = createDebug.names.length; i < len; i++) { - if (createDebug.names[i].test(name)) { - return true; - } - } +CombinedStream.prototype.append = function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); - return false; - } + if (isStreamLike) { + if (!(stream instanceof DelayedStream)) { + var newStream = DelayedStream.create(stream, { + maxDataSize: Infinity, + pauseStream: this.pauseStreams, + }); + stream.on('data', this._checkDataSize.bind(this)); + stream = newStream; + } - /** - * Convert regexp to namespace - * - * @param {RegExp} regxep - * @return {String} namespace - * @api private - */ - function toNamespace(regexp) { - return regexp.toString() - .substring(2, regexp.toString().length - 2) - .replace(/\.\*\?$/, '*'); - } + this._handleErrors(stream); - /** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - function coerce(val) { - if (val instanceof Error) { - return val.stack || val.message; - } - return val; - } + if (this.pauseStreams) { + stream.pause(); + } + } - /** - * XXX DO NOT USE. This is a temporary stub function. - * XXX It WILL be removed in the next major release. - */ - function destroy() { - console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); - } + this._streams.push(stream); + return this; +}; - createDebug.enable(createDebug.load()); +CombinedStream.prototype.pipe = function(dest, options) { + Stream.prototype.pipe.call(this, dest, options); + this.resume(); + return dest; +}; - return createDebug; -} +CombinedStream.prototype._getNext = function() { + this._currentStream = null; -module.exports = setup; + if (this._insideLoop) { + this._pendingNext = true; + return; // defer call + } + this._insideLoop = true; + try { + do { + this._pendingNext = false; + this._realGetNext(); + } while (this._pendingNext); + } finally { + this._insideLoop = false; + } +}; -/***/ }), +CombinedStream.prototype._realGetNext = function() { + var stream = this._streams.shift(); -/***/ 38237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Detect Electron renderer / nwjs process, which is node, but we should - * treat as a browser. - */ + if (typeof stream == 'undefined') { + this.end(); + return; + } -if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { - module.exports = __nccwpck_require__(28222); -} else { - module.exports = __nccwpck_require__(35332); -} + if (typeof stream !== 'function') { + this._pipeNext(stream); + return; + } + var getStream = stream; + getStream(function(stream) { + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('data', this._checkDataSize.bind(this)); + this._handleErrors(stream); + } -/***/ }), + this._pipeNext(stream); + }.bind(this)); +}; -/***/ 35332: -/***/ ((module, exports, __nccwpck_require__) => { +CombinedStream.prototype._pipeNext = function(stream) { + this._currentStream = stream; -/** - * Module dependencies. - */ + var isStreamLike = CombinedStream.isStreamLike(stream); + if (isStreamLike) { + stream.on('end', this._getNext.bind(this)); + stream.pipe(this, {end: false}); + return; + } -const tty = __nccwpck_require__(33867); -const util = __nccwpck_require__(31669); + var value = stream; + this.write(value); + this._getNext(); +}; -/** - * This is the Node.js implementation of `debug()`. - */ +CombinedStream.prototype._handleErrors = function(stream) { + var self = this; + stream.on('error', function(err) { + self._emitError(err); + }); +}; -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.destroy = util.deprecate( - () => {}, - 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' -); +CombinedStream.prototype.write = function(data) { + this.emit('data', data); +}; -/** - * Colors. - */ +CombinedStream.prototype.pause = function() { + if (!this.pauseStreams) { + return; + } -exports.colors = [6, 2, 3, 4, 5, 1]; + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.pause) == 'function') this._currentStream.pause(); + this.emit('pause'); +}; -try { - // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) - // eslint-disable-next-line import/no-extraneous-dependencies - const supportsColor = __nccwpck_require__(59318); +CombinedStream.prototype.resume = function() { + if (!this._released) { + this._released = true; + this.writable = true; + this._getNext(); + } - if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { - exports.colors = [ - 20, - 21, - 26, - 27, - 32, - 33, - 38, - 39, - 40, - 41, - 42, - 43, - 44, - 45, - 56, - 57, - 62, - 63, - 68, - 69, - 74, - 75, - 76, - 77, - 78, - 79, - 80, - 81, - 92, - 93, - 98, - 99, - 112, - 113, - 128, - 129, - 134, - 135, - 148, - 149, - 160, - 161, - 162, - 163, - 164, - 165, - 166, - 167, - 168, - 169, - 170, - 171, - 172, - 173, - 178, - 179, - 184, - 185, - 196, - 197, - 198, - 199, - 200, - 201, - 202, - 203, - 204, - 205, - 206, - 207, - 208, - 209, - 214, - 215, - 220, - 221 - ]; - } -} catch (error) { - // Swallow - we only care if `supports-color` is available; it doesn't have to be. -} + if(this.pauseStreams && this._currentStream && typeof(this._currentStream.resume) == 'function') this._currentStream.resume(); + this.emit('resume'); +}; -/** - * Build up the default `inspectOpts` object from the environment variables. - * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js - */ +CombinedStream.prototype.end = function() { + this._reset(); + this.emit('end'); +}; -exports.inspectOpts = Object.keys(process.env).filter(key => { - return /^debug_/i.test(key); -}).reduce((obj, key) => { - // Camel-case - const prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, (_, k) => { - return k.toUpperCase(); - }); +CombinedStream.prototype.destroy = function() { + this._reset(); + this.emit('close'); +}; - // Coerce string value into JS value - let val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) { - val = true; - } else if (/^(no|off|false|disabled)$/i.test(val)) { - val = false; - } else if (val === 'null') { - val = null; - } else { - val = Number(val); - } +CombinedStream.prototype._reset = function() { + this.writable = false; + this._streams = []; + this._currentStream = null; +}; - obj[prop] = val; - return obj; -}, {}); +CombinedStream.prototype._checkDataSize = function() { + this._updateDataSize(); + if (this.dataSize <= this.maxDataSize) { + return; + } -/** - * Is stdout a TTY? Colored output is enabled when `true`. - */ + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.'; + this._emitError(new Error(message)); +}; -function useColors() { - return 'colors' in exports.inspectOpts ? - Boolean(exports.inspectOpts.colors) : - tty.isatty(process.stderr.fd); -} +CombinedStream.prototype._updateDataSize = function() { + this.dataSize = 0; -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ + var self = this; + this._streams.forEach(function(stream) { + if (!stream.dataSize) { + return; + } -function formatArgs(args) { - const {namespace: name, useColors} = this; + self.dataSize += stream.dataSize; + }); - if (useColors) { - const c = this.color; - const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); - const prefix = ` ${colorCode};1m${name} \u001B[0m`; + if (this._currentStream && this._currentStream.dataSize) { + this.dataSize += this._currentStream.dataSize; + } +}; - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); - } else { - args[0] = getDate() + name + ' ' + args[0]; - } -} +CombinedStream.prototype._emitError = function(err) { + this._reset(); + this.emit('error', err); +}; -function getDate() { - if (exports.inspectOpts.hideDate) { - return ''; - } - return new Date().toISOString() + ' '; -} -/** - * Invokes `util.format()` with the specified arguments and writes to stderr. - */ +/***/ }), -function log(...args) { - return process.stderr.write(util.format(...args) + '\n'); -} +/***/ 61904: +/***/ ((module, exports, __nccwpck_require__) => { /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private + * Module dependencies. */ -function save(namespaces) { - if (namespaces) { - process.env.DEBUG = namespaces; - } else { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } -} -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ +const EventEmitter = __nccwpck_require__(28614).EventEmitter; +const spawn = __nccwpck_require__(63129).spawn; +const path = __nccwpck_require__(85622); +const fs = __nccwpck_require__(35747); -function load() { - return process.env.DEBUG; -} +// @ts-check -/** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. - */ +class Option { + /** + * Initialize a new `Option` with the given `flags` and `description`. + * + * @param {string} flags + * @param {string} description + * @api public + */ -function init(debug) { - debug.inspectOpts = {}; + constructor(flags, description) { + this.flags = flags; + this.required = flags.includes('<'); // A value must be supplied when the option is specified. + this.optional = flags.includes('['); // A value is optional when the option is specified. + // variadic test ignores et al which might be used to describe custom splitting of single argument + this.variadic = /\w\.\.\.[>\]]$/.test(flags); // The option can take multiple values. + this.mandatory = false; // The option must have a value after parsing, which usually means it must be specified on command line. + const optionFlags = _parseOptionFlags(flags); + this.short = optionFlags.shortFlag; + this.long = optionFlags.longFlag; + this.negate = false; + if (this.long) { + this.negate = this.long.startsWith('--no-'); + } + this.description = description || ''; + this.defaultValue = undefined; + } - const keys = Object.keys(exports.inspectOpts); - for (let i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} + /** + * Return option name. + * + * @return {string} + * @api private + */ -module.exports = __nccwpck_require__(46243)(exports); + name() { + if (this.long) { + return this.long.replace(/^--/, ''); + } + return this.short.replace(/^-/, ''); + }; -const {formatters} = module.exports; + /** + * Return option name, in a camelcase format that can be used + * as a object attribute key. + * + * @return {string} + * @api private + */ -/** - * Map %o to `util.inspect()`, all on a single line. - */ + attributeName() { + return camelcase(this.name().replace(/^no-/, '')); + }; -formatters.o = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n') - .map(str => str.trim()) - .join(' '); -}; + /** + * Check if `arg` matches the short or long flag. + * + * @param {string} arg + * @return {boolean} + * @api private + */ + + is(arg) { + return this.short === arg || this.long === arg; + }; +} /** - * Map %O to `util.inspect()`, allowing multiple lines if needed. + * CommanderError class + * @class */ +class CommanderError extends Error { + /** + * Constructs the CommanderError class + * @param {number} exitCode suggested exit code which could be used with process.exit + * @param {string} code an id string representing the error + * @param {string} message human-readable description of the error + * @constructor + */ + constructor(exitCode, code, message) { + super(message); + // properly capture stack trace in Node.js + Error.captureStackTrace(this, this.constructor); + this.name = this.constructor.name; + this.code = code; + this.exitCode = exitCode; + this.nestedError = undefined; + } +} -formatters.O = function (v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; - +class Command extends EventEmitter { + /** + * Initialize a new `Command`. + * + * @param {string} [name] + * @api public + */ -/***/ }), + constructor(name) { + super(); + this.commands = []; + this.options = []; + this.parent = null; + this._allowUnknownOption = false; + this._args = []; + this.rawArgs = null; + this._scriptPath = null; + this._name = name || ''; + this._optionValues = {}; + this._storeOptionsAsProperties = true; // backwards compatible by default + this._storeOptionsAsPropertiesCalled = false; + this._passCommandToAction = true; // backwards compatible by default + this._actionResults = []; + this._actionHandler = null; + this._executableHandler = false; + this._executableFile = null; // custom name for executable + this._defaultCommandName = null; + this._exitCallback = null; + this._aliases = []; + this._combineFlagAndOptionalValue = true; -/***/ 56323: -/***/ ((module) => { + this._hidden = false; + this._hasHelpOption = true; + this._helpFlags = '-h, --help'; + this._helpDescription = 'display help for command'; + this._helpShortFlag = '-h'; + this._helpLongFlag = '--help'; + this._hasImplicitHelpCommand = undefined; // Deliberately undefined, not decided whether true or false + this._helpCommandName = 'help'; + this._helpCommandnameAndArgs = 'help [command]'; + this._helpCommandDescription = 'display help for command'; + } -"use strict"; + /** + * Define a command. + * + * There are two styles of command: pay attention to where to put the description. + * + * Examples: + * + * // Command implemented using action handler (description is supplied separately to `.command`) + * program + * .command('clone [destination]') + * .description('clone a repository into a newly created directory') + * .action((source, destination) => { + * console.log('clone command called'); + * }); + * + * // Command implemented using separate executable file (description is second parameter to `.command`) + * program + * .command('start ', 'start named service') + * .command('stop [service]', 'stop named service, or all if no name supplied'); + * + * @param {string} nameAndArgs - command name and arguments, args are `` or `[optional]` and last may also be `variadic...` + * @param {Object|string} [actionOptsOrExecDesc] - configuration options (for action), or description (for executable) + * @param {Object} [execOpts] - configuration options (for executable) + * @return {Command} returns new command for action handler, or `this` for executable command + * @api public + */ + command(nameAndArgs, actionOptsOrExecDesc, execOpts) { + let desc = actionOptsOrExecDesc; + let opts = execOpts; + if (typeof desc === 'object' && desc !== null) { + opts = desc; + desc = null; + } + opts = opts || {}; + const args = nameAndArgs.split(/ +/); + const cmd = this.createCommand(args.shift()); -var isMergeableObject = function isMergeableObject(value) { - return isNonNullObject(value) - && !isSpecial(value) -}; + if (desc) { + cmd.description(desc); + cmd._executableHandler = true; + } + if (opts.isDefault) this._defaultCommandName = cmd._name; -function isNonNullObject(value) { - return !!value && typeof value === 'object' -} + cmd._hidden = !!(opts.noHelp || opts.hidden); + cmd._hasHelpOption = this._hasHelpOption; + cmd._helpFlags = this._helpFlags; + cmd._helpDescription = this._helpDescription; + cmd._helpShortFlag = this._helpShortFlag; + cmd._helpLongFlag = this._helpLongFlag; + cmd._helpCommandName = this._helpCommandName; + cmd._helpCommandnameAndArgs = this._helpCommandnameAndArgs; + cmd._helpCommandDescription = this._helpCommandDescription; + cmd._exitCallback = this._exitCallback; + cmd._storeOptionsAsProperties = this._storeOptionsAsProperties; + cmd._passCommandToAction = this._passCommandToAction; + cmd._combineFlagAndOptionalValue = this._combineFlagAndOptionalValue; -function isSpecial(value) { - var stringValue = Object.prototype.toString.call(value); + cmd._executableFile = opts.executableFile || null; // Custom name for executable file, set missing to null to match constructor + this.commands.push(cmd); + cmd._parseExpectedArgs(args); + cmd.parent = this; - return stringValue === '[object RegExp]' - || stringValue === '[object Date]' - || isReactElement(value) -} + if (desc) return this; + return cmd; + }; -// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 -var canUseSymbol = typeof Symbol === 'function' && Symbol.for; -var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; + /** + * Factory routine to create a new unattached command. + * + * See .command() for creating an attached subcommand, which uses this routine to + * create the command. You can override createCommand to customise subcommands. + * + * @param {string} [name] + * @return {Command} new command + * @api public + */ -function isReactElement(value) { - return value.$$typeof === REACT_ELEMENT_TYPE -} + createCommand(name) { + return new Command(name); + }; -function emptyTarget(val) { - return Array.isArray(val) ? [] : {} -} + /** + * Add a prepared subcommand. + * + * See .command() for creating an attached subcommand which inherits settings from its parent. + * + * @param {Command} cmd - new subcommand + * @param {Object} [opts] - configuration options + * @return {Command} `this` command for chaining + * @api public + */ -function cloneUnlessOtherwiseSpecified(value, options) { - return (options.clone !== false && options.isMergeableObject(value)) - ? deepmerge(emptyTarget(value), value, options) - : value -} + addCommand(cmd, opts) { + if (!cmd._name) throw new Error('Command passed to .addCommand() must have a name'); -function defaultArrayMerge(target, source, options) { - return target.concat(source).map(function(element) { - return cloneUnlessOtherwiseSpecified(element, options) - }) -} + // To keep things simple, block automatic name generation for deeply nested executables. + // Fail fast and detect when adding rather than later when parsing. + function checkExplicitNames(commandArray) { + commandArray.forEach((cmd) => { + if (cmd._executableHandler && !cmd._executableFile) { + throw new Error(`Must specify executableFile for deeply nested executable: ${cmd.name()}`); + } + checkExplicitNames(cmd.commands); + }); + } + checkExplicitNames(cmd.commands); -function getMergeFunction(key, options) { - if (!options.customMerge) { - return deepmerge - } - var customMerge = options.customMerge(key); - return typeof customMerge === 'function' ? customMerge : deepmerge -} + opts = opts || {}; + if (opts.isDefault) this._defaultCommandName = cmd._name; + if (opts.noHelp || opts.hidden) cmd._hidden = true; // modifying passed command due to existing implementation -function getEnumerableOwnPropertySymbols(target) { - return Object.getOwnPropertySymbols - ? Object.getOwnPropertySymbols(target).filter(function(symbol) { - return target.propertyIsEnumerable(symbol) - }) - : [] -} + this.commands.push(cmd); + cmd.parent = this; + return this; + }; -function getKeys(target) { - return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) -} + /** + * Define argument syntax for the command. + * + * @api public + */ -function propertyIsOnObject(object, property) { - try { - return property in object - } catch(_) { - return false - } -} + arguments(desc) { + return this._parseExpectedArgs(desc.split(/ +/)); + }; -// Protects from prototype poisoning and unexpected merging up the prototype chain. -function propertyIsUnsafe(target, key) { - return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, - && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, - && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. -} + /** + * Override default decision whether to add implicit help command. + * + * addHelpCommand() // force on + * addHelpCommand(false); // force off + * addHelpCommand('help [cmd]', 'display help for [cmd]'); // force on with custom details + * + * @return {Command} `this` command for chaining + * @api public + */ -function mergeObject(target, source, options) { - var destination = {}; - if (options.isMergeableObject(target)) { - getKeys(target).forEach(function(key) { - destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); - }); - } - getKeys(source).forEach(function(key) { - if (propertyIsUnsafe(target, key)) { - return - } + addHelpCommand(enableOrNameAndArgs, description) { + if (enableOrNameAndArgs === false) { + this._hasImplicitHelpCommand = false; + } else { + this._hasImplicitHelpCommand = true; + if (typeof enableOrNameAndArgs === 'string') { + this._helpCommandName = enableOrNameAndArgs.split(' ')[0]; + this._helpCommandnameAndArgs = enableOrNameAndArgs; + } + this._helpCommandDescription = description || this._helpCommandDescription; + } + return this; + }; - if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { - destination[key] = getMergeFunction(key, options)(target[key], source[key], options); - } else { - destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); - } - }); - return destination -} + /** + * @return {boolean} + * @api private + */ -function deepmerge(target, source, options) { - options = options || {}; - options.arrayMerge = options.arrayMerge || defaultArrayMerge; - options.isMergeableObject = options.isMergeableObject || isMergeableObject; - // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() - // implementations can use it. The caller may not replace it. - options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; + _lazyHasImplicitHelpCommand() { + if (this._hasImplicitHelpCommand === undefined) { + this._hasImplicitHelpCommand = this.commands.length && !this._actionHandler && !this._findCommand('help'); + } + return this._hasImplicitHelpCommand; + }; - var sourceIsArray = Array.isArray(source); - var targetIsArray = Array.isArray(target); - var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; + /** + * Parse expected `args`. + * + * For example `["[type]"]` becomes `[{ required: false, name: 'type' }]`. + * + * @param {Array} args + * @return {Command} `this` command for chaining + * @api private + */ - if (!sourceAndTargetTypesMatch) { - return cloneUnlessOtherwiseSpecified(source, options) - } else if (sourceIsArray) { - return options.arrayMerge(target, source, options) - } else { - return mergeObject(target, source, options) - } -} + _parseExpectedArgs(args) { + if (!args.length) return; + args.forEach((arg) => { + const argDetails = { + required: false, + name: '', + variadic: false + }; -deepmerge.all = function deepmergeAll(array, options) { - if (!Array.isArray(array)) { - throw new Error('first argument should be an array') - } + switch (arg[0]) { + case '<': + argDetails.required = true; + argDetails.name = arg.slice(1, -1); + break; + case '[': + argDetails.name = arg.slice(1, -1); + break; + } - return array.reduce(function(prev, next) { - return deepmerge(prev, next, options) - }, {}) -}; + if (argDetails.name.length > 3 && argDetails.name.slice(-3) === '...') { + argDetails.variadic = true; + argDetails.name = argDetails.name.slice(0, -3); + } + if (argDetails.name) { + this._args.push(argDetails); + } + }); + this._args.forEach((arg, i) => { + if (arg.variadic && i < this._args.length - 1) { + throw new Error(`only the last argument can be variadic '${arg.name}'`); + } + }); + return this; + }; -var deepmerge_1 = deepmerge; + /** + * Register callback to use as replacement for calling process.exit. + * + * @param {Function} [fn] optional callback which will be passed a CommanderError, defaults to throwing + * @return {Command} `this` command for chaining + * @api public + */ -module.exports = deepmerge_1; + exitOverride(fn) { + if (fn) { + this._exitCallback = fn; + } else { + this._exitCallback = (err) => { + if (err.code !== 'commander.executeSubCommandAsync') { + throw err; + } else { + // Async callback from spawn events, not useful to throw. + } + }; + } + return this; + }; + /** + * Call process.exit, and _exitCallback if defined. + * + * @param {number} exitCode exit code for using with process.exit + * @param {string} code an id string representing the error + * @param {string} message human-readable description of the error + * @return never + * @api private + */ -/***/ }), + _exit(exitCode, code, message) { + if (this._exitCallback) { + this._exitCallback(new CommanderError(exitCode, code, message)); + // Expecting this line is not reached. + } + process.exit(exitCode); + }; -/***/ 18611: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + /** + * Register callback `fn` for the command. + * + * Examples: + * + * program + * .command('help') + * .description('display verbose help') + * .action(function() { + * // output help here + * }); + * + * @param {Function} fn + * @return {Command} `this` command for chaining + * @api public + */ -var Stream = __nccwpck_require__(92413).Stream; -var util = __nccwpck_require__(31669); + action(fn) { + const listener = (args) => { + // The .action callback takes an extra parameter which is the command or options. + const expectedArgsCount = this._args.length; + const actionArgs = args.slice(0, expectedArgsCount); + if (this._passCommandToAction) { + actionArgs[expectedArgsCount] = this; + } else { + actionArgs[expectedArgsCount] = this.opts(); + } + // Add the extra arguments so available too. + if (args.length > expectedArgsCount) { + actionArgs.push(args.slice(expectedArgsCount)); + } -module.exports = DelayedStream; -function DelayedStream() { - this.source = null; - this.dataSize = 0; - this.maxDataSize = 1024 * 1024; - this.pauseStream = true; + const actionResult = fn.apply(this, actionArgs); + // Remember result in case it is async. Assume parseAsync getting called on root. + let rootCommand = this; + while (rootCommand.parent) { + rootCommand = rootCommand.parent; + } + rootCommand._actionResults.push(actionResult); + }; + this._actionHandler = listener; + return this; + }; - this._maxDataSizeExceeded = false; - this._released = false; - this._bufferedEvents = []; -} -util.inherits(DelayedStream, Stream); + /** + * Internal routine to check whether there is a clash storing option value with a Command property. + * + * @param {Option} option + * @api private + */ -DelayedStream.create = function(source, options) { - var delayedStream = new this(); + _checkForOptionNameClash(option) { + if (!this._storeOptionsAsProperties || this._storeOptionsAsPropertiesCalled) { + // Storing options safely, or user has been explicit and up to them. + return; + } + // User may override help, and hard to tell if worth warning. + if (option.name() === 'help') { + return; + } - options = options || {}; - for (var option in options) { - delayedStream[option] = options[option]; - } + const commandProperty = this._getOptionValue(option.attributeName()); + if (commandProperty === undefined) { + // no clash + return; + } - delayedStream.source = source; + let foundClash = true; + if (option.negate) { + // It is ok if define foo before --no-foo. + const positiveLongFlag = option.long.replace(/^--no-/, '--'); + foundClash = !this._findOption(positiveLongFlag); + } else if (option.long) { + const negativeLongFlag = option.long.replace(/^--/, '--no-'); + foundClash = !this._findOption(negativeLongFlag); + } - var realEmit = source.emit; - source.emit = function() { - delayedStream._handleEmit(arguments); - return realEmit.apply(source, arguments); + if (foundClash) { + throw new Error(`option '${option.name()}' clashes with existing property '${option.attributeName()}' on Command +- call storeOptionsAsProperties(false) to store option values safely, +- or call storeOptionsAsProperties(true) to suppress this check, +- or change option name + +Read more on https://git.io/JJc0W`); + } }; - source.on('error', function() {}); - if (delayedStream.pauseStream) { - source.pause(); - } + /** + * Internal implementation shared by .option() and .requiredOption() + * + * @param {Object} config + * @param {string} flags + * @param {string} description + * @param {Function|*} [fn] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + * @api private + */ - return delayedStream; -}; + _optionEx(config, flags, description, fn, defaultValue) { + const option = new Option(flags, description); + const oname = option.name(); + const name = option.attributeName(); + option.mandatory = !!config.mandatory; -Object.defineProperty(DelayedStream.prototype, 'readable', { - configurable: true, - enumerable: true, - get: function() { - return this.source.readable; - } -}); + this._checkForOptionNameClash(option); -DelayedStream.prototype.setEncoding = function() { - return this.source.setEncoding.apply(this.source, arguments); -}; + // default as 3rd arg + if (typeof fn !== 'function') { + if (fn instanceof RegExp) { + // This is a bit simplistic (especially no error messages), and probably better handled by caller using custom option processing. + // No longer documented in README, but still present for backwards compatibility. + const regex = fn; + fn = (val, def) => { + const m = regex.exec(val); + return m ? m[0] : def; + }; + } else { + defaultValue = fn; + fn = null; + } + } -DelayedStream.prototype.resume = function() { - if (!this._released) { - this.release(); - } + // preassign default value for --no-*, [optional], , or plain flag if boolean value + if (option.negate || option.optional || option.required || typeof defaultValue === 'boolean') { + // when --no-foo we make sure default is true, unless a --foo option is already defined + if (option.negate) { + const positiveLongFlag = option.long.replace(/^--no-/, '--'); + defaultValue = this._findOption(positiveLongFlag) ? this._getOptionValue(name) : true; + } + // preassign only if we have a default + if (defaultValue !== undefined) { + this._setOptionValue(name, defaultValue); + option.defaultValue = defaultValue; + } + } - this.source.resume(); -}; + // register the option + this.options.push(option); -DelayedStream.prototype.pause = function() { - this.source.pause(); -}; + // when it's passed assign the value + // and conditionally invoke the callback + this.on('option:' + oname, (val) => { + const oldValue = this._getOptionValue(name); -DelayedStream.prototype.release = function() { - this._released = true; + // custom processing + if (val !== null && fn) { + val = fn(val, oldValue === undefined ? defaultValue : oldValue); + } else if (val !== null && option.variadic) { + if (oldValue === defaultValue || !Array.isArray(oldValue)) { + val = [val]; + } else { + val = oldValue.concat(val); + } + } - this._bufferedEvents.forEach(function(args) { - this.emit.apply(this, args); - }.bind(this)); - this._bufferedEvents = []; -}; + // unassigned or boolean value + if (typeof oldValue === 'boolean' || typeof oldValue === 'undefined') { + // if no value, negate false, and we have a default, then use it! + if (val == null) { + this._setOptionValue(name, option.negate + ? false + : defaultValue || true); + } else { + this._setOptionValue(name, val); + } + } else if (val !== null) { + // reassign + this._setOptionValue(name, option.negate ? false : val); + } + }); -DelayedStream.prototype.pipe = function() { - var r = Stream.prototype.pipe.apply(this, arguments); - this.resume(); - return r; -}; + return this; + }; -DelayedStream.prototype._handleEmit = function(args) { - if (this._released) { - this.emit.apply(this, args); - return; - } + /** + * Define option with `flags`, `description` and optional + * coercion `fn`. + * + * The `flags` string should contain both the short and long flags, + * separated by comma, a pipe or space. The following are all valid + * all will output this way when `--help` is used. + * + * "-p, --pepper" + * "-p|--pepper" + * "-p --pepper" + * + * Examples: + * + * // simple boolean defaulting to undefined + * program.option('-p, --pepper', 'add pepper'); + * + * program.pepper + * // => undefined + * + * --pepper + * program.pepper + * // => true + * + * // simple boolean defaulting to true (unless non-negated option is also defined) + * program.option('-C, --no-cheese', 'remove cheese'); + * + * program.cheese + * // => true + * + * --no-cheese + * program.cheese + * // => false + * + * // required argument + * program.option('-C, --chdir ', 'change the working directory'); + * + * --chdir /tmp + * program.chdir + * // => "/tmp" + * + * // optional argument + * program.option('-c, --cheese [type]', 'add cheese [marble]'); + * + * @param {string} flags + * @param {string} description + * @param {Function|*} [fn] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + * @api public + */ - if (args[0] === 'data') { - this.dataSize += args[1].length; - this._checkIfMaxDataSizeExceeded(); - } + option(flags, description, fn, defaultValue) { + return this._optionEx({}, flags, description, fn, defaultValue); + }; - this._bufferedEvents.push(args); -}; + /** + * Add a required option which must have a value after parsing. This usually means + * the option must be specified on the command line. (Otherwise the same as .option().) + * + * The `flags` string should contain both the short and long flags, separated by comma, a pipe or space. + * + * @param {string} flags + * @param {string} description + * @param {Function|*} [fn] - custom option processing function or default value + * @param {*} [defaultValue] + * @return {Command} `this` command for chaining + * @api public + */ -DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { - if (this._maxDataSizeExceeded) { - return; - } + requiredOption(flags, description, fn, defaultValue) { + return this._optionEx({ mandatory: true }, flags, description, fn, defaultValue); + }; - if (this.dataSize <= this.maxDataSize) { - return; - } + /** + * Alter parsing of short flags with optional values. + * + * Examples: + * + * // for `.option('-f,--flag [value]'): + * .combineFlagAndOptionalValue(true) // `-f80` is treated like `--flag=80`, this is the default behaviour + * .combineFlagAndOptionalValue(false) // `-fb` is treated like `-f -b` + * + * @param {Boolean} [arg] - if `true` or omitted, an optional value can be specified directly after the flag. + * @api public + */ + combineFlagAndOptionalValue(arg) { + this._combineFlagAndOptionalValue = (arg === undefined) || arg; + return this; + }; - this._maxDataSizeExceeded = true; - var message = - 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' - this.emit('error', new Error(message)); -}; + /** + * Allow unknown options on the command line. + * + * @param {Boolean} [arg] - if `true` or omitted, no error will be thrown + * for unknown options. + * @api public + */ + allowUnknownOption(arg) { + this._allowUnknownOption = (arg === undefined) || arg; + return this; + }; + /** + * Whether to store option values as properties on command object, + * or store separately (specify false). In both cases the option values can be accessed using .opts(). + * + * @param {boolean} value + * @return {Command} `this` command for chaining + * @api public + */ -/***/ }), + storeOptionsAsProperties(value) { + this._storeOptionsAsPropertiesCalled = true; + this._storeOptionsAsProperties = (value === undefined) || value; + if (this.options.length) { + throw new Error('call .storeOptionsAsProperties() before adding options'); + } + return this; + }; -/***/ 42342: -/***/ ((module) => { + /** + * Whether to pass command to action handler, + * or just the options (specify false). + * + * @param {boolean} value + * @return {Command} `this` command for chaining + * @api public + */ -"use strict"; + passCommandToAction(value) { + this._passCommandToAction = (value === undefined) || value; + return this; + }; + /** + * Store option value + * + * @param {string} key + * @param {Object} value + * @api private + */ -/** - * Custom implementation of a double ended queue. - */ -function Denque(array) { - this._head = 0; - this._tail = 0; - this._capacityMask = 0x3; - this._list = new Array(4); - if (Array.isArray(array)) { - this._fromArray(array); - } -} + _setOptionValue(key, value) { + if (this._storeOptionsAsProperties) { + this[key] = value; + } else { + this._optionValues[key] = value; + } + }; -/** - * ------------- - * PUBLIC API - * ------------- - */ + /** + * Retrieve option value + * + * @param {string} key + * @return {Object} value + * @api private + */ -/** - * Returns the item at the specified index from the list. - * 0 is the first element, 1 is the second, and so on... - * Elements at negative values are that many from the end: -1 is one before the end - * (the last element), -2 is two before the end (one before last), etc. - * @param index - * @returns {*} - */ -Denque.prototype.peekAt = function peekAt(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - var len = this.size(); - if (i >= len || i < -len) return undefined; - if (i < 0) i += len; - i = (this._head + i) & this._capacityMask; - return this._list[i]; -}; + _getOptionValue(key) { + if (this._storeOptionsAsProperties) { + return this[key]; + } + return this._optionValues[key]; + }; + + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * The default expectation is that the arguments are from node and have the application as argv[0] + * and the script being run in argv[1], with user parameters after that. + * + * Examples: + * + * program.parse(process.argv); + * program.parse(); // implicitly use process.argv and auto-detect node vs electron conventions + * program.parse(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] + * + * @param {string[]} [argv] - optional, defaults to process.argv + * @param {Object} [parseOptions] - optionally specify style of options with from: node/user/electron + * @param {string} [parseOptions.from] - where the args are from: 'node', 'user', 'electron' + * @return {Command} `this` command for chaining + * @api public + */ -/** - * Alias for peakAt() - * @param i - * @returns {*} - */ -Denque.prototype.get = function get(i) { - return this.peekAt(i); -}; + parse(argv, parseOptions) { + if (argv !== undefined && !Array.isArray(argv)) { + throw new Error('first parameter to parse must be array or undefined'); + } + parseOptions = parseOptions || {}; -/** - * Returns the first item in the list without removing it. - * @returns {*} - */ -Denque.prototype.peek = function peek() { - if (this._head === this._tail) return undefined; - return this._list[this._head]; -}; + // Default to using process.argv + if (argv === undefined) { + argv = process.argv; + // @ts-ignore + if (process.versions && process.versions.electron) { + parseOptions.from = 'electron'; + } + } + this.rawArgs = argv.slice(); -/** - * Alias for peek() - * @returns {*} - */ -Denque.prototype.peekFront = function peekFront() { - return this.peek(); -}; + // make it a little easier for callers by supporting various argv conventions + let userArgs; + switch (parseOptions.from) { + case undefined: + case 'node': + this._scriptPath = argv[1]; + userArgs = argv.slice(2); + break; + case 'electron': + // @ts-ignore + if (process.defaultApp) { + this._scriptPath = argv[1]; + userArgs = argv.slice(2); + } else { + userArgs = argv.slice(1); + } + break; + case 'user': + userArgs = argv.slice(0); + break; + default: + throw new Error(`unexpected parse option { from: '${parseOptions.from}' }`); + } + if (!this._scriptPath && process.mainModule) { + this._scriptPath = process.mainModule.filename; + } -/** - * Returns the item that is at the back of the queue without removing it. - * Uses peekAt(-1) - */ -Denque.prototype.peekBack = function peekBack() { - return this.peekAt(-1); -}; + // Guess name, used in usage in help. + this._name = this._name || (this._scriptPath && path.basename(this._scriptPath, path.extname(this._scriptPath))); -/** - * Returns the current length of the queue - * @return {Number} - */ -Object.defineProperty(Denque.prototype, 'length', { - get: function length() { - return this.size(); - } -}); + // Let's go! + this._parseCommand([], userArgs); -/** - * Return the number of items on the list, or 0 if empty. - * @returns {number} - */ -Denque.prototype.size = function size() { - if (this._head === this._tail) return 0; - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; + return this; + }; -/** - * Add an item at the beginning of the list. - * @param item - */ -Denque.prototype.unshift = function unshift(item) { - if (item === undefined) return this.size(); - var len = this._list.length; - this._head = (this._head - 1 + len) & this._capacityMask; - this._list[this._head] = item; - if (this._tail === this._head) this._growArray(); - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; + /** + * Parse `argv`, setting options and invoking commands when defined. + * + * Use parseAsync instead of parse if any of your action handlers are async. Returns a Promise. + * + * The default expectation is that the arguments are from node and have the application as argv[0] + * and the script being run in argv[1], with user parameters after that. + * + * Examples: + * + * program.parseAsync(process.argv); + * program.parseAsync(); // implicitly use process.argv and auto-detect node vs electron conventions + * program.parseAsync(my-args, { from: 'user' }); // just user supplied arguments, nothing special about argv[0] + * + * @param {string[]} [argv] + * @param {Object} [parseOptions] + * @param {string} parseOptions.from - where the args are from: 'node', 'user', 'electron' + * @return {Promise} + * @api public + */ -/** - * Remove and return the first item on the list, - * Returns undefined if the list is empty. - * @returns {*} - */ -Denque.prototype.shift = function shift() { - var head = this._head; - if (head === this._tail) return undefined; - var item = this._list[head]; - this._list[head] = undefined; - this._head = (head + 1) & this._capacityMask; - if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); - return item; -}; + parseAsync(argv, parseOptions) { + this.parse(argv, parseOptions); + return Promise.all(this._actionResults).then(() => this); + }; -/** - * Add an item to the bottom of the list. - * @param item - */ -Denque.prototype.push = function push(item) { - if (item === undefined) return this.size(); - var tail = this._tail; - this._list[tail] = item; - this._tail = (tail + 1) & this._capacityMask; - if (this._tail === this._head) { - this._growArray(); - } + /** + * Execute a sub-command executable. + * + * @api private + */ - if (this._head < this._tail) return this._tail - this._head; - else return this._capacityMask + 1 - (this._head - this._tail); -}; + _executeSubCommand(subcommand, args) { + args = args.slice(); + let launchWithNode = false; // Use node for source targets so do not need to get permissions correct, and on Windows. + const sourceExt = ['.js', '.ts', '.tsx', '.mjs']; -/** - * Remove and return the last item on the list. - * Returns undefined if the list is empty. - * @returns {*} - */ -Denque.prototype.pop = function pop() { - var tail = this._tail; - if (tail === this._head) return undefined; - var len = this._list.length; - this._tail = (tail - 1 + len) & this._capacityMask; - var item = this._list[this._tail]; - this._list[this._tail] = undefined; - if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); - return item; -}; + // Not checking for help first. Unlikely to have mandatory and executable, and can't robustly test for help flags in external command. + this._checkForMissingMandatoryOptions(); -/** - * Remove and return the item at the specified index from the list. - * Returns undefined if the list is empty. - * @param index - * @returns {*} - */ -Denque.prototype.removeOne = function removeOne(index) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size) return void 0; - if (i < 0) i += size; - i = (this._head + i) & this._capacityMask; - var item = this._list[i]; - var k; - if (index < size / 2) { - for (k = index; k > 0; k--) { - this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; - } - this._list[i] = void 0; - this._head = (this._head + 1 + len) & this._capacityMask; - } else { - for (k = size - 1 - index; k > 0; k--) { - this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask]; + // Want the entry script as the reference for command name and directory for searching for other files. + let scriptPath = this._scriptPath; + // Fallback in case not set, due to how Command created or called. + if (!scriptPath && process.mainModule) { + scriptPath = process.mainModule.filename; } - this._list[i] = void 0; - this._tail = (this._tail - 1 + len) & this._capacityMask; - } - return item; -}; -/** - * Remove number of items from the specified index from the list. - * Returns array of removed items. - * Returns undefined if the list is empty. - * @param index - * @param count - * @returns {array} - */ -Denque.prototype.remove = function remove(index, count) { - var i = index; - var removed; - var del_count = count; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - if (this._head === this._tail) return void 0; - var size = this.size(); - var len = this._list.length; - if (i >= size || i < -size || count < 1) return void 0; - if (i < 0) i += size; - if (count === 1 || !count) { - removed = new Array(1); - removed[0] = this.removeOne(i); - return removed; - } - if (i === 0 && i + count >= size) { - removed = this.toArray(); - this.clear(); - return removed; - } - if (i + count > size) count = size - i; - var k; - removed = new Array(count); - for (k = 0; k < count; k++) { - removed[k] = this._list[(this._head + i + k) & this._capacityMask]; - } - i = (this._head + i) & this._capacityMask; - if (index + count === size) { - this._tail = (this._tail - count + len) & this._capacityMask; - for (k = count; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + let baseDir; + try { + const resolvedLink = fs.realpathSync(scriptPath); + baseDir = path.dirname(resolvedLink); + } catch (e) { + baseDir = '.'; // dummy, probably not going to find executable! } - return removed; - } - if (index === 0) { - this._head = (this._head + count + len) & this._capacityMask; - for (k = count - 1; k > 0; k--) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + + // name of the subcommand, like `pm-install` + let bin = path.basename(scriptPath, path.extname(scriptPath)) + '-' + subcommand._name; + if (subcommand._executableFile) { + bin = subcommand._executableFile; } - return removed; - } - if (index < size / 2) { - this._head = (this._head + index + count + len) & this._capacityMask; - for (k = index; k > 0; k--) { - this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); + + const localBin = path.join(baseDir, bin); + if (fs.existsSync(localBin)) { + // prefer local `./` to bin in the $PATH + bin = localBin; + } else { + // Look for source files. + sourceExt.forEach((ext) => { + if (fs.existsSync(`${localBin}${ext}`)) { + bin = `${localBin}${ext}`; + } + }); } - i = (this._head - 1 + len) & this._capacityMask; - while (del_count > 0) { - this._list[i = (i - 1 + len) & this._capacityMask] = void 0; - del_count--; + launchWithNode = sourceExt.includes(path.extname(bin)); + + let proc; + if (process.platform !== 'win32') { + if (launchWithNode) { + args.unshift(bin); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); + + proc = spawn(process.argv[0], args, { stdio: 'inherit' }); + } else { + proc = spawn(bin, args, { stdio: 'inherit' }); + } + } else { + args.unshift(bin); + // add executable arguments to spawn + args = incrementNodeInspectorPort(process.execArgv).concat(args); + proc = spawn(process.execPath, args, { stdio: 'inherit' }); } - } else { - this._tail = i; - i = (i + count + len) & this._capacityMask; - for (k = size - (count + index); k > 0; k--) { - this.push(this._list[i++]); + + const signals = ['SIGUSR1', 'SIGUSR2', 'SIGTERM', 'SIGINT', 'SIGHUP']; + signals.forEach((signal) => { + // @ts-ignore + process.on(signal, () => { + if (proc.killed === false && proc.exitCode === null) { + proc.kill(signal); + } + }); + }); + + // By default terminate process when spawned process terminates. + // Suppressing the exit if exitCallback defined is a bit messy and of limited use, but does allow process to stay running! + const exitCallback = this._exitCallback; + if (!exitCallback) { + proc.on('close', process.exit.bind(process)); + } else { + proc.on('close', () => { + exitCallback(new CommanderError(process.exitCode || 0, 'commander.executeSubCommandAsync', '(close)')); + }); } - i = this._tail; - while (del_count > 0) { - this._list[i = (i + 1 + len) & this._capacityMask] = void 0; - del_count--; + proc.on('error', (err) => { + // @ts-ignore + if (err.code === 'ENOENT') { + const executableMissing = `'${bin}' does not exist + - if '${subcommand._name}' is not meant to be an executable command, remove description parameter from '.command()' and use '.description()' instead + - if the default executable name is not suitable, use the executableFile option to supply a custom name`; + throw new Error(executableMissing); + // @ts-ignore + } else if (err.code === 'EACCES') { + throw new Error(`'${bin}' not executable`); + } + if (!exitCallback) { + process.exit(1); + } else { + const wrappedError = new CommanderError(1, 'commander.executeSubCommandAsync', '(error)'); + wrappedError.nestedError = err; + exitCallback(wrappedError); + } + }); + + // Store the reference to the child process + this.runningCommand = proc; + }; + + /** + * @api private + */ + _dispatchSubcommand(commandName, operands, unknown) { + const subCommand = this._findCommand(commandName); + if (!subCommand) this._helpAndError(); + + if (subCommand._executableHandler) { + this._executeSubCommand(subCommand, operands.concat(unknown)); + } else { + subCommand._parseCommand(operands, unknown); } - } - if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); - return removed; -}; + }; -/** - * Native splice implementation. - * Remove number of items from the specified index from the list and/or add new elements. - * Returns array of removed items or empty array if count == 0. - * Returns undefined if the list is empty. - * - * @param index - * @param count - * @param {...*} [elements] - * @returns {array} - */ -Denque.prototype.splice = function splice(index, count) { - var i = index; - // expect a number or return undefined - if ((i !== (i | 0))) { - return void 0; - } - var size = this.size(); - if (i < 0) i += size; - if (i > size) return void 0; - if (arguments.length > 2) { - var k; - var temp; - var removed; - var arg_len = arguments.length; - var len = this._list.length; - var arguments_index = 2; - if (!size || i < size / 2) { - temp = new Array(i); - for (k = 0; k < i; k++) { - temp[k] = this._list[(this._head + k) & this._capacityMask]; - } - if (count === 0) { - removed = []; - if (i > 0) { - this._head = (this._head + i + len) & this._capacityMask; - } + /** + * Process arguments in context of this command. + * + * @api private + */ + + _parseCommand(operands, unknown) { + const parsed = this.parseOptions(unknown); + operands = operands.concat(parsed.operands); + unknown = parsed.unknown; + this.args = operands.concat(unknown); + + if (operands && this._findCommand(operands[0])) { + this._dispatchSubcommand(operands[0], operands.slice(1), unknown); + } else if (this._lazyHasImplicitHelpCommand() && operands[0] === this._helpCommandName) { + if (operands.length === 1) { + this.help(); } else { - removed = this.remove(i, count); - this._head = (this._head + i + len) & this._capacityMask; + this._dispatchSubcommand(operands[1], [], [this._helpLongFlag]); } - while (arg_len > arguments_index) { - this.unshift(arguments[--arg_len]); + } else if (this._defaultCommandName) { + outputHelpIfRequested(this, unknown); // Run the help for default command from parent rather than passing to default command + this._dispatchSubcommand(this._defaultCommandName, operands, unknown); + } else { + if (this.commands.length && this.args.length === 0 && !this._actionHandler && !this._defaultCommandName) { + // probably missing subcommand and no handler, user needs help + this._helpAndError(); } - for (k = i; k > 0; k--) { - this.unshift(temp[k - 1]); + + outputHelpIfRequested(this, parsed.unknown); + this._checkForMissingMandatoryOptions(); + if (parsed.unknown.length > 0) { + this.unknownOption(parsed.unknown[0]); } - } else { - temp = new Array(size - (i + count)); - var leng = temp.length; - for (k = 0; k < leng; k++) { - temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; + + if (this._actionHandler) { + const args = this.args.slice(); + this._args.forEach((arg, i) => { + if (arg.required && args[i] == null) { + this.missingArgument(arg.name); + } else if (arg.variadic) { + args[i] = args.splice(i); + } + }); + + this._actionHandler(args); + this.emit('command:' + this.name(), operands, unknown); + } else if (operands.length) { + if (this._findCommand('*')) { + this._dispatchSubcommand('*', operands, unknown); + } else if (this.listenerCount('command:*')) { + this.emit('command:*', operands, unknown); + } else if (this.commands.length) { + this.unknownCommand(); + } + } else if (this.commands.length) { + // This command has subcommands and nothing hooked up at this level, so display help. + this._helpAndError(); + } else { + // fall through for caller to handle after calling .parse() } - if (count === 0) { - removed = []; - if (i != size) { - this._tail = (this._head + i + len) & this._capacityMask; + } + }; + + /** + * Find matching command. + * + * @api private + */ + _findCommand(name) { + if (!name) return undefined; + return this.commands.find(cmd => cmd._name === name || cmd._aliases.includes(name)); + }; + + /** + * Return an option matching `arg` if any. + * + * @param {string} arg + * @return {Option} + * @api private + */ + + _findOption(arg) { + return this.options.find(option => option.is(arg)); + }; + + /** + * Display an error message if a mandatory option does not have a value. + * Lazy calling after checking for help flags from leaf subcommand. + * + * @api private + */ + + _checkForMissingMandatoryOptions() { + // Walk up hierarchy so can call in subcommand after checking for displaying help. + for (let cmd = this; cmd; cmd = cmd.parent) { + cmd.options.forEach((anOption) => { + if (anOption.mandatory && (cmd._getOptionValue(anOption.attributeName()) === undefined)) { + cmd.missingMandatoryOptionValue(anOption); } - } else { - removed = this.remove(i, count); - this._tail = (this._tail - leng + len) & this._capacityMask; - } - while (arguments_index < arg_len) { - this.push(arguments[arguments_index++]); - } - for (k = 0; k < leng; k++) { - this.push(temp[k]); - } + }); } - return removed; - } else { - return this.remove(i, count); - } -}; - -/** - * Soft clear - does not reset capacity. - */ -Denque.prototype.clear = function clear() { - this._head = 0; - this._tail = 0; -}; + }; -/** - * Returns true or false whether the list is empty. - * @returns {boolean} - */ -Denque.prototype.isEmpty = function isEmpty() { - return this._head === this._tail; -}; + /** + * Parse options from `argv` removing known options, + * and return argv split into operands and unknown arguments. + * + * Examples: + * + * argv => operands, unknown + * --known kkk op => [op], [] + * op --known kkk => [op], [] + * sub --unknown uuu op => [sub], [--unknown uuu op] + * sub -- --unknown uuu op => [sub --unknown uuu op], [] + * + * @param {String[]} argv + * @return {{operands: String[], unknown: String[]}} + * @api public + */ -/** - * Returns an array of all queue items. - * @returns {Array} - */ -Denque.prototype.toArray = function toArray() { - return this._copyArray(false); -}; + parseOptions(argv) { + const operands = []; // operands, not options or values + const unknown = []; // first unknown option and remaining unknown args + let dest = operands; + const args = argv.slice(); -/** - * ------------- - * INTERNALS - * ------------- - */ + function maybeOption(arg) { + return arg.length > 1 && arg[0] === '-'; + } -/** - * Fills the queue with items from an array - * For use in the constructor - * @param array - * @private - */ -Denque.prototype._fromArray = function _fromArray(array) { - for (var i = 0; i < array.length; i++) this.push(array[i]); -}; + // parse options + let activeVariadicOption = null; + while (args.length) { + const arg = args.shift(); -/** - * - * @param fullCopy - * @returns {Array} - * @private - */ -Denque.prototype._copyArray = function _copyArray(fullCopy) { - var newArray = []; - var list = this._list; - var len = list.length; - var i; - if (fullCopy || this._head > this._tail) { - for (i = this._head; i < len; i++) newArray.push(list[i]); - for (i = 0; i < this._tail; i++) newArray.push(list[i]); - } else { - for (i = this._head; i < this._tail; i++) newArray.push(list[i]); - } - return newArray; -}; + // literal + if (arg === '--') { + if (dest === unknown) dest.push(arg); + dest.push(...args); + break; + } -/** - * Grows the internal list array. - * @private - */ -Denque.prototype._growArray = function _growArray() { - if (this._head) { - // copy existing data, head to end, then beginning to tail. - this._list = this._copyArray(true); - this._head = 0; - } + if (activeVariadicOption && !maybeOption(arg)) { + this.emit(`option:${activeVariadicOption.name()}`, arg); + continue; + } + activeVariadicOption = null; - // head is at 0 and array is now full, safe to extend - this._tail = this._list.length; + if (maybeOption(arg)) { + const option = this._findOption(arg); + // recognised option, call listener to assign value with possible custom processing + if (option) { + if (option.required) { + const value = args.shift(); + if (value === undefined) this.optionMissingArgument(option); + this.emit(`option:${option.name()}`, value); + } else if (option.optional) { + let value = null; + // historical behaviour is optional value is following arg unless an option + if (args.length > 0 && !maybeOption(args[0])) { + value = args.shift(); + } + this.emit(`option:${option.name()}`, value); + } else { // boolean flag + this.emit(`option:${option.name()}`); + } + activeVariadicOption = option.variadic ? option : null; + continue; + } + } - this._list.length *= 2; - this._capacityMask = (this._capacityMask << 1) | 1; -}; + // Look for combo options following single dash, eat first one if known. + if (arg.length > 2 && arg[0] === '-' && arg[1] !== '-') { + const option = this._findOption(`-${arg[1]}`); + if (option) { + if (option.required || (option.optional && this._combineFlagAndOptionalValue)) { + // option with value following in same argument + this.emit(`option:${option.name()}`, arg.slice(2)); + } else { + // boolean option, emit and put back remainder of arg for further processing + this.emit(`option:${option.name()}`); + args.unshift(`-${arg.slice(2)}`); + } + continue; + } + } -/** - * Shrinks the internal list array. - * @private - */ -Denque.prototype._shrinkArray = function _shrinkArray() { - this._list.length >>>= 1; - this._capacityMask >>>= 1; -}; + // Look for known long flag with value, like --foo=bar + if (/^--[^=]+=/.test(arg)) { + const index = arg.indexOf('='); + const option = this._findOption(arg.slice(0, index)); + if (option && (option.required || option.optional)) { + this.emit(`option:${option.name()}`, arg.slice(index + 1)); + continue; + } + } + // looks like an option but unknown, unknowns from here + if (arg.length > 1 && arg[0] === '-') { + dest = unknown; + } -module.exports = Denque; + // add arg + dest.push(arg); + } + return { operands, unknown }; + }; -/***/ }), + /** + * Return an object containing options as key-value pairs + * + * @return {Object} + * @api public + */ + opts() { + if (this._storeOptionsAsProperties) { + // Preserve original behaviour so backwards compatible when still using properties + const result = {}; + const len = this.options.length; -/***/ 18883: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + for (let i = 0; i < len; i++) { + const key = this.options[i].attributeName(); + result[key] = key === this._versionOptionName ? this._version : this[key]; + } + return result; + } -/*! - * depd - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ + return this._optionValues; + }; -/** - * Module dependencies. - */ + /** + * Argument `name` is missing. + * + * @param {string} name + * @api private + */ -var callSiteToString = __nccwpck_require__(69829).callSiteToString -var eventListenerCount = __nccwpck_require__(69829).eventListenerCount -var relative = __nccwpck_require__(85622).relative + missingArgument(name) { + const message = `error: missing required argument '${name}'`; + console.error(message); + this._exit(1, 'commander.missingArgument', message); + }; -/** - * Module exports. - */ + /** + * `Option` is missing an argument, but received `flag` or nothing. + * + * @param {Option} option + * @param {string} [flag] + * @api private + */ -module.exports = depd + optionMissingArgument(option, flag) { + let message; + if (flag) { + message = `error: option '${option.flags}' argument missing, got '${flag}'`; + } else { + message = `error: option '${option.flags}' argument missing`; + } + console.error(message); + this._exit(1, 'commander.optionMissingArgument', message); + }; -/** - * Get the path to base files on. - */ + /** + * `Option` does not have a value, and is a mandatory option. + * + * @param {Option} option + * @api private + */ -var basePath = process.cwd() + missingMandatoryOptionValue(option) { + const message = `error: required option '${option.flags}' not specified`; + console.error(message); + this._exit(1, 'commander.missingMandatoryOptionValue', message); + }; -/** - * Determine if namespace is contained in the string. - */ + /** + * Unknown option `flag`. + * + * @param {string} flag + * @api private + */ -function containsNamespace (str, namespace) { - var vals = str.split(/[ ,]+/) - var ns = String(namespace).toLowerCase() + unknownOption(flag) { + if (this._allowUnknownOption) return; + const message = `error: unknown option '${flag}'`; + console.error(message); + this._exit(1, 'commander.unknownOption', message); + }; - for (var i = 0; i < vals.length; i++) { - var val = vals[i] + /** + * Unknown command. + * + * @api private + */ - // namespace contained - if (val && (val === '*' || val.toLowerCase() === ns)) { - return true + unknownCommand() { + const partCommands = [this.name()]; + for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { + partCommands.unshift(parentCmd.name()); } - } + const fullCommand = partCommands.join(' '); + const message = `error: unknown command '${this.args[0]}'.` + + (this._hasHelpOption ? ` See '${fullCommand} ${this._helpLongFlag}'.` : ''); + console.error(message); + this._exit(1, 'commander.unknownCommand', message); + }; - return false -} + /** + * Set the program version to `str`. + * + * This method auto-registers the "-V, --version" flag + * which will print the version number when passed. + * + * You can optionally supply the flags and description to override the defaults. + * + * @param {string} str + * @param {string} [flags] + * @param {string} [description] + * @return {this | string} `this` command for chaining, or version string if no arguments + * @api public + */ -/** - * Convert a data descriptor to accessor descriptor. - */ + version(str, flags, description) { + if (str === undefined) return this._version; + this._version = str; + flags = flags || '-V, --version'; + description = description || 'output the version number'; + const versionOption = new Option(flags, description); + this._versionOptionName = versionOption.attributeName(); + this.options.push(versionOption); + this.on('option:' + versionOption.name(), () => { + process.stdout.write(str + '\n'); + this._exit(0, 'commander.version', str); + }); + return this; + }; -function convertDataDescriptorToAccessor (obj, prop, message) { - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - var value = descriptor.value + /** + * Set the description to `str`. + * + * @param {string} str + * @param {Object} [argsDescription] + * @return {string|Command} + * @api public + */ - descriptor.get = function getter () { return value } + description(str, argsDescription) { + if (str === undefined && argsDescription === undefined) return this._description; + this._description = str; + this._argsDescription = argsDescription; + return this; + }; - if (descriptor.writable) { - descriptor.set = function setter (val) { return (value = val) } - } + /** + * Set an alias for the command. + * + * You may call more than once to add multiple aliases. Only the first alias is shown in the auto-generated help. + * + * @param {string} [alias] + * @return {string|Command} + * @api public + */ - delete descriptor.value - delete descriptor.writable + alias(alias) { + if (alias === undefined) return this._aliases[0]; // just return first, for backwards compatibility - Object.defineProperty(obj, prop, descriptor) + let command = this; + if (this.commands.length !== 0 && this.commands[this.commands.length - 1]._executableHandler) { + // assume adding alias for last added executable subcommand, rather than this + command = this.commands[this.commands.length - 1]; + } - return descriptor -} + if (alias === command._name) throw new Error('Command alias can\'t be the same as its name'); -/** - * Create arguments string to keep arity. - */ + command._aliases.push(alias); + return this; + }; -function createArgumentsString (arity) { - var str = '' + /** + * Set aliases for the command. + * + * Only the first alias is shown in the auto-generated help. + * + * @param {string[]} [aliases] + * @return {string[]|Command} + * @api public + */ - for (var i = 0; i < arity; i++) { - str += ', arg' + i - } + aliases(aliases) { + // Getter for the array of aliases is the main reason for having aliases() in addition to alias(). + if (aliases === undefined) return this._aliases; - return str.substr(2) -} + aliases.forEach((alias) => this.alias(alias)); + return this; + }; -/** - * Create stack string from stack. - */ + /** + * Set / get the command usage `str`. + * + * @param {string} [str] + * @return {String|Command} + * @api public + */ -function createStackString (stack) { - var str = this.name + ': ' + this.namespace + usage(str) { + if (str === undefined) { + if (this._usage) return this._usage; - if (this.message) { - str += ' deprecated ' + this.message - } + const args = this._args.map((arg) => { + return humanReadableArgName(arg); + }); + return [].concat( + (this.options.length || this._hasHelpOption ? '[options]' : []), + (this.commands.length ? '[command]' : []), + (this._args.length ? args : []) + ).join(' '); + } - for (var i = 0; i < stack.length; i++) { - str += '\n at ' + callSiteToString(stack[i]) - } + this._usage = str; + return this; + }; - return str -} + /** + * Get or set the name of the command + * + * @param {string} [str] + * @return {String|Command} + * @api public + */ -/** - * Create deprecate for namespace in caller. - */ + name(str) { + if (str === undefined) return this._name; + this._name = str; + return this; + }; -function depd (namespace) { - if (!namespace) { - throw new TypeError('argument namespace is required') - } + /** + * Return prepared commands. + * + * @return {Array} + * @api private + */ + + prepareCommands() { + const commandDetails = this.commands.filter((cmd) => { + return !cmd._hidden; + }).map((cmd) => { + const args = cmd._args.map((arg) => { + return humanReadableArgName(arg); + }).join(' '); + + return [ + cmd._name + + (cmd._aliases[0] ? '|' + cmd._aliases[0] : '') + + (cmd.options.length ? ' [options]' : '') + + (args ? ' ' + args : ''), + cmd._description + ]; + }); - var stack = getStack() - var site = callSiteLocation(stack[1]) - var file = site[0] + if (this._lazyHasImplicitHelpCommand()) { + commandDetails.push([this._helpCommandnameAndArgs, this._helpCommandDescription]); + } + return commandDetails; + }; - function deprecate (message) { - // call to self as log - log.call(deprecate, message) - } + /** + * Return the largest command length. + * + * @return {number} + * @api private + */ - deprecate._file = file - deprecate._ignored = isignored(namespace) - deprecate._namespace = namespace - deprecate._traced = istraced(namespace) - deprecate._warned = Object.create(null) + largestCommandLength() { + const commands = this.prepareCommands(); + return commands.reduce((max, command) => { + return Math.max(max, command[0].length); + }, 0); + }; - deprecate.function = wrapfunction - deprecate.property = wrapproperty + /** + * Return the largest option length. + * + * @return {number} + * @api private + */ - return deprecate -} + largestOptionLength() { + const options = [].slice.call(this.options); + options.push({ + flags: this._helpFlags + }); -/** - * Determine if namespace is ignored. - */ + return options.reduce((max, option) => { + return Math.max(max, option.flags.length); + }, 0); + }; -function isignored (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.noDeprecation) { - // --no-deprecation support - return true - } + /** + * Return the largest arg length. + * + * @return {number} + * @api private + */ - var str = process.env.NO_DEPRECATION || '' + largestArgLength() { + return this._args.reduce((max, arg) => { + return Math.max(max, arg.name.length); + }, 0); + }; - // namespace ignored - return containsNamespace(str, namespace) -} + /** + * Return the pad width. + * + * @return {number} + * @api private + */ -/** - * Determine if namespace is traced. - */ + padWidth() { + let width = this.largestOptionLength(); + if (this._argsDescription && this._args.length) { + if (this.largestArgLength() > width) { + width = this.largestArgLength(); + } + } -function istraced (namespace) { - /* istanbul ignore next: tested in a child processs */ - if (process.traceDeprecation) { - // --trace-deprecation support - return true - } + if (this.commands && this.commands.length) { + if (this.largestCommandLength() > width) { + width = this.largestCommandLength(); + } + } - var str = process.env.TRACE_DEPRECATION || '' + return width; + }; - // namespace traced - return containsNamespace(str, namespace) -} + /** + * Return help for options. + * + * @return {string} + * @api private + */ -/** - * Display deprecation message. - */ + optionHelp() { + const width = this.padWidth(); + const columns = process.stdout.columns || 80; + const descriptionWidth = columns - width - 4; + function padOptionDetails(flags, description) { + return pad(flags, width) + ' ' + optionalWrap(description, descriptionWidth, width + 2); + }; -function log (message, site) { - var haslisteners = eventListenerCount(process, 'deprecation') !== 0 + // Explicit options (including version) + const help = this.options.map((option) => { + const fullDesc = option.description + + ((!option.negate && option.defaultValue !== undefined) ? ' (default: ' + JSON.stringify(option.defaultValue) + ')' : ''); + return padOptionDetails(option.flags, fullDesc); + }); - // abort early if no destination - if (!haslisteners && this._ignored) { - return - } + // Implicit help + const showShortHelpFlag = this._hasHelpOption && this._helpShortFlag && !this._findOption(this._helpShortFlag); + const showLongHelpFlag = this._hasHelpOption && !this._findOption(this._helpLongFlag); + if (showShortHelpFlag || showLongHelpFlag) { + let helpFlags = this._helpFlags; + if (!showShortHelpFlag) { + helpFlags = this._helpLongFlag; + } else if (!showLongHelpFlag) { + helpFlags = this._helpShortFlag; + } + help.push(padOptionDetails(helpFlags, this._helpDescription)); + } - var caller - var callFile - var callSite - var depSite - var i = 0 - var seen = false - var stack = getStack() - var file = this._file + return help.join('\n'); + }; - if (site) { - // provided site - depSite = site - callSite = callSiteLocation(stack[1]) - callSite.name = depSite.name - file = callSite[0] - } else { - // get call site - i = 2 - depSite = callSiteLocation(stack[i]) - callSite = depSite - } + /** + * Return command help documentation. + * + * @return {string} + * @api private + */ - // get caller of deprecated thing in relation to file - for (; i < stack.length; i++) { - caller = callSiteLocation(stack[i]) - callFile = caller[0] + commandHelp() { + if (!this.commands.length && !this._lazyHasImplicitHelpCommand()) return ''; - if (callFile === file) { - seen = true - } else if (callFile === this._file) { - file = this._file - } else if (seen) { - break - } - } + const commands = this.prepareCommands(); + const width = this.padWidth(); - var key = caller - ? depSite.join(':') + '__' + caller.join(':') - : undefined + const columns = process.stdout.columns || 80; + const descriptionWidth = columns - width - 4; - if (key !== undefined && key in this._warned) { - // already warned - return - } + return [ + 'Commands:', + commands.map((cmd) => { + const desc = cmd[1] ? ' ' + cmd[1] : ''; + return (desc ? pad(cmd[0], width) : cmd[0]) + optionalWrap(desc, descriptionWidth, width + 2); + }).join('\n').replace(/^/gm, ' '), + '' + ].join('\n'); + }; - this._warned[key] = true + /** + * Return program help documentation. + * + * @return {string} + * @api public + */ - // generate automatic message from call site - var msg = message - if (!msg) { - msg = callSite === depSite || !callSite.name - ? defaultMessage(depSite) - : defaultMessage(callSite) - } + helpInformation() { + let desc = []; + if (this._description) { + desc = [ + this._description, + '' + ]; - // emit deprecation if listeners exist - if (haslisteners) { - var err = DeprecationError(this._namespace, msg, stack.slice(i)) - process.emit('deprecation', err) - return - } + const argsDescription = this._argsDescription; + if (argsDescription && this._args.length) { + const width = this.padWidth(); + const columns = process.stdout.columns || 80; + const descriptionWidth = columns - width - 5; + desc.push('Arguments:'); + this._args.forEach((arg) => { + desc.push(' ' + pad(arg.name, width) + ' ' + wrap(argsDescription[arg.name] || '', descriptionWidth, width + 4)); + }); + desc.push(''); + } + } - // format and write message - var format = process.stderr.isTTY - ? formatColor - : formatPlain - var output = format.call(this, msg, caller, stack.slice(i)) - process.stderr.write(output + '\n', 'utf8') -} + let cmdName = this._name; + if (this._aliases[0]) { + cmdName = cmdName + '|' + this._aliases[0]; + } + let parentCmdNames = ''; + for (let parentCmd = this.parent; parentCmd; parentCmd = parentCmd.parent) { + parentCmdNames = parentCmd.name() + ' ' + parentCmdNames; + } + const usage = [ + 'Usage: ' + parentCmdNames + cmdName + ' ' + this.usage(), + '' + ]; -/** - * Get call site location as array. - */ + let cmds = []; + const commandHelp = this.commandHelp(); + if (commandHelp) cmds = [commandHelp]; -function callSiteLocation (callSite) { - var file = callSite.getFileName() || '' - var line = callSite.getLineNumber() - var colm = callSite.getColumnNumber() + let options = []; + if (this._hasHelpOption || this.options.length > 0) { + options = [ + 'Options:', + '' + this.optionHelp().replace(/^/gm, ' '), + '' + ]; + } - if (callSite.isEval()) { - file = callSite.getEvalOrigin() + ', ' + file - } + return usage + .concat(desc) + .concat(options) + .concat(cmds) + .join('\n'); + }; - var site = [file, line, colm] + /** + * Output help information for this command. + * + * When listener(s) are available for the helpLongFlag + * those callbacks are invoked. + * + * @api public + */ - site.callSite = callSite - site.name = callSite.getFunctionName() + outputHelp(cb) { + if (!cb) { + cb = (passthru) => { + return passthru; + }; + } + const cbOutput = cb(this.helpInformation()); + if (typeof cbOutput !== 'string' && !Buffer.isBuffer(cbOutput)) { + throw new Error('outputHelp callback must return a string or a Buffer'); + } + process.stdout.write(cbOutput); + this.emit(this._helpLongFlag); + }; - return site -} + /** + * You can pass in flags and a description to override the help + * flags and help description for your command. Pass in false to + * disable the built-in help option. + * + * @param {string | boolean} [flags] + * @param {string} [description] + * @return {Command} `this` command for chaining + * @api public + */ -/** - * Generate a default message from the site. - */ + helpOption(flags, description) { + if (typeof flags === 'boolean') { + this._hasHelpOption = flags; + return this; + } + this._helpFlags = flags || this._helpFlags; + this._helpDescription = description || this._helpDescription; -function defaultMessage (site) { - var callSite = site.callSite - var funcName = site.name + const helpFlags = _parseOptionFlags(this._helpFlags); + this._helpShortFlag = helpFlags.shortFlag; + this._helpLongFlag = helpFlags.longFlag; - // make useful anonymous name - if (!funcName) { - funcName = '' - } + return this; + }; - var context = callSite.getThis() - var typeName = context && callSite.getTypeName() + /** + * Output help information and exit. + * + * @param {Function} [cb] + * @api public + */ - // ignore useless type name - if (typeName === 'Object') { - typeName = undefined - } + help(cb) { + this.outputHelp(cb); + // exitCode: preserving original behaviour which was calling process.exit() + // message: do not have all displayed text available so only passing placeholder. + this._exit(process.exitCode || 0, 'commander.help', '(outputHelp)'); + }; - // make useful type name - if (typeName === 'Function') { - typeName = context.name || typeName - } + /** + * Output help information and exit. Display for error situations. + * + * @api private + */ - return typeName && callSite.getMethodName() - ? typeName + '.' + funcName - : funcName -} + _helpAndError() { + this.outputHelp(); + // message: do not have all displayed text available so only passing placeholder. + this._exit(1, 'commander.help', '(outputHelp)'); + }; +}; /** - * Format deprecation message without color. + * Expose the root command. */ -function formatPlain (msg, caller, stack) { - var timestamp = new Date().toUTCString() - - var formatted = timestamp + - ' ' + this._namespace + - ' deprecated ' + msg +exports = module.exports = new Command(); +exports.program = exports; // More explicit access to global command. - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n at ' + callSiteToString(stack[i]) - } +/** + * Expose classes + */ - return formatted - } +exports.Command = Command; +exports.Option = Option; +exports.CommanderError = CommanderError; - if (caller) { - formatted += ' at ' + formatLocation(caller) - } +/** + * Camel-case the given `flag` + * + * @param {string} flag + * @return {string} + * @api private + */ - return formatted +function camelcase(flag) { + return flag.split('-').reduce((str, word) => { + return str + word[0].toUpperCase() + word.slice(1); + }); } /** - * Format deprecation message with color. + * Pad `str` to `width`. + * + * @param {string} str + * @param {number} width + * @return {string} + * @api private */ -function formatColor (msg, caller, stack) { - var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan - ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow - ' \x1b[0m' + msg + '\x1b[39m' // reset - - // add stack trace - if (this._traced) { - for (var i = 0; i < stack.length; i++) { - formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan - } - - return formatted - } - - if (caller) { - formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan - } - - return formatted +function pad(str, width) { + const len = Math.max(0, width - str.length); + return str + Array(len + 1).join(' '); } /** - * Format call site location. + * Wraps the given string with line breaks at the specified width while breaking + * words and indenting every but the first line on the left. + * + * @param {string} str + * @param {number} width + * @param {number} indent + * @return {string} + * @api private */ - -function formatLocation (callSite) { - return relative(basePath, callSite[0]) + - ':' + callSite[1] + - ':' + callSite[2] +function wrap(str, width, indent) { + const regex = new RegExp('.{1,' + (width - 1) + '}([\\s\u200B]|$)|[^\\s\u200B]+?([\\s\u200B]|$)', 'g'); + const lines = str.match(regex) || []; + return lines.map((line, i) => { + if (line.slice(-1) === '\n') { + line = line.slice(0, line.length - 1); + } + return ((i > 0 && indent) ? Array(indent + 1).join(' ') : '') + line.trimRight(); + }).join('\n'); } /** - * Get the stack as array of call sites. + * Optionally wrap the given str to a max width of width characters per line + * while indenting with indent spaces. Do not wrap if insufficient width or + * string is manually formatted. + * + * @param {string} str + * @param {number} width + * @param {number} indent + * @return {string} + * @api private */ +function optionalWrap(str, width, indent) { + // Detect manually wrapped and indented strings by searching for line breaks + // followed by multiple spaces/tabs. + if (str.match(/[\n]\s+/)) return str; + // Do not wrap to narrow columns (or can end up with a word per line). + const minWidth = 40; + if (width < minWidth) return str; -function getStack () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace - - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = Math.max(10, limit) - - // capture the stack - Error.captureStackTrace(obj) - - // slice this function off the top - var stack = obj.stack.slice(1) - - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit - - return stack + return wrap(str, width, indent); } /** - * Capture call site stack from v8. + * Output help information if help flags specified + * + * @param {Command} cmd - command to output help for + * @param {Array} args - array of options to search for help flags + * @api private */ -function prepareObjectStackTrace (obj, stack) { - return stack +function outputHelpIfRequested(cmd, args) { + const helpOption = cmd._hasHelpOption && args.find(arg => arg === cmd._helpLongFlag || arg === cmd._helpShortFlag); + if (helpOption) { + cmd.outputHelp(); + // (Do not have all displayed text available so only passing placeholder.) + cmd._exit(0, 'commander.helpDisplayed', '(outputHelp)'); + } } /** - * Return a wrapped function in a deprecation message. + * Takes an argument and returns its human readable equivalent for help usage. + * + * @param {Object} arg + * @return {string} + * @api private */ -function wrapfunction (fn, message) { - if (typeof fn !== 'function') { - throw new TypeError('argument fn must be a function') - } - - var args = createArgumentsString(fn.length) - var deprecate = this // eslint-disable-line no-unused-vars - var stack = getStack() - var site = callSiteLocation(stack[1]) - - site.name = fn.name - - // eslint-disable-next-line no-eval - var deprecatedfn = eval('(function (' + args + ') {\n' + - '"use strict"\n' + - 'log.call(deprecate, message, site)\n' + - 'return fn.apply(this, arguments)\n' + - '})') +function humanReadableArgName(arg) { + const nameOutput = arg.name + (arg.variadic === true ? '...' : ''); - return deprecatedfn + return arg.required + ? '<' + nameOutput + '>' + : '[' + nameOutput + ']'; } /** - * Wrap property in a deprecation message. + * Parse the short and long flag out of something like '-m,--mixed ' + * + * @api private */ -function wrapproperty (obj, prop, message) { - if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { - throw new TypeError('argument obj must be object') - } - - var descriptor = Object.getOwnPropertyDescriptor(obj, prop) - - if (!descriptor) { - throw new TypeError('must call property on owner object') - } - - if (!descriptor.configurable) { - throw new TypeError('property must be configurable') - } - - var deprecate = this - var stack = getStack() - var site = callSiteLocation(stack[1]) - - // set site name - site.name = prop - - // convert data descriptor - if ('value' in descriptor) { - descriptor = convertDataDescriptorToAccessor(obj, prop, message) - } - - var get = descriptor.get - var set = descriptor.set - - // wrap getter - if (typeof get === 'function') { - descriptor.get = function getter () { - log.call(deprecate, message, site) - return get.apply(this, arguments) - } - } - - // wrap setter - if (typeof set === 'function') { - descriptor.set = function setter () { - log.call(deprecate, message, site) - return set.apply(this, arguments) - } +function _parseOptionFlags(flags) { + let shortFlag; + let longFlag; + // Use original very loose parsing to maintain backwards compatibility for now, + // which allowed for example unintended `-sw, --short-word` [sic]. + const flagParts = flags.split(/[ |,]+/); + if (flagParts.length > 1 && !/^[[<]/.test(flagParts[1])) shortFlag = flagParts.shift(); + longFlag = flagParts.shift(); + // Add support for lone short flag without significantly changing parsing! + if (!shortFlag && /^-[^-]$/.test(longFlag)) { + shortFlag = longFlag; + longFlag = undefined; } - - Object.defineProperty(obj, prop, descriptor) + return { shortFlag, longFlag }; } /** - * Create DeprecationError for deprecation + * Scan arguments and increment port number for inspect calls (to avoid conflicts when spawning new command). + * + * @param {string[]} args - array of arguments from node.execArgv + * @returns {string[]} + * @api private */ -function DeprecationError (namespace, message, stack) { - var error = new Error() - var stackString - - Object.defineProperty(error, 'constructor', { - value: DeprecationError - }) - - Object.defineProperty(error, 'message', { - configurable: true, - enumerable: false, - value: message, - writable: true - }) - - Object.defineProperty(error, 'name', { - enumerable: false, - configurable: true, - value: 'DeprecationError', - writable: true - }) - - Object.defineProperty(error, 'namespace', { - configurable: true, - enumerable: false, - value: namespace, - writable: true - }) - - Object.defineProperty(error, 'stack', { - configurable: true, - enumerable: false, - get: function () { - if (stackString !== undefined) { - return stackString +function incrementNodeInspectorPort(args) { + // Testing for these options: + // --inspect[=[host:]port] + // --inspect-brk[=[host:]port] + // --inspect-port=[host:]port + return args.map((arg) => { + if (!arg.startsWith('--inspect')) { + return arg; + } + let debugOption; + let debugHost = '127.0.0.1'; + let debugPort = '9229'; + let match; + if ((match = arg.match(/^(--inspect(-brk)?)$/)) !== null) { + // e.g. --inspect + debugOption = match[1]; + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+)$/)) !== null) { + debugOption = match[1]; + if (/^\d+$/.test(match[3])) { + // e.g. --inspect=1234 + debugPort = match[3]; + } else { + // e.g. --inspect=localhost + debugHost = match[3]; } - - // prepare stack trace - return (stackString = createStackString.call(this, stack)) - }, - set: function setter (val) { - stackString = val + } else if ((match = arg.match(/^(--inspect(-brk|-port)?)=([^:]+):(\d+)$/)) !== null) { + // e.g. --inspect=localhost:1234 + debugOption = match[1]; + debugHost = match[3]; + debugPort = match[4]; } - }) - return error + if (debugOption && debugPort !== '0') { + return `${debugOption}=${debugHost}:${parseInt(debugPort) + 1}`; + } + return arg; + }); } /***/ }), -/***/ 35554: -/***/ ((module) => { - -"use strict"; -/*! - * depd - * Copyright(c) 2014 Douglas Christopher Wilson - * MIT Licensed - */ - +/***/ 89296: +/***/ (function(module) { +/* global define */ +(function (root, factory) { + /* istanbul ignore next */ + if (typeof define === 'function' && define.amd) { + define([], factory); + } else if (true) { + module.exports = factory(); + } else {} +}(this, function () { -/** - * Module exports. - */ + var semver = /^v?(?:\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+)(\.(?:[x*]|\d+))?(?:-[\da-z\-]+(?:\.[\da-z\-]+)*)?(?:\+[\da-z\-]+(?:\.[\da-z\-]+)*)?)?)?$/i; -module.exports = callSiteToString + function indexOrEnd(str, q) { + return str.indexOf(q) === -1 ? str.length : str.indexOf(q); + } -/** - * Format a CallSite file location to a string. - */ + function split(v) { + var c = v.replace(/^v/, '').replace(/\+.*$/, ''); + var patchIndex = indexOrEnd(c, '-'); + var arr = c.substring(0, patchIndex).split('.'); + arr.push(c.substring(patchIndex + 1)); + return arr; + } -function callSiteFileLocation (callSite) { - var fileName - var fileLocation = '' + function tryParse(v) { + return isNaN(Number(v)) ? v : Number(v); + } - if (callSite.isNative()) { - fileLocation = 'native' - } else if (callSite.isEval()) { - fileName = callSite.getScriptNameOrSourceURL() - if (!fileName) { - fileLocation = callSite.getEvalOrigin() + function validate(version) { + if (typeof version !== 'string') { + throw new TypeError('Invalid argument expected string'); + } + if (!semver.test(version)) { + throw new Error('Invalid argument not valid semver (\''+version+'\' received)'); } - } else { - fileName = callSite.getFileName() } - if (fileName) { - fileLocation += fileName + function compareVersions(v1, v2) { + [v1, v2].forEach(validate); - var lineNumber = callSite.getLineNumber() - if (lineNumber != null) { - fileLocation += ':' + lineNumber + var s1 = split(v1); + var s2 = split(v2); - var columnNumber = callSite.getColumnNumber() - if (columnNumber) { - fileLocation += ':' + columnNumber - } - } - } + for (var i = 0; i < Math.max(s1.length - 1, s2.length - 1); i++) { + var n1 = parseInt(s1[i] || 0, 10); + var n2 = parseInt(s2[i] || 0, 10); - return fileLocation || 'unknown source' -} + if (n1 > n2) return 1; + if (n2 > n1) return -1; + } -/** - * Format a CallSite to a string. - */ + var sp1 = s1[s1.length - 1]; + var sp2 = s2[s2.length - 1]; -function callSiteToString (callSite) { - var addSuffix = true - var fileLocation = callSiteFileLocation(callSite) - var functionName = callSite.getFunctionName() - var isConstructor = callSite.isConstructor() - var isMethodCall = !(callSite.isToplevel() || isConstructor) - var line = '' + if (sp1 && sp2) { + var p1 = sp1.split('.').map(tryParse); + var p2 = sp2.split('.').map(tryParse); - if (isMethodCall) { - var methodName = callSite.getMethodName() - var typeName = getConstructorName(callSite) + for (i = 0; i < Math.max(p1.length, p2.length); i++) { + if (p1[i] === undefined || typeof p2[i] === 'string' && typeof p1[i] === 'number') return -1; + if (p2[i] === undefined || typeof p1[i] === 'string' && typeof p2[i] === 'number') return 1; - if (functionName) { - if (typeName && functionName.indexOf(typeName) !== 0) { - line += typeName + '.' + if (p1[i] > p2[i]) return 1; + if (p2[i] > p1[i]) return -1; } + } else if (sp1 || sp2) { + return sp1 ? -1 : 1; + } - line += functionName + return 0; + }; - if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { - line += ' [as ' + methodName + ']' - } - } else { - line += typeName + '.' + (methodName || '') + var allowedOperators = [ + '>', + '>=', + '=', + '<', + '<=' + ]; + + var operatorResMap = { + '>': [1], + '>=': [0, 1], + '=': [0], + '<=': [-1, 0], + '<': [-1] + }; + + function validateOperator(op) { + if (typeof op !== 'string') { + throw new TypeError('Invalid operator type, expected string but got ' + typeof op); + } + if (allowedOperators.indexOf(op) === -1) { + throw new TypeError('Invalid operator, expected one of ' + allowedOperators.join('|')); } - } else if (isConstructor) { - line += 'new ' + (functionName || '') - } else if (functionName) { - line += functionName - } else { - addSuffix = false - line += fileLocation } - if (addSuffix) { - line += ' (' + fileLocation + ')' + compareVersions.validate = function(version) { + return typeof version === 'string' && semver.test(version); } - return line -} + compareVersions.compare = function (v1, v2, operator) { + // Validate operator + validateOperator(operator); -/** - * Get constructor name of reviver. - */ + // since result of compareVersions can only be -1 or 0 or 1 + // a simple map can be used to replace switch + var res = compareVersions(v1, v2); + return operatorResMap[operator].indexOf(res) > -1; + } -function getConstructorName (obj) { - var receiver = obj.receiver - return (receiver.constructor && receiver.constructor.name) || null -} + return compareVersions; +})); /***/ }), -/***/ 12078: -/***/ ((module) => { +/***/ 53921: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! - * depd - * Copyright(c) 2015 Douglas Christopher Wilson + * content-disposition + * Copyright(c) 2014-2017 Douglas Christopher Wilson * MIT Licensed */ @@ -42135,687 +45282,820 @@ function getConstructorName (obj) { * @public */ -module.exports = eventListenerCount +module.exports = contentDisposition +module.exports.parse = parse /** - * Get the count of listeners on an event emitter of a specific type. - */ - -function eventListenerCount (emitter, type) { - return emitter.listeners(type).length -} - - -/***/ }), - -/***/ 69829: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * depd - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed + * Module dependencies. + * @private */ - +var basename = __nccwpck_require__(85622).basename +var Buffer = __nccwpck_require__(38558).Buffer /** - * Module dependencies. + * RegExp to match non attr-char, *after* encodeURIComponent (i.e. not including "%") * @private */ -var EventEmitter = __nccwpck_require__(28614).EventEmitter +var ENCODE_URL_ATTR_CHAR_REGEXP = /[\x00-\x20"'()*,/:;<=>?@[\\\]{}\x7f]/g // eslint-disable-line no-control-regex /** - * Module exports. - * @public + * RegExp to match percent encoding escape. + * @private */ -lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { - var limit = Error.stackTraceLimit - var obj = {} - var prep = Error.prepareStackTrace - - function prepareObjectStackTrace (obj, stack) { - return stack - } - - Error.prepareStackTrace = prepareObjectStackTrace - Error.stackTraceLimit = 2 - - // capture the stack - Error.captureStackTrace(obj) - - // slice the stack - var stack = obj.stack.slice() - - Error.prepareStackTrace = prep - Error.stackTraceLimit = limit - - return stack[0].toString ? toString : __nccwpck_require__(35554) -}) - -lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { - return EventEmitter.listenerCount || __nccwpck_require__(12078) -}) +var HEX_ESCAPE_REGEXP = /%[0-9A-Fa-f]{2}/ +var HEX_ESCAPE_REPLACE_REGEXP = /%([0-9A-Fa-f]{2})/g /** - * Define a lazy property. + * RegExp to match non-latin1 characters. + * @private */ -function lazyProperty (obj, prop, getter) { - function get () { - var val = getter() - - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - value: val - }) - - return val - } - - Object.defineProperty(obj, prop, { - configurable: true, - enumerable: true, - get: get - }) -} +var NON_LATIN1_REGEXP = /[^\x20-\x7e\xa0-\xff]/g /** - * Call toString() on the obj + * RegExp to match quoted-pair in RFC 2616 + * + * quoted-pair = "\" CHAR + * CHAR = + * @private */ -function toString (obj) { - return obj.toString() -} - - -/***/ }), - -/***/ 58932: -/***/ ((__unused_webpack_module, exports) => { - -"use strict"; - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - - this.name = 'Deprecation'; - } - -} - -exports.Deprecation = Deprecation; - - -/***/ }), - -/***/ 43225: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var QESC_REGEXP = /\\([\u0000-\u007f])/g // eslint-disable-line no-control-regex -"use strict"; -/*! - * destroy - * Copyright(c) 2014 Jonathan Ong - * MIT Licensed +/** + * RegExp to match chars that must be quoted-pair in RFC 2616 + * @private */ - +var QUOTE_REGEXP = /([\\"])/g /** - * Module dependencies. + * RegExp for various RFC 2616 grammar + * + * parameter = token "=" ( token | quoted-string ) + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + * quoted-string = ( <"> *(qdtext | quoted-pair ) <"> ) + * qdtext = > + * quoted-pair = "\" CHAR + * CHAR = + * TEXT = + * LWS = [CRLF] 1*( SP | HT ) + * CRLF = CR LF + * CR = + * LF = + * SP = + * HT = + * CTL = + * OCTET = * @private */ -var ReadStream = __nccwpck_require__(35747).ReadStream -var Stream = __nccwpck_require__(92413) +var PARAM_REGEXP = /;[\x09\x20]*([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*=[\x09\x20]*("(?:[\x20!\x23-\x5b\x5d-\x7e\x80-\xff]|\\[\x20-\x7e])*"|[!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*/g // eslint-disable-line no-control-regex +var TEXT_REGEXP = /^[\x20-\x7e\x80-\xff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.0-9A-Z^_`a-z|~-]+$/ /** - * Module exports. - * @public + * RegExp for various RFC 5987 grammar + * + * ext-value = charset "'" [ language ] "'" value-chars + * charset = "UTF-8" / "ISO-8859-1" / mime-charset + * mime-charset = 1*mime-charsetc + * mime-charsetc = ALPHA / DIGIT + * / "!" / "#" / "$" / "%" / "&" + * / "+" / "-" / "^" / "_" / "`" + * / "{" / "}" / "~" + * language = ( 2*3ALPHA [ extlang ] ) + * / 4ALPHA + * / 5*8ALPHA + * extlang = *3( "-" 3ALPHA ) + * value-chars = *( pct-encoded / attr-char ) + * pct-encoded = "%" HEXDIG HEXDIG + * attr-char = ALPHA / DIGIT + * / "!" / "#" / "$" / "&" / "+" / "-" / "." + * / "^" / "_" / "`" / "|" / "~" + * @private */ -module.exports = destroy +var EXT_VALUE_REGEXP = /^([A-Za-z0-9!#$%&+\-^_`{}~]+)'(?:[A-Za-z]{2,3}(?:-[A-Za-z]{3}){0,3}|[A-Za-z]{4,8}|)'((?:%[0-9A-Fa-f]{2}|[A-Za-z0-9!#$&+.^_`|~-])+)$/ /** - * Destroy a stream. + * RegExp for various RFC 6266 grammar * - * @param {object} stream - * @public + * disposition-type = "inline" | "attachment" | disp-ext-type + * disp-ext-type = token + * disposition-parm = filename-parm | disp-ext-parm + * filename-parm = "filename" "=" value + * | "filename*" "=" ext-value + * disp-ext-parm = token "=" value + * | ext-token "=" ext-value + * ext-token = + * @private */ -function destroy(stream) { - if (stream instanceof ReadStream) { - return destroyReadStream(stream) - } - - if (!(stream instanceof Stream)) { - return stream - } - - if (typeof stream.destroy === 'function') { - stream.destroy() - } - - return stream -} +var DISPOSITION_TYPE_REGEXP = /^([!#$%&'*+.0-9A-Z^_`a-z|~-]+)[\x09\x20]*(?:$|;)/ // eslint-disable-line no-control-regex /** - * Destroy a ReadStream. + * Create an attachment Content-Disposition header. * - * @param {object} stream - * @private + * @param {string} [filename] + * @param {object} [options] + * @param {string} [options.type=attachment] + * @param {string|boolean} [options.fallback=true] + * @return {string} + * @public */ -function destroyReadStream(stream) { - stream.destroy() +function contentDisposition (filename, options) { + var opts = options || {} - if (typeof stream.close === 'function') { - // node.js core bug work-around - stream.on('open', onOpenClose) - } + // get type + var type = opts.type || 'attachment' - return stream + // get parameters + var params = createparams(filename, opts.fallback) + + // format into string + return format(new ContentDisposition(type, params)) } /** - * On open handler to close stream. + * Create parameters object from filename and fallback. + * + * @param {string} [filename] + * @param {string|boolean} [fallback=true] + * @return {object} * @private */ -function onOpenClose() { - if (typeof this.fd === 'number') { - // actually close down the fd - this.close() +function createparams (filename, fallback) { + if (filename === undefined) { + return } -} + var params = {} -/***/ }), + if (typeof filename !== 'string') { + throw new TypeError('filename must be a string') + } -/***/ 12437: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // fallback defaults to true + if (fallback === undefined) { + fallback = true + } -/* @flow */ -/*:: + if (typeof fallback !== 'string' && typeof fallback !== 'boolean') { + throw new TypeError('fallback must be a string or boolean') + } -type DotenvParseOptions = { - debug?: boolean -} + if (typeof fallback === 'string' && NON_LATIN1_REGEXP.test(fallback)) { + throw new TypeError('fallback must be ISO-8859-1 string') + } -// keys and values from src -type DotenvParseOutput = { [string]: string } + // restrict to file base name + var name = basename(filename) -type DotenvConfigOptions = { - path?: string, // path to .env file - encoding?: string, // encoding of .env file - debug?: string // turn on logging for debugging purposes -} + // determine if name is suitable for quoted string + var isQuotedString = TEXT_REGEXP.test(name) -type DotenvConfigOutput = { - parsed?: DotenvParseOutput, - error?: Error -} + // generate fallback name + var fallbackName = typeof fallback !== 'string' + ? fallback && getlatin1(name) + : basename(fallback) + var hasFallback = typeof fallbackName === 'string' && fallbackName !== name -*/ + // set extended filename parameter + if (hasFallback || !isQuotedString || HEX_ESCAPE_REGEXP.test(name)) { + params['filename*'] = name + } -const fs = __nccwpck_require__(35747) -const path = __nccwpck_require__(85622) + // set filename parameter + if (isQuotedString || hasFallback) { + params.filename = hasFallback + ? fallbackName + : name + } -function log (message /*: string */) { - console.log(`[dotenv][DEBUG] ${message}`) + return params } -const NEWLINE = '\n' -const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/ -const RE_NEWLINES = /\\n/g -const NEWLINES_MATCH = /\n|\r|\r\n/ - -// Parses src into an Object -function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ { - const debug = Boolean(options && options.debug) - const obj = {} +/** + * Format object to Content-Disposition header. + * + * @param {object} obj + * @param {string} obj.type + * @param {object} [obj.parameters] + * @return {string} + * @private + */ - // convert Buffers before splitting into lines and processing - src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) { - // matching "KEY' and 'VAL' in 'KEY=VAL' - const keyValueArr = line.match(RE_INI_KEY_VAL) - // matched? - if (keyValueArr != null) { - const key = keyValueArr[1] - // default undefined or missing values to empty string - let val = (keyValueArr[2] || '') - const end = val.length - 1 - const isDoubleQuoted = val[0] === '"' && val[end] === '"' - const isSingleQuoted = val[0] === "'" && val[end] === "'" +function format (obj) { + var parameters = obj.parameters + var type = obj.type - // if single or double quoted, remove quotes - if (isSingleQuoted || isDoubleQuoted) { - val = val.substring(1, end) + if (!type || typeof type !== 'string' || !TOKEN_REGEXP.test(type)) { + throw new TypeError('invalid type') + } - // if double quoted, expand newlines - if (isDoubleQuoted) { - val = val.replace(RE_NEWLINES, NEWLINE) - } - } else { - // remove surrounding whitespace - val = val.trim() - } + // start with normalized type + var string = String(type).toLowerCase() - obj[key] = val - } else if (debug) { - log(`did not match key and value when parsing line ${idx + 1}: ${line}`) - } - }) + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() - return obj -} + for (var i = 0; i < params.length; i++) { + param = params[i] -// Populates process.env from .env file -function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ { - let dotenvPath = path.resolve(process.cwd(), '.env') - let encoding /*: string */ = 'utf8' - let debug = false + var val = param.substr(-1) === '*' + ? ustring(parameters[param]) + : qstring(parameters[param]) - if (options) { - if (options.path != null) { - dotenvPath = options.path - } - if (options.encoding != null) { - encoding = options.encoding - } - if (options.debug != null) { - debug = true + string += '; ' + param + '=' + val } } - try { - // specifying an encoding returns a string instead of a buffer - const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug }) - - Object.keys(parsed).forEach(function (key) { - if (!Object.prototype.hasOwnProperty.call(process.env, key)) { - process.env[key] = parsed[key] - } else if (debug) { - log(`"${key}" is already defined in \`process.env\` and will not be overwritten`) - } - }) - - return { parsed } - } catch (e) { - return { error: e } - } + return string } -module.exports.config = config -module.exports.parse = parse - - -/***/ }), - -/***/ 11728: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Decode a RFC 6987 field value (gracefully). + * + * @param {string} str + * @return {string} + * @private + */ -"use strict"; +function decodefield (str) { + var match = EXT_VALUE_REGEXP.exec(str) + if (!match) { + throw new TypeError('invalid extended field value') + } -var Buffer = __nccwpck_require__(21867).Buffer; + var charset = match[1].toLowerCase() + var encoded = match[2] + var value -var getParamBytesForAlg = __nccwpck_require__(30528); + // to binary string + var binary = encoded.replace(HEX_ESCAPE_REPLACE_REGEXP, pdecode) -var MAX_OCTET = 0x80, - CLASS_UNIVERSAL = 0, - PRIMITIVE_BIT = 0x20, - TAG_SEQ = 0x10, - TAG_INT = 0x02, - ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), - ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); + switch (charset) { + case 'iso-8859-1': + value = getlatin1(binary) + break + case 'utf-8': + value = Buffer.from(binary, 'binary').toString('utf8') + break + default: + throw new TypeError('unsupported charset in extended field') + } -function base64Url(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); + return value } -function signatureAsBuffer(signature) { - if (Buffer.isBuffer(signature)) { - return signature; - } else if ('string' === typeof signature) { - return Buffer.from(signature, 'base64'); - } +/** + * Get ISO-8859-1 version of string. + * + * @param {string} val + * @return {string} + * @private + */ - throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); +function getlatin1 (val) { + // simple Unicode -> ISO-8859-1 transformation + return String(val).replace(NON_LATIN1_REGEXP, '?') } -function derToJose(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); - - // the DER encoded param should at most be the param size, plus a padding - // zero, since due to being a signed integer - var maxEncodedParamLength = paramBytes + 1; - - var inputLength = signature.length; - - var offset = 0; - if (signature[offset++] !== ENCODED_TAG_SEQ) { - throw new Error('Could not find expected "seq"'); - } - - var seqLength = signature[offset++]; - if (seqLength === (MAX_OCTET | 1)) { - seqLength = signature[offset++]; - } +/** + * Parse Content-Disposition header string. + * + * @param {string} string + * @return {object} + * @public + */ - if (inputLength - offset < seqLength) { - throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); - } +function parse (string) { + if (!string || typeof string !== 'string') { + throw new TypeError('argument string is required') + } - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "r"'); - } + var match = DISPOSITION_TYPE_REGEXP.exec(string) - var rLength = signature[offset++]; + if (!match) { + throw new TypeError('invalid type format') + } - if (inputLength - offset - 2 < rLength) { - throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); - } + // normalize type + var index = match[0].length + var type = match[1].toLowerCase() - if (maxEncodedParamLength < rLength) { - throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } + var key + var names = [] + var params = {} + var value - var rOffset = offset; - offset += rLength; + // calculate index to start at + index = PARAM_REGEXP.lastIndex = match[0].substr(-1) === ';' + ? index - 1 + : index - if (signature[offset++] !== ENCODED_TAG_INT) { - throw new Error('Could not find expected "int" for "s"'); - } + // match parameters + while ((match = PARAM_REGEXP.exec(string))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } - var sLength = signature[offset++]; + index += match[0].length + key = match[1].toLowerCase() + value = match[2] - if (inputLength - offset !== sLength) { - throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); - } + if (names.indexOf(key) !== -1) { + throw new TypeError('invalid duplicate parameter') + } - if (maxEncodedParamLength < sLength) { - throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); - } + names.push(key) - var sOffset = offset; - offset += sLength; + if (key.indexOf('*') + 1 === key.length) { + // decode extended value + key = key.slice(0, -1) + value = decodefield(value) - if (offset !== inputLength) { - throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); - } + // overwrite existing value + params[key] = value + continue + } - var rPadding = paramBytes - rLength, - sPadding = paramBytes - sLength; + if (typeof params[key] === 'string') { + continue + } - var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } - for (offset = 0; offset < rPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); + params[key] = value + } - offset = paramBytes; + if (index !== -1 && index !== string.length) { + throw new TypeError('invalid parameter format') + } - for (var o = offset; offset < o + sPadding; ++offset) { - dst[offset] = 0; - } - signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); + return new ContentDisposition(type, params) +} - dst = dst.toString('base64'); - dst = base64Url(dst); +/** + * Percent decode a single character. + * + * @param {string} str + * @param {string} hex + * @return {string} + * @private + */ - return dst; +function pdecode (str, hex) { + return String.fromCharCode(parseInt(hex, 16)) } -function countPadding(buf, start, stop) { - var padding = 0; - while (start + padding < stop && buf[start + padding] === 0) { - ++padding; - } - - var needsSign = buf[start + padding] >= MAX_OCTET; - if (needsSign) { - --padding; - } +/** + * Percent encode a single character. + * + * @param {string} char + * @return {string} + * @private + */ - return padding; +function pencode (char) { + return '%' + String(char) + .charCodeAt(0) + .toString(16) + .toUpperCase() } -function joseToDer(signature, alg) { - signature = signatureAsBuffer(signature); - var paramBytes = getParamBytesForAlg(alg); - - var signatureBytes = signature.length; - if (signatureBytes !== paramBytes * 2) { - throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); - } +/** + * Quote a string for HTTP. + * + * @param {string} val + * @return {string} + * @private + */ - var rPadding = countPadding(signature, 0, paramBytes); - var sPadding = countPadding(signature, paramBytes, signature.length); - var rLength = paramBytes - rPadding; - var sLength = paramBytes - sPadding; +function qstring (val) { + var str = String(val) - var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} - var shortLength = rsBytes < MAX_OCTET; +/** + * Encode a Unicode string for HTTP (RFC 5987). + * + * @param {string} val + * @return {string} + * @private + */ - var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); +function ustring (val) { + var str = String(val) - var offset = 0; - dst[offset++] = ENCODED_TAG_SEQ; - if (shortLength) { - // Bit 8 has value "0" - // bits 7-1 give the length. - dst[offset++] = rsBytes; - } else { - // Bit 8 of first octet has value "1" - // bits 7-1 give the number of additional length octets. - dst[offset++] = MAX_OCTET | 1; - // length, base 256 - dst[offset++] = rsBytes & 0xff; - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = rLength; - if (rPadding < 0) { - dst[offset++] = 0; - offset += signature.copy(dst, offset, 0, paramBytes); - } else { - offset += signature.copy(dst, offset, rPadding, paramBytes); - } - dst[offset++] = ENCODED_TAG_INT; - dst[offset++] = sLength; - if (sPadding < 0) { - dst[offset++] = 0; - signature.copy(dst, offset, paramBytes); - } else { - signature.copy(dst, offset, paramBytes + sPadding); - } + // percent encode as UTF-8 + var encoded = encodeURIComponent(str) + .replace(ENCODE_URL_ATTR_CHAR_REGEXP, pencode) - return dst; + return 'UTF-8\'\'' + encoded } -module.exports = { - derToJose: derToJose, - joseToDer: joseToDer -}; +/** + * Class for parsed Content-Disposition header for v8 optimization + * + * @public + * @param {string} type + * @param {object} parameters + * @constructor + */ + +function ContentDisposition (type, parameters) { + this.type = type + this.parameters = parameters +} /***/ }), -/***/ 30528: -/***/ ((module) => { +/***/ 38558: +/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; +/* eslint-disable node/no-deprecated-api */ +var buffer = __nccwpck_require__(64293) +var Buffer = buffer.Buffer +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} -function getParamSize(keySize) { - var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); - return result; +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) } -var paramBytesForAlg = { - ES256: getParamSize(256), - ES384: getParamSize(384), - ES512: getParamSize(521) -}; +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) -function getParamBytesForAlg(alg) { - var paramBytes = paramBytesForAlg[alg]; - if (paramBytes) { - return paramBytes; - } +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) +} - throw new Error('Unknown algorithm "' + alg + '"'); +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf } -module.exports = getParamBytesForAlg; +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} + +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} /***/ }), -/***/ 14401: -/***/ ((module) => { +/***/ 99915: +/***/ ((__unused_webpack_module, exports) => { "use strict"; /*! - * ee-first - * Copyright(c) 2014 Jonathan Ong + * content-type + * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ +/** + * RegExp to match *( ";" parameter ) in RFC 7231 sec 3.1.1.1 + * + * parameter = token "=" ( token / quoted-string ) + * token = 1*tchar + * tchar = "!" / "#" / "$" / "%" / "&" / "'" / "*" + * / "+" / "-" / "." / "^" / "_" / "`" / "|" / "~" + * / DIGIT / ALPHA + * ; any VCHAR, except delimiters + * quoted-string = DQUOTE *( qdtext / quoted-pair ) DQUOTE + * qdtext = HTAB / SP / %x21 / %x23-5B / %x5D-7E / obs-text + * obs-text = %x80-FF + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + */ +var PARAM_REGEXP = /; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g +var TEXT_REGEXP = /^[\u000b\u0020-\u007e\u0080-\u00ff]+$/ +var TOKEN_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + +/** + * RegExp to match quoted-pair in RFC 7230 sec 3.2.6 + * + * quoted-pair = "\" ( HTAB / SP / VCHAR / obs-text ) + * obs-text = %x80-FF + */ +var QESC_REGEXP = /\\([\u000b\u0020-\u00ff])/g + +/** + * RegExp to match chars that must be quoted-pair in RFC 7230 sec 3.2.6 + */ +var QUOTE_REGEXP = /([\\"])/g + +/** + * RegExp to match type in RFC 7231 sec 3.1.1.1 + * + * media-type = type "/" subtype + * type = token + * subtype = token + */ +var TYPE_REGEXP = /^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/ + /** * Module exports. * @public */ -module.exports = first +exports.format = format +exports.parse = parse /** - * Get the first event in a set of event emitters and event pairs. + * Format object to media type. * - * @param {array} stuff - * @param {function} done + * @param {object} obj + * @return {string} * @public */ -function first(stuff, done) { - if (!Array.isArray(stuff)) - throw new TypeError('arg must be an array of [ee, events...] arrays') +function format (obj) { + if (!obj || typeof obj !== 'object') { + throw new TypeError('argument obj is required') + } - var cleanups = [] + var parameters = obj.parameters + var type = obj.type - for (var i = 0; i < stuff.length; i++) { - var arr = stuff[i] + if (!type || !TYPE_REGEXP.test(type)) { + throw new TypeError('invalid type') + } - if (!Array.isArray(arr) || arr.length < 2) - throw new TypeError('each array member must be [ee, events...]') + var string = type - var ee = arr[0] + // append parameters + if (parameters && typeof parameters === 'object') { + var param + var params = Object.keys(parameters).sort() - for (var j = 1; j < arr.length; j++) { - var event = arr[j] - var fn = listener(event, callback) + for (var i = 0; i < params.length; i++) { + param = params[i] - // listen to the event - ee.on(event, fn) - // push this listener to the list of cleanups - cleanups.push({ - ee: ee, - event: event, - fn: fn, - }) + if (!TOKEN_REGEXP.test(param)) { + throw new TypeError('invalid parameter name') + } + + string += '; ' + param + '=' + qstring(parameters[param]) } } - function callback() { - cleanup() - done.apply(null, arguments) + return string +} + +/** + * Parse media type to object. + * + * @param {string|object} string + * @return {Object} + * @public + */ + +function parse (string) { + if (!string) { + throw new TypeError('argument string is required') } - function cleanup() { - var x - for (var i = 0; i < cleanups.length; i++) { - x = cleanups[i] - x.ee.removeListener(x.event, x.fn) + // support req/res-like objects as argument + var header = typeof string === 'object' + ? getcontenttype(string) + : string + + if (typeof header !== 'string') { + throw new TypeError('argument string is required to be a string') + } + + var index = header.indexOf(';') + var type = index !== -1 + ? header.substr(0, index).trim() + : header.trim() + + if (!TYPE_REGEXP.test(type)) { + throw new TypeError('invalid media type') + } + + var obj = new ContentType(type.toLowerCase()) + + // parse parameters + if (index !== -1) { + var key + var match + var value + + PARAM_REGEXP.lastIndex = index + + while ((match = PARAM_REGEXP.exec(header))) { + if (match.index !== index) { + throw new TypeError('invalid parameter format') + } + + index += match[0].length + key = match[1].toLowerCase() + value = match[2] + + if (value[0] === '"') { + // remove quotes and escapes + value = value + .substr(1, value.length - 2) + .replace(QESC_REGEXP, '$1') + } + + obj.parameters[key] = value + } + + if (index !== header.length) { + throw new TypeError('invalid parameter format') } } - function thunk(fn) { - done = fn + return obj +} + +/** + * Get content-type from req/res objects. + * + * @param {object} + * @return {Object} + * @private + */ + +function getcontenttype (obj) { + var header + + if (typeof obj.getHeader === 'function') { + // res-like + header = obj.getHeader('content-type') + } else if (typeof obj.headers === 'object') { + // req-like + header = obj.headers && obj.headers['content-type'] } - thunk.cancel = cleanup + if (typeof header !== 'string') { + throw new TypeError('content-type header is missing from object') + } - return thunk + return header } /** - * Create the event listener. + * Quote a string if necessary. + * + * @param {string} val + * @return {string} * @private */ -function listener(event, done) { - return function onevent(arg1) { - var args = new Array(arguments.length) - var ee = this - var err = event === 'error' - ? arg1 - : null +function qstring (val) { + var str = String(val) - // copy args to prevent arguments escaping scope - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } + // no need to quote tokens + if (TOKEN_REGEXP.test(str)) { + return str + } - done(err, ee, event, args) + if (str.length > 0 && !TEXT_REGEXP.test(str)) { + throw new TypeError('invalid parameter value') } + + return '"' + str.replace(QUOTE_REGEXP, '\\$1') + '"' +} + +/** + * Class to represent a content type. + * @private + */ +function ContentType (type) { + this.parameters = Object.create(null) + this.type = type } /***/ }), -/***/ 18212: -/***/ ((module) => { +/***/ 61579: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +/** + * Module dependencies. + */ +var crypto = __nccwpck_require__(76417); -module.exports = function () { - // https://mths.be/emoji - return /\uD83C\uDFF4\uDB40\uDC67\uDB40\uDC62(?:\uDB40\uDC65\uDB40\uDC6E\uDB40\uDC67|\uDB40\uDC73\uDB40\uDC63\uDB40\uDC74|\uDB40\uDC77\uDB40\uDC6C\uDB40\uDC73)\uDB40\uDC7F|\uD83D\uDC68(?:\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68\uD83C\uDFFB|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFE])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D)?\uD83D\uDC68|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D[\uDC68\uDC69])\u200D(?:\uD83D[\uDC66\uDC67])|[\u2695\u2696\u2708]\uFE0F|\uD83D[\uDC66\uDC67]|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|(?:\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708])\uFE0F|\uD83C\uDFFB\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C[\uDFFB-\uDFFF])|(?:\uD83E\uDDD1\uD83C\uDFFB\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)\uD83C\uDFFB|\uD83E\uDDD1(?:\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1)|(?:\uD83E\uDDD1\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFF\u200D\uD83E\uDD1D\u200D(?:\uD83D[\uDC68\uDC69]))(?:\uD83C[\uDFFB-\uDFFE])|(?:\uD83E\uDDD1\uD83C\uDFFC\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB\uDFFC])|\uD83D\uDC69(?:\uD83C\uDFFE\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB-\uDFFD\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFC\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFD-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFB\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFC-\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFD\u200D(?:\uD83E\uDD1D\u200D\uD83D\uDC68(?:\uD83C[\uDFFB\uDFFC\uDFFE\uDFFF])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\u200D(?:\u2764\uFE0F\u200D(?:\uD83D\uDC8B\u200D(?:\uD83D[\uDC68\uDC69])|\uD83D[\uDC68\uDC69])|\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD])|\uD83C\uDFFF\u200D(?:\uD83C[\uDF3E\uDF73\uDF93\uDFA4\uDFA8\uDFEB\uDFED]|\uD83D[\uDCBB\uDCBC\uDD27\uDD2C\uDE80\uDE92]|\uD83E[\uDDAF-\uDDB3\uDDBC\uDDBD]))|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67]))|(?:\uD83E\uDDD1\uD83C\uDFFD\u200D\uD83E\uDD1D\u200D\uD83E\uDDD1|\uD83D\uDC69\uD83C\uDFFE\u200D\uD83E\uDD1D\u200D\uD83D\uDC69)(?:\uD83C[\uDFFB-\uDFFD])|\uD83D\uDC69\u200D\uD83D\uDC66\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC69\u200D(?:\uD83D[\uDC66\uDC67])|(?:\uD83D\uDC41\uFE0F\u200D\uD83D\uDDE8|\uD83D\uDC69(?:\uD83C\uDFFF\u200D[\u2695\u2696\u2708]|\uD83C\uDFFE\u200D[\u2695\u2696\u2708]|\uD83C\uDFFC\u200D[\u2695\u2696\u2708]|\uD83C\uDFFB\u200D[\u2695\u2696\u2708]|\uD83C\uDFFD\u200D[\u2695\u2696\u2708]|\u200D[\u2695\u2696\u2708])|(?:(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)\uFE0F|\uD83D\uDC6F|\uD83E[\uDD3C\uDDDE\uDDDF])\u200D[\u2640\u2642]|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:(?:\uD83C[\uDFFB-\uDFFF])\u200D[\u2640\u2642]|\u200D[\u2640\u2642])|\uD83C\uDFF4\u200D\u2620)\uFE0F|\uD83D\uDC69\u200D\uD83D\uDC67\u200D(?:\uD83D[\uDC66\uDC67])|\uD83C\uDFF3\uFE0F\u200D\uD83C\uDF08|\uD83D\uDC15\u200D\uD83E\uDDBA|\uD83D\uDC69\u200D\uD83D\uDC66|\uD83D\uDC69\u200D\uD83D\uDC67|\uD83C\uDDFD\uD83C\uDDF0|\uD83C\uDDF4\uD83C\uDDF2|\uD83C\uDDF6\uD83C\uDDE6|[#\*0-9]\uFE0F\u20E3|\uD83C\uDDE7(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEF\uDDF1-\uDDF4\uDDF6-\uDDF9\uDDFB\uDDFC\uDDFE\uDDFF])|\uD83C\uDDF9(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDED\uDDEF-\uDDF4\uDDF7\uDDF9\uDDFB\uDDFC\uDDFF])|\uD83C\uDDEA(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDED\uDDF7-\uDDFA])|\uD83E\uDDD1(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF7(?:\uD83C[\uDDEA\uDDF4\uDDF8\uDDFA\uDDFC])|\uD83D\uDC69(?:\uD83C[\uDFFB-\uDFFF])|\uD83C\uDDF2(?:\uD83C[\uDDE6\uDDE8-\uDDED\uDDF0-\uDDFF])|\uD83C\uDDE6(?:\uD83C[\uDDE8-\uDDEC\uDDEE\uDDF1\uDDF2\uDDF4\uDDF6-\uDDFA\uDDFC\uDDFD\uDDFF])|\uD83C\uDDF0(?:\uD83C[\uDDEA\uDDEC-\uDDEE\uDDF2\uDDF3\uDDF5\uDDF7\uDDFC\uDDFE\uDDFF])|\uD83C\uDDED(?:\uD83C[\uDDF0\uDDF2\uDDF3\uDDF7\uDDF9\uDDFA])|\uD83C\uDDE9(?:\uD83C[\uDDEA\uDDEC\uDDEF\uDDF0\uDDF2\uDDF4\uDDFF])|\uD83C\uDDFE(?:\uD83C[\uDDEA\uDDF9])|\uD83C\uDDEC(?:\uD83C[\uDDE6\uDDE7\uDDE9-\uDDEE\uDDF1-\uDDF3\uDDF5-\uDDFA\uDDFC\uDDFE])|\uD83C\uDDF8(?:\uD83C[\uDDE6-\uDDEA\uDDEC-\uDDF4\uDDF7-\uDDF9\uDDFB\uDDFD-\uDDFF])|\uD83C\uDDEB(?:\uD83C[\uDDEE-\uDDF0\uDDF2\uDDF4\uDDF7])|\uD83C\uDDF5(?:\uD83C[\uDDE6\uDDEA-\uDDED\uDDF0-\uDDF3\uDDF7-\uDDF9\uDDFC\uDDFE])|\uD83C\uDDFB(?:\uD83C[\uDDE6\uDDE8\uDDEA\uDDEC\uDDEE\uDDF3\uDDFA])|\uD83C\uDDF3(?:\uD83C[\uDDE6\uDDE8\uDDEA-\uDDEC\uDDEE\uDDF1\uDDF4\uDDF5\uDDF7\uDDFA\uDDFF])|\uD83C\uDDE8(?:\uD83C[\uDDE6\uDDE8\uDDE9\uDDEB-\uDDEE\uDDF0-\uDDF5\uDDF7\uDDFA-\uDDFF])|\uD83C\uDDF1(?:\uD83C[\uDDE6-\uDDE8\uDDEE\uDDF0\uDDF7-\uDDFB\uDDFE])|\uD83C\uDDFF(?:\uD83C[\uDDE6\uDDF2\uDDFC])|\uD83C\uDDFC(?:\uD83C[\uDDEB\uDDF8])|\uD83C\uDDFA(?:\uD83C[\uDDE6\uDDEC\uDDF2\uDDF3\uDDF8\uDDFE\uDDFF])|\uD83C\uDDEE(?:\uD83C[\uDDE8-\uDDEA\uDDF1-\uDDF4\uDDF6-\uDDF9])|\uD83C\uDDEF(?:\uD83C[\uDDEA\uDDF2\uDDF4\uDDF5])|(?:\uD83C[\uDFC3\uDFC4\uDFCA]|\uD83D[\uDC6E\uDC71\uDC73\uDC77\uDC81\uDC82\uDC86\uDC87\uDE45-\uDE47\uDE4B\uDE4D\uDE4E\uDEA3\uDEB4-\uDEB6]|\uD83E[\uDD26\uDD37-\uDD39\uDD3D\uDD3E\uDDB8\uDDB9\uDDCD-\uDDCF\uDDD6-\uDDDD])(?:\uD83C[\uDFFB-\uDFFF])|(?:\u26F9|\uD83C[\uDFCB\uDFCC]|\uD83D\uDD75)(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u261D\u270A-\u270D]|\uD83C[\uDF85\uDFC2\uDFC7]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66\uDC67\uDC6B-\uDC6D\uDC70\uDC72\uDC74-\uDC76\uDC78\uDC7C\uDC83\uDC85\uDCAA\uDD74\uDD7A\uDD90\uDD95\uDD96\uDE4C\uDE4F\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1C\uDD1E\uDD1F\uDD30-\uDD36\uDDB5\uDDB6\uDDBB\uDDD2-\uDDD5])(?:\uD83C[\uDFFB-\uDFFF])|(?:[\u231A\u231B\u23E9-\u23EC\u23F0\u23F3\u25FD\u25FE\u2614\u2615\u2648-\u2653\u267F\u2693\u26A1\u26AA\u26AB\u26BD\u26BE\u26C4\u26C5\u26CE\u26D4\u26EA\u26F2\u26F3\u26F5\u26FA\u26FD\u2705\u270A\u270B\u2728\u274C\u274E\u2753-\u2755\u2757\u2795-\u2797\u27B0\u27BF\u2B1B\u2B1C\u2B50\u2B55]|\uD83C[\uDC04\uDCCF\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE1A\uDE2F\uDE32-\uDE36\uDE38-\uDE3A\uDE50\uDE51\uDF00-\uDF20\uDF2D-\uDF35\uDF37-\uDF7C\uDF7E-\uDF93\uDFA0-\uDFCA\uDFCF-\uDFD3\uDFE0-\uDFF0\uDFF4\uDFF8-\uDFFF]|\uD83D[\uDC00-\uDC3E\uDC40\uDC42-\uDCFC\uDCFF-\uDD3D\uDD4B-\uDD4E\uDD50-\uDD67\uDD7A\uDD95\uDD96\uDDA4\uDDFB-\uDE4F\uDE80-\uDEC5\uDECC\uDED0-\uDED2\uDED5\uDEEB\uDEEC\uDEF4-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])|(?:[#\*0-9\xA9\xAE\u203C\u2049\u2122\u2139\u2194-\u2199\u21A9\u21AA\u231A\u231B\u2328\u23CF\u23E9-\u23F3\u23F8-\u23FA\u24C2\u25AA\u25AB\u25B6\u25C0\u25FB-\u25FE\u2600-\u2604\u260E\u2611\u2614\u2615\u2618\u261D\u2620\u2622\u2623\u2626\u262A\u262E\u262F\u2638-\u263A\u2640\u2642\u2648-\u2653\u265F\u2660\u2663\u2665\u2666\u2668\u267B\u267E\u267F\u2692-\u2697\u2699\u269B\u269C\u26A0\u26A1\u26AA\u26AB\u26B0\u26B1\u26BD\u26BE\u26C4\u26C5\u26C8\u26CE\u26CF\u26D1\u26D3\u26D4\u26E9\u26EA\u26F0-\u26F5\u26F7-\u26FA\u26FD\u2702\u2705\u2708-\u270D\u270F\u2712\u2714\u2716\u271D\u2721\u2728\u2733\u2734\u2744\u2747\u274C\u274E\u2753-\u2755\u2757\u2763\u2764\u2795-\u2797\u27A1\u27B0\u27BF\u2934\u2935\u2B05-\u2B07\u2B1B\u2B1C\u2B50\u2B55\u3030\u303D\u3297\u3299]|\uD83C[\uDC04\uDCCF\uDD70\uDD71\uDD7E\uDD7F\uDD8E\uDD91-\uDD9A\uDDE6-\uDDFF\uDE01\uDE02\uDE1A\uDE2F\uDE32-\uDE3A\uDE50\uDE51\uDF00-\uDF21\uDF24-\uDF93\uDF96\uDF97\uDF99-\uDF9B\uDF9E-\uDFF0\uDFF3-\uDFF5\uDFF7-\uDFFF]|\uD83D[\uDC00-\uDCFD\uDCFF-\uDD3D\uDD49-\uDD4E\uDD50-\uDD67\uDD6F\uDD70\uDD73-\uDD7A\uDD87\uDD8A-\uDD8D\uDD90\uDD95\uDD96\uDDA4\uDDA5\uDDA8\uDDB1\uDDB2\uDDBC\uDDC2-\uDDC4\uDDD1-\uDDD3\uDDDC-\uDDDE\uDDE1\uDDE3\uDDE8\uDDEF\uDDF3\uDDFA-\uDE4F\uDE80-\uDEC5\uDECB-\uDED2\uDED5\uDEE0-\uDEE5\uDEE9\uDEEB\uDEEC\uDEF0\uDEF3-\uDEFA\uDFE0-\uDFEB]|\uD83E[\uDD0D-\uDD3A\uDD3C-\uDD45\uDD47-\uDD71\uDD73-\uDD76\uDD7A-\uDDA2\uDDA5-\uDDAA\uDDAE-\uDDCA\uDDCD-\uDDFF\uDE70-\uDE73\uDE78-\uDE7A\uDE80-\uDE82\uDE90-\uDE95])\uFE0F|(?:[\u261D\u26F9\u270A-\u270D]|\uD83C[\uDF85\uDFC2-\uDFC4\uDFC7\uDFCA-\uDFCC]|\uD83D[\uDC42\uDC43\uDC46-\uDC50\uDC66-\uDC78\uDC7C\uDC81-\uDC83\uDC85-\uDC87\uDC8F\uDC91\uDCAA\uDD74\uDD75\uDD7A\uDD90\uDD95\uDD96\uDE45-\uDE47\uDE4B-\uDE4F\uDEA3\uDEB4-\uDEB6\uDEC0\uDECC]|\uD83E[\uDD0F\uDD18-\uDD1F\uDD26\uDD30-\uDD39\uDD3C-\uDD3E\uDDB5\uDDB6\uDDB8\uDDB9\uDDBB\uDDCD-\uDDCF\uDDD1-\uDDDD])/g; +/** + * Sign the given `val` with `secret`. + * + * @param {String} val + * @param {String} secret + * @return {String} + * @api private + */ + +exports.sign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Cookie value must be provided as a string."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + return val + '.' + crypto + .createHmac('sha256', secret) + .update(val) + .digest('base64') + .replace(/\=+$/, ''); +}; + +/** + * Unsign and decode the given `val` with `secret`, + * returning `false` if the signature is invalid. + * + * @param {String} val + * @param {String} secret + * @return {String|Boolean} + * @api private + */ + +exports.unsign = function(val, secret){ + if ('string' != typeof val) throw new TypeError("Signed cookie string must be provided."); + if ('string' != typeof secret) throw new TypeError("Secret string must be provided."); + var str = val.slice(0, val.lastIndexOf('.')) + , mac = exports.sign(str, secret); + + return sha1(mac) == sha1(val) ? str : false; }; +/** + * Private + */ + +function sha1(str){ + return crypto.createHash('sha1').update(str).digest('hex'); +} + /***/ }), -/***/ 16592: -/***/ ((module) => { +/***/ 93658: +/***/ ((__unused_webpack_module, exports) => { "use strict"; /*! - * encodeurl - * Copyright(c) 2016 Douglas Christopher Wilson + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson * MIT Licensed */ @@ -42826,2330 +46106,2715 @@ module.exports = function () { * @public */ -module.exports = encodeUrl +exports.parse = parse; +exports.serialize = serialize; /** - * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") - * and including invalid escape sequences. + * Module variables. * @private */ -var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g +var decode = decodeURIComponent; +var encode = encodeURIComponent; +var pairSplitRegExp = /; */; /** - * RegExp to match unmatched surrogate pair. - * @private + * RegExp to match field-content in RFC 7230 sec 3.2 + * + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * obs-text = %x80-FF */ -var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; /** - * String to replace unmatched surrogate pair with. - * @private + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public */ -var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); + } + + var obj = {} + var opt = options || {}; + var pairs = str.split(pairSplitRegExp); + var dec = opt.decode || decode; + + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + var eq_idx = pair.indexOf('='); + + // skip things that don't look like key=value + if (eq_idx < 0) { + continue; + } + + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); + + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); + } + + // only assign once + if (undefined == obj[key]) { + obj[key] = tryDecode(val, dec); + } + } + + return obj; +} /** - * Encode a URL to a percent-encoded form, excluding already-encoded sequences. + * Serialize data into a cookie header. * - * This function will take an already-encoded URL and encode all the non-URL - * code points. This function will not encode the "%" character unless it is - * not part of a valid sequence (`%20` will be left as-is, but `%foo` will - * be encoded as `%25foo`). + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. * - * This encode is meant to be "safe" and does not throw errors. It will try as - * hard as it can to properly encode the given URL, including replacing any raw, - * unpaired surrogate pairs with the Unicode replacement character prior to - * encoding. + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" * - * @param {string} url + * @param {string} name + * @param {string} val + * @param {object} [options] * @return {string} * @public */ -function encodeUrl (url) { - return String(url) - .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) - .replace(ENCODE_CHARS_REGEXP, encodeURI) -} - - -/***/ }), - -/***/ 23505: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var util = __nccwpck_require__(31669); -var isArrayish = __nccwpck_require__(7604); - -var errorEx = function errorEx(name, properties) { - if (!name || name.constructor !== String) { - properties = name || {}; - name = Error.name; - } - - var errorExError = function ErrorEXError(message) { - if (!this) { - return new ErrorEXError(message); - } - - message = message instanceof Error - ? message.message - : (message || this.message); - - Error.call(this, message); - Error.captureStackTrace(this, errorExError); +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; - this.name = name; + if (typeof enc !== 'function') { + throw new TypeError('option encode is invalid'); + } - Object.defineProperty(this, 'message', { - configurable: true, - enumerable: false, - get: function () { - var newMessage = message.split(/\r?\n/g); + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } + var value = enc(val); - var modifier = properties[key]; + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } - if ('message' in modifier) { - newMessage = modifier.message(this[key], newMessage) || newMessage; - if (!isArrayish(newMessage)) { - newMessage = [newMessage]; - } - } - } + var str = name + '=' + value; - return newMessage.join('\n'); - }, - set: function (v) { - message = v; - } - }); + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; - var overwrittenStack = null; + if (isNaN(maxAge) || !isFinite(maxAge)) { + throw new TypeError('option maxAge is invalid') + } - var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); - var stackGetter = stackDescriptor.get; - var stackValue = stackDescriptor.value; - delete stackDescriptor.value; - delete stackDescriptor.writable; + str += '; Max-Age=' + Math.floor(maxAge); + } - stackDescriptor.set = function (newstack) { - overwrittenStack = newstack; - }; + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } - stackDescriptor.get = function () { - var stack = (overwrittenStack || ((stackGetter) - ? stackGetter.call(this) - : stackValue)).split(/\r?\n+/g); + str += '; Domain=' + opt.domain; + } - // starting in Node 7, the stack builder caches the message. - // just replace it. - if (!overwrittenStack) { - stack[0] = this.name + ': ' + this.message; - } + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } - var lineCount = 1; - for (var key in properties) { - if (!properties.hasOwnProperty(key)) { - continue; - } + str += '; Path=' + opt.path; + } - var modifier = properties[key]; + if (opt.expires) { + if (typeof opt.expires.toUTCString !== 'function') { + throw new TypeError('option expires is invalid'); + } - if ('line' in modifier) { - var line = modifier.line(this[key]); - if (line) { - stack.splice(lineCount++, 0, ' ' + line); - } - } + str += '; Expires=' + opt.expires.toUTCString(); + } - if ('stack' in modifier) { - modifier.stack(this[key], stack); - } - } + if (opt.httpOnly) { + str += '; HttpOnly'; + } - return stack.join('\n'); - }; + if (opt.secure) { + str += '; Secure'; + } - Object.defineProperty(this, 'stack', stackDescriptor); - }; + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === 'string' + ? opt.sameSite.toLowerCase() : opt.sameSite; - if (Object.setPrototypeOf) { - Object.setPrototypeOf(errorExError.prototype, Error.prototype); - Object.setPrototypeOf(errorExError, Error); - } else { - util.inherits(errorExError, Error); - } + switch (sameSite) { + case true: + str += '; SameSite=Strict'; + break; + case 'lax': + str += '; SameSite=Lax'; + break; + case 'strict': + str += '; SameSite=Strict'; + break; + case 'none': + str += '; SameSite=None'; + break; + default: + throw new TypeError('option sameSite is invalid'); + } + } - return errorExError; -}; + return str; +} -errorEx.append = function (str, def) { - return { - message: function (v, message) { - v = v || def; +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ - if (v) { - message[0] += ' ' + str.replace('%s', v.toString()); - } +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} - return message; - } - }; -}; -errorEx.line = function (str, def) { - return { - line: function (v) { - v = v || def; +/***/ }), - if (v) { - return str.replace('%s', v.toString()); - } +/***/ 65507: +/***/ ((__unused_webpack_module, exports) => { - return null; - } - }; -}; +/* jshint node: true */ +(function () { + "use strict"; -module.exports = errorEx; + function CookieAccessInfo(domain, path, secure, script) { + if (this instanceof CookieAccessInfo) { + this.domain = domain || undefined; + this.path = path || "/"; + this.secure = !!secure; + this.script = !!script; + return this; + } + return new CookieAccessInfo(domain, path, secure, script); + } + CookieAccessInfo.All = Object.freeze(Object.create(null)); + exports.CookieAccessInfo = CookieAccessInfo; + function Cookie(cookiestr, request_domain, request_path) { + if (cookiestr instanceof Cookie) { + return cookiestr; + } + if (this instanceof Cookie) { + this.name = null; + this.value = null; + this.expiration_date = Infinity; + this.path = String(request_path || "/"); + this.explicit_path = false; + this.domain = request_domain || null; + this.explicit_domain = false; + this.secure = false; //how to define default? + this.noscript = false; //httponly + if (cookiestr) { + this.parse(cookiestr, request_domain, request_path); + } + return this; + } + return new Cookie(cookiestr, request_domain, request_path); + } + exports.Cookie = Cookie; -/***/ }), + Cookie.prototype.toString = function toString() { + var str = [this.name + "=" + this.value]; + if (this.expiration_date !== Infinity) { + str.push("expires=" + (new Date(this.expiration_date)).toGMTString()); + } + if (this.domain) { + str.push("domain=" + this.domain); + } + if (this.path) { + str.push("path=" + this.path); + } + if (this.secure) { + str.push("secure"); + } + if (this.noscript) { + str.push("httponly"); + } + return str.join("; "); + }; -/***/ 94070: -/***/ ((module) => { + Cookie.prototype.toValueString = function toValueString() { + return this.name + "=" + this.value; + }; -"use strict"; -/*! - * escape-html - * Copyright(c) 2012-2013 TJ Holowaychuk - * Copyright(c) 2015 Andreas Lubbe - * Copyright(c) 2015 Tiancheng "Timothy" Gu - * MIT Licensed - */ + var cookie_str_splitter = /[:](?=\s*[a-zA-Z0-9_\-]+\s*[=])/g; + Cookie.prototype.parse = function parse(str, request_domain, request_path) { + if (this instanceof Cookie) { + var parts = str.split(";").filter(function (value) { + return !!value; + }); + var i; + var pair = parts[0].match(/([^=]+)=([\s\S]*)/); + if (!pair) { + console.warn("Invalid cookie header encountered. Header: '"+str+"'"); + return; + } + var key = pair[1]; + var value = pair[2]; + if ( typeof key !== 'string' || key.length === 0 || typeof value !== 'string' ) { + console.warn("Unable to extract values from cookie header. Cookie: '"+str+"'"); + return; + } -/** - * Module variables. - * @private - */ + this.name = key; + this.value = value; -var matchHtmlRegExp = /["'&<>]/; + for (i = 1; i < parts.length; i += 1) { + pair = parts[i].match(/([^=]+)(?:=([\s\S]*))?/); + key = pair[1].trim().toLowerCase(); + value = pair[2]; + switch (key) { + case "httponly": + this.noscript = true; + break; + case "expires": + this.expiration_date = value ? + Number(Date.parse(value)) : + Infinity; + break; + case "path": + this.path = value ? + value.trim() : + ""; + this.explicit_path = true; + break; + case "domain": + this.domain = value ? + value.trim() : + ""; + this.explicit_domain = !!this.domain; + break; + case "secure": + this.secure = true; + break; + } + } -/** - * Module exports. - * @public - */ + if (!this.explicit_path) { + this.path = request_path || "/"; + } + if (!this.explicit_domain) { + this.domain = request_domain; + } -module.exports = escapeHtml; + return this; + } + return new Cookie().parse(str, request_domain, request_path); + }; -/** - * Escape special characters in the given string of html. - * - * @param {string} string The string to escape for inserting into HTML - * @return {string} - * @public - */ + Cookie.prototype.matches = function matches(access_info) { + if (access_info === CookieAccessInfo.All) { + return true; + } + if (this.noscript && access_info.script || + this.secure && !access_info.secure || + !this.collidesWith(access_info)) { + return false; + } + return true; + }; -function escapeHtml(string) { - var str = '' + string; - var match = matchHtmlRegExp.exec(str); + Cookie.prototype.collidesWith = function collidesWith(access_info) { + if ((this.path && !access_info.path) || (this.domain && !access_info.domain)) { + return false; + } + if (this.path && access_info.path.indexOf(this.path) !== 0) { + return false; + } + if (this.explicit_path && access_info.path.indexOf( this.path ) !== 0) { + return false; + } + var access_domain = access_info.domain && access_info.domain.replace(/^[\.]/,''); + var cookie_domain = this.domain && this.domain.replace(/^[\.]/,''); + if (cookie_domain === access_domain) { + return true; + } + if (cookie_domain) { + if (!this.explicit_domain) { + return false; // we already checked if the domains were exactly the same + } + var wildcard = access_domain.indexOf(cookie_domain); + if (wildcard === -1 || wildcard !== access_domain.length - cookie_domain.length) { + return false; + } + return true; + } + return true; + }; - if (!match) { - return str; - } + function CookieJar() { + var cookies, cookies_list, collidable_cookie; + if (this instanceof CookieJar) { + cookies = Object.create(null); //name: [Cookie] - var escape; - var html = ''; - var index = 0; - var lastIndex = 0; + this.setCookie = function setCookie(cookie, request_domain, request_path) { + var remove, i; + cookie = new Cookie(cookie, request_domain, request_path); + //Delete the cookie if the set is past the current time + remove = cookie.expiration_date <= Date.now(); + if (cookies[cookie.name] !== undefined) { + cookies_list = cookies[cookie.name]; + for (i = 0; i < cookies_list.length; i += 1) { + collidable_cookie = cookies_list[i]; + if (collidable_cookie.collidesWith(cookie)) { + if (remove) { + cookies_list.splice(i, 1); + if (cookies_list.length === 0) { + delete cookies[cookie.name]; + } + return false; + } + cookies_list[i] = cookie; + return cookie; + } + } + if (remove) { + return false; + } + cookies_list.push(cookie); + return cookie; + } + if (remove) { + return false; + } + cookies[cookie.name] = [cookie]; + return cookies[cookie.name]; + }; + //returns a cookie + this.getCookie = function getCookie(cookie_name, access_info) { + var cookie, i; + cookies_list = cookies[cookie_name]; + if (!cookies_list) { + return; + } + for (i = 0; i < cookies_list.length; i += 1) { + cookie = cookies_list[i]; + if (cookie.expiration_date <= Date.now()) { + if (cookies_list.length === 0) { + delete cookies[cookie.name]; + } + continue; + } - for (index = match.index; index < str.length; index++) { - switch (str.charCodeAt(index)) { - case 34: // " - escape = '"'; - break; - case 38: // & - escape = '&'; - break; - case 39: // ' - escape = '''; - break; - case 60: // < - escape = '<'; - break; - case 62: // > - escape = '>'; - break; - default: - continue; - } + if (cookie.matches(access_info)) { + return cookie; + } + } + }; + //returns a list of cookies + this.getCookies = function getCookies(access_info) { + var matches = [], cookie_name, cookie; + for (cookie_name in cookies) { + cookie = this.getCookie(cookie_name, access_info); + if (cookie) { + matches.push(cookie); + } + } + matches.toString = function toString() { + return matches.join(":"); + }; + matches.toValueString = function toValueString() { + return matches.map(function (c) { + return c.toValueString(); + }).join(';'); + }; + return matches; + }; - if (lastIndex !== index) { - html += str.substring(lastIndex, index); + return this; + } + return new CookieJar(); } + exports.CookieJar = CookieJar; - lastIndex = index + 1; - html += escape; - } - - return lastIndex !== index - ? html + str.substring(lastIndex, index) - : html; -} + //returns list of cookies that were set correctly. Cookies that are expired and removed are not returned. + CookieJar.prototype.setCookies = function setCookies(cookies, request_domain, request_path) { + cookies = Array.isArray(cookies) ? + cookies : + cookies.split(cookie_str_splitter); + var successful = [], + i, + cookie; + cookies = cookies.map(function(item){ + return new Cookie(item, request_domain, request_path); + }); + for (i = 0; i < cookies.length; i += 1) { + cookie = cookies[i]; + if (this.setCookie(cookie, request_domain, request_path)) { + successful.push(cookie); + } + } + return successful; + }; +}()); /***/ }), -/***/ 98691: -/***/ ((module) => { +/***/ 51512: +/***/ ((module, exports) => { "use strict"; - - -module.exports = string => { - if (typeof string !== 'string') { - throw new TypeError('Expected a string'); - } - - // Escape characters with special meaning either inside or outside character sets. - // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. - return string - .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') - .replace(/-/g, '\\x2d'); -}; - +function _typeof(obj){"@babel/helpers - typeof";if(typeof Symbol==="function"&&typeof Symbol.iterator==="symbol"){_typeof=function _typeof(obj){return typeof obj}}else{_typeof=function _typeof(obj){return obj&&typeof Symbol==="function"&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj}}return _typeof(obj)}(function(global){var _arguments=arguments;var dateFormat=function(){var token=/d{1,4}|D{3,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|W{1,2}|[LlopSZN]|"[^"]*"|'[^']*'/g;var timezone=/\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g;var timezoneClip=/[^-+\dA-Z]/g;return function(date,mask,utc,gmt){if(_arguments.length===1&&kindOf(date)==="string"&&!/\d/.test(date)){mask=date;date=undefined}date=date||date===0?date:new Date;if(!(date instanceof Date)){date=new Date(date)}if(isNaN(date)){throw TypeError("Invalid date")}mask=String(dateFormat.masks[mask]||mask||dateFormat.masks["default"]);var maskSlice=mask.slice(0,4);if(maskSlice==="UTC:"||maskSlice==="GMT:"){mask=mask.slice(4);utc=true;if(maskSlice==="GMT:"){gmt=true}}var _=function _(){return utc?"getUTC":"get"};var _d=function d(){return date[_()+"Date"]()};var D=function D(){return date[_()+"Day"]()};var _m=function m(){return date[_()+"Month"]()};var y=function y(){return date[_()+"FullYear"]()};var _H=function H(){return date[_()+"Hours"]()};var _M=function M(){return date[_()+"Minutes"]()};var _s=function s(){return date[_()+"Seconds"]()};var _L=function L(){return date[_()+"Milliseconds"]()};var _o=function o(){return utc?0:date.getTimezoneOffset()};var _W=function W(){return getWeek(date)};var _N=function N(){return getDayOfWeek(date)};var flags={d:function d(){return _d()},dd:function dd(){return pad(_d())},ddd:function ddd(){return dateFormat.i18n.dayNames[D()]},DDD:function DDD(){return getDayName({y:y(),m:_m(),d:_d(),_:_(),dayName:dateFormat.i18n.dayNames[D()],short:true})},dddd:function dddd(){return dateFormat.i18n.dayNames[D()+7]},DDDD:function DDDD(){return getDayName({y:y(),m:_m(),d:_d(),_:_(),dayName:dateFormat.i18n.dayNames[D()+7]})},m:function m(){return _m()+1},mm:function mm(){return pad(_m()+1)},mmm:function mmm(){return dateFormat.i18n.monthNames[_m()]},mmmm:function mmmm(){return dateFormat.i18n.monthNames[_m()+12]},yy:function yy(){return String(y()).slice(2)},yyyy:function yyyy(){return pad(y(),4)},h:function h(){return _H()%12||12},hh:function hh(){return pad(_H()%12||12)},H:function H(){return _H()},HH:function HH(){return pad(_H())},M:function M(){return _M()},MM:function MM(){return pad(_M())},s:function s(){return _s()},ss:function ss(){return pad(_s())},l:function l(){return pad(_L(),3)},L:function L(){return pad(Math.floor(_L()/10))},t:function t(){return _H()<12?dateFormat.i18n.timeNames[0]:dateFormat.i18n.timeNames[1]},tt:function tt(){return _H()<12?dateFormat.i18n.timeNames[2]:dateFormat.i18n.timeNames[3]},T:function T(){return _H()<12?dateFormat.i18n.timeNames[4]:dateFormat.i18n.timeNames[5]},TT:function TT(){return _H()<12?dateFormat.i18n.timeNames[6]:dateFormat.i18n.timeNames[7]},Z:function Z(){return gmt?"GMT":utc?"UTC":(String(date).match(timezone)||[""]).pop().replace(timezoneClip,"").replace(/GMT\+0000/g,"UTC")},o:function o(){return(_o()>0?"-":"+")+pad(Math.floor(Math.abs(_o())/60)*100+Math.abs(_o())%60,4)},p:function p(){return(_o()>0?"-":"+")+pad(Math.floor(Math.abs(_o())/60),2)+":"+pad(Math.floor(Math.abs(_o())%60),2)},S:function S(){return["th","st","nd","rd"][_d()%10>3?0:(_d()%100-_d()%10!=10)*_d()%10]},W:function W(){return _W()},WW:function WW(){return pad(_W())},N:function N(){return _N()}};return mask.replace(token,function(match){if(match in flags){return flags[match]()}return match.slice(1,match.length-1)})}}();dateFormat.masks={default:"ddd mmm dd yyyy HH:MM:ss",shortDate:"m/d/yy",paddedShortDate:"mm/dd/yyyy",mediumDate:"mmm d, yyyy",longDate:"mmmm d, yyyy",fullDate:"dddd, mmmm d, yyyy",shortTime:"h:MM TT",mediumTime:"h:MM:ss TT",longTime:"h:MM:ss TT Z",isoDate:"yyyy-mm-dd",isoTime:"HH:MM:ss",isoDateTime:"yyyy-mm-dd'T'HH:MM:sso",isoUtcDateTime:"UTC:yyyy-mm-dd'T'HH:MM:ss'Z'",expiresHeaderFormat:"ddd, dd mmm yyyy HH:MM:ss Z"};dateFormat.i18n={dayNames:["Sun","Mon","Tue","Wed","Thu","Fri","Sat","Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],monthNames:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec","January","February","March","April","May","June","July","August","September","October","November","December"],timeNames:["a","p","am","pm","A","P","AM","PM"]};var pad=function pad(val,len){val=String(val);len=len||2;while(val.length { +/***/ 28222: +/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; -/*! - * etag - * Copyright(c) 2014-2016 Douglas Christopher Wilson - * MIT Licensed +/* eslint-env browser */ + +/** + * This is the web browser implementation of `debug()`. */ +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = localstorage(); +exports.destroy = (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } + }; +})(); /** - * Module exports. - * @public + * Colors. */ -module.exports = etag +exports.colors = [ + '#0000CC', + '#0000FF', + '#0033CC', + '#0033FF', + '#0066CC', + '#0066FF', + '#0099CC', + '#0099FF', + '#00CC00', + '#00CC33', + '#00CC66', + '#00CC99', + '#00CCCC', + '#00CCFF', + '#3300CC', + '#3300FF', + '#3333CC', + '#3333FF', + '#3366CC', + '#3366FF', + '#3399CC', + '#3399FF', + '#33CC00', + '#33CC33', + '#33CC66', + '#33CC99', + '#33CCCC', + '#33CCFF', + '#6600CC', + '#6600FF', + '#6633CC', + '#6633FF', + '#66CC00', + '#66CC33', + '#9900CC', + '#9900FF', + '#9933CC', + '#9933FF', + '#99CC00', + '#99CC33', + '#CC0000', + '#CC0033', + '#CC0066', + '#CC0099', + '#CC00CC', + '#CC00FF', + '#CC3300', + '#CC3333', + '#CC3366', + '#CC3399', + '#CC33CC', + '#CC33FF', + '#CC6600', + '#CC6633', + '#CC9900', + '#CC9933', + '#CCCC00', + '#CCCC33', + '#FF0000', + '#FF0033', + '#FF0066', + '#FF0099', + '#FF00CC', + '#FF00FF', + '#FF3300', + '#FF3333', + '#FF3366', + '#FF3399', + '#FF33CC', + '#FF33FF', + '#FF6600', + '#FF6633', + '#FF9900', + '#FF9933', + '#FFCC00', + '#FFCC33' +]; /** - * Module dependencies. - * @private + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors */ -var crypto = __nccwpck_require__(76417) -var Stats = __nccwpck_require__(35747).Stats +// eslint-disable-next-line complexity +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && (window.process.type === 'renderer' || window.process.__nwjs)) { + return true; + } -/** - * Module variables. - * @private - */ + // Internet Explorer and Edge do not support colors. + if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } -var toString = Object.prototype.toString + // Is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // Is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // Double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} /** - * Generate an entity tag. + * Colorize log arguments if enabled. * - * @param {Buffer|string} entity - * @return {string} - * @private + * @api public */ -function entitytag (entity) { - if (entity.length === 0) { - // fast-path empty - return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' - } +function formatArgs(args) { + args[0] = (this.useColors ? '%c' : '') + + this.namespace + + (this.useColors ? ' %c' : ' ') + + args[0] + + (this.useColors ? '%c ' : ' ') + + '+' + module.exports.humanize(this.diff); - // compute hash of entity - var hash = crypto - .createHash('sha1') - .update(entity, 'utf8') - .digest('base64') - .substring(0, 27) + if (!this.useColors) { + return; + } - // compute length of entity - var len = typeof entity === 'string' - ? Buffer.byteLength(entity, 'utf8') - : entity.length + const c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit'); - return '"' + len.toString(16) + '-' + hash + '"' + // The final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + let index = 0; + let lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, match => { + if (match === '%%') { + return; + } + index++; + if (match === '%c') { + // We only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); + + args.splice(lastC, 0, c); } /** - * Create a simple ETag. + * Invokes `console.debug()` when available. + * No-op when `console.debug` is not a "function". + * If `console.debug` is not available, falls back + * to `console.log`. * - * @param {string|Buffer|Stats} entity - * @param {object} [options] - * @param {boolean} [options.weak] - * @return {String} - * @public + * @api public */ +exports.log = console.debug || console.log || (() => {}); -function etag (entity, options) { - if (entity == null) { - throw new TypeError('argument entity is required') - } - - // support fs.Stats object - var isStats = isstats(entity) - var weak = options && typeof options.weak === 'boolean' - ? options.weak - : isStats - - // validate argument - if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { - throw new TypeError('argument entity must be string, Buffer, or fs.Stats') - } - - // generate entity tag - var tag = isStats - ? stattag(entity) - : entitytag(entity) - - return weak - ? 'W/' + tag - : tag +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ +function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem('debug', namespaces); + } else { + exports.storage.removeItem('debug'); + } + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } } /** - * Determine if object is a Stats object. + * Load `namespaces`. * - * @param {object} obj - * @return {boolean} + * @return {String} returns the previously persisted debug modes * @api private */ +function load() { + let r; + try { + r = exports.storage.getItem('debug'); + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } -function isstats (obj) { - // genuine fs.Stats - if (typeof Stats === 'function' && obj instanceof Stats) { - return true - } + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } - // quack quack - return obj && typeof obj === 'object' && - 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && - 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && - 'ino' in obj && typeof obj.ino === 'number' && - 'size' in obj && typeof obj.size === 'number' + return r; } /** - * Generate a tag for a stat. + * Localstorage attempts to return the localstorage. * - * @param {object} stat - * @return {string} - * @private + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private */ -function stattag (stat) { - var mtime = stat.mtime.getTime().toString(16) - var size = stat.size.toString(16) - - return '"' + size + '-' + mtime + '"' +function localstorage() { + try { + // TVMLKit (Apple TV JS Runtime) does not have a window object, just localStorage in the global context + // The Browser also has localStorage in the global context. + return localStorage; + } catch (error) { + // Swallow + // XXX (@Qix-) should we be logging these? + } } +module.exports = __nccwpck_require__(46243)(exports); + +const {formatters} = module.exports; + +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ + +formatters.j = function (v) { + try { + return JSON.stringify(v); + } catch (error) { + return '[UnexpectedJSONParseError]: ' + error.message; + } +}; + /***/ }), -/***/ 68883: +/***/ 46243: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var original = __nccwpck_require__(80086) -var parse = __nccwpck_require__(78835).parse -var events = __nccwpck_require__(28614) -var https = __nccwpck_require__(57211) -var http = __nccwpck_require__(98605) -var util = __nccwpck_require__(31669) -var httpsOptions = [ - 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers', - 'rejectUnauthorized', 'secureProtocol', 'servername', 'checkServerIdentity' -] +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + */ -var bom = [239, 187, 191] -var colon = 58 -var space = 32 -var lineFeed = 10 -var carriageReturn = 13 +function setup(env) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = __nccwpck_require__(80900); + createDebug.destroy = destroy; + + Object.keys(env).forEach(key => { + createDebug[key] = env[key]; + }); + + /** + * The currently active debug mode names, and names to skip. + */ + + createDebug.names = []; + createDebug.skips = []; + + /** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + createDebug.formatters = {}; + + /** + * Selects a color for a debug namespace + * @param {String} namespace The namespace string for the for the debug instance to be colored + * @return {Number|String} An ANSI color code for the given namespace + * @api private + */ + function selectColor(namespace) { + let hash = 0; + + for (let i = 0; i < namespace.length; i++) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return createDebug.colors[Math.abs(hash) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + + /** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + + function debug(...args) { + // Disabled? + if (!debug.enabled) { + return; + } + + const self = debug; + + // Set `diff` timestamp + const curr = Number(new Date()); + const ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + args[0] = createDebug.coerce(args[0]); + + if (typeof args[0] !== 'string') { + // Anything else let's inspect with %O + args.unshift('%O'); + } + + // Apply any `formatters` transformations + let index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, (match, format) => { + // If we encounter an escaped % then don't increase the array index + if (match === '%%') { + return '%'; + } + index++; + const formatter = createDebug.formatters[format]; + if (typeof formatter === 'function') { + const val = args[index]; + match = formatter.call(self, val); + + // Now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // Apply env-specific formatting (colors, etc.) + createDebug.formatArgs.call(self, args); + + const logFn = self.log || createDebug.log; + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.useColors = createDebug.useColors(); + debug.color = createDebug.selectColor(namespace); + debug.extend = extend; + debug.destroy = createDebug.destroy; // XXX Temporary. Will be removed in the next major release. -function hasBom (buf) { - return bom.every(function (charCode, index) { - return buf[index] === charCode - }) -} + Object.defineProperty(debug, 'enabled', { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } -/** - * Creates a new EventSource object - * - * @param {String} url the URL to which to connect - * @param {Object} [eventSourceInitDict] extra init params. See README for details. - * @api public - **/ -function EventSource (url, eventSourceInitDict) { - var readyState = EventSource.CONNECTING - Object.defineProperty(this, 'readyState', { - get: function () { - return readyState - } - }) + return enabledCache; + }, + set: v => { + enableOverride = v; + } + }); - Object.defineProperty(this, 'url', { - get: function () { - return url - } - }) + // Env-specific initialization logic for debug instances + if (typeof createDebug.init === 'function') { + createDebug.init(debug); + } - var self = this - self.reconnectInterval = 1000 + return debug; + } - function onConnectionClosed (message) { - if (readyState === EventSource.CLOSED) return - readyState = EventSource.CONNECTING - _emit('error', new Event('error', {message: message})) + function extend(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === 'undefined' ? ':' : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } - // The url may have been changed by a temporary - // redirect. If that's the case, revert it now. - if (reconnectUrl) { - url = reconnectUrl - reconnectUrl = null - } - setTimeout(function () { - if (readyState !== EventSource.CONNECTING) { - return - } - connect() - }, self.reconnectInterval) - } + /** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; - var req - var lastEventId = '' - if (eventSourceInitDict && eventSourceInitDict.headers && eventSourceInitDict.headers['Last-Event-ID']) { - lastEventId = eventSourceInitDict.headers['Last-Event-ID'] - delete eventSourceInitDict.headers['Last-Event-ID'] - } + createDebug.names = []; + createDebug.skips = []; - var discardTrailingNewline = false - var data = '' - var eventName = '' + let i; + const split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + const len = split.length; - var reconnectUrl = null + for (i = 0; i < len; i++) { + if (!split[i]) { + // ignore empty strings + continue; + } - function connect () { - var options = parse(url) - var isSecure = options.protocol === 'https:' - options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' } - if (lastEventId) options.headers['Last-Event-ID'] = lastEventId - if (eventSourceInitDict && eventSourceInitDict.headers) { - for (var i in eventSourceInitDict.headers) { - var header = eventSourceInitDict.headers[i] - if (header) { - options.headers[i] = header - } - } - } + namespaces = split[i].replace(/\*/g, '.*?'); - // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`, - // but for now exists as a backwards-compatibility layer - options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized) + if (namespaces[0] === '-') { + createDebug.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + createDebug.names.push(new RegExp('^' + namespaces + '$')); + } + } + } - // If specify http proxy, make the request to sent to the proxy server, - // and include the original url in path and Host headers - var useProxy = eventSourceInitDict && eventSourceInitDict.proxy - if (useProxy) { - var proxy = parse(eventSourceInitDict.proxy) - isSecure = proxy.protocol === 'https:' + /** + * Disable debug output. + * + * @return {String} namespaces + * @api public + */ + function disable() { + const namespaces = [ + ...createDebug.names.map(toNamespace), + ...createDebug.skips.map(toNamespace).map(namespace => '-' + namespace) + ].join(','); + createDebug.enable(''); + return namespaces; + } - options.protocol = isSecure ? 'https:' : 'http:' - options.path = url - options.headers.Host = options.host - options.hostname = proxy.hostname - options.host = proxy.host - options.port = proxy.port - } + /** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + function enabled(name) { + if (name[name.length - 1] === '*') { + return true; + } - // If https options are specified, merge them into the request options - if (eventSourceInitDict && eventSourceInitDict.https) { - for (var optName in eventSourceInitDict.https) { - if (httpsOptions.indexOf(optName) === -1) { - continue - } + let i; + let len; - var option = eventSourceInitDict.https[optName] - if (option !== undefined) { - options[optName] = option - } - } - } + for (i = 0, len = createDebug.skips.length; i < len; i++) { + if (createDebug.skips[i].test(name)) { + return false; + } + } - // Pass this on to the XHR - if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) { - options.withCredentials = eventSourceInitDict.withCredentials - } + for (i = 0, len = createDebug.names.length; i < len; i++) { + if (createDebug.names[i].test(name)) { + return true; + } + } - req = (isSecure ? https : http).request(options, function (res) { - // Handle HTTP errors - if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) { - _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) - onConnectionClosed() - return - } + return false; + } - // Handle HTTP redirects - if (res.statusCode === 301 || res.statusCode === 307) { - if (!res.headers.location) { - // Server sent redirect response without Location header. - _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) - return - } - if (res.statusCode === 307) reconnectUrl = url - url = res.headers.location - process.nextTick(connect) - return - } + /** + * Convert regexp to namespace + * + * @param {RegExp} regxep + * @return {String} namespace + * @api private + */ + function toNamespace(regexp) { + return regexp.toString() + .substring(2, regexp.toString().length - 2) + .replace(/\.\*\?$/, '*'); + } - if (res.statusCode !== 200) { - _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) - return self.close() - } + /** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } - readyState = EventSource.OPEN - res.on('close', function () { - res.removeAllListeners('close') - res.removeAllListeners('end') - onConnectionClosed() - }) + /** + * XXX DO NOT USE. This is a temporary stub function. + * XXX It WILL be removed in the next major release. + */ + function destroy() { + console.warn('Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.'); + } - res.on('end', function () { - res.removeAllListeners('close') - res.removeAllListeners('end') - onConnectionClosed() - }) - _emit('open', new Event('open')) + createDebug.enable(createDebug.load()); - // text/event-stream parser adapted from webkit's - // Source/WebCore/page/EventSource.cpp - var isFirst = true - var buf - res.on('data', function (chunk) { - buf = buf ? Buffer.concat([buf, chunk]) : chunk - if (isFirst && hasBom(buf)) { - buf = buf.slice(bom.length) - } + return createDebug; +} - isFirst = false - var pos = 0 - var length = buf.length +module.exports = setup; - while (pos < length) { - if (discardTrailingNewline) { - if (buf[pos] === lineFeed) { - ++pos - } - discardTrailingNewline = false - } - var lineLength = -1 - var fieldLength = -1 - var c +/***/ }), - for (var i = pos; lineLength < 0 && i < length; ++i) { - c = buf[i] - if (c === colon) { - if (fieldLength < 0) { - fieldLength = i - pos - } - } else if (c === carriageReturn) { - discardTrailingNewline = true - lineLength = i - pos - } else if (c === lineFeed) { - lineLength = i - pos - } - } +/***/ 38237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (lineLength < 0) { - break - } +/** + * Detect Electron renderer / nwjs process, which is node, but we should + * treat as a browser. + */ - parseEventStreamLine(buf, pos, fieldLength, lineLength) +if (typeof process === 'undefined' || process.type === 'renderer' || process.browser === true || process.__nwjs) { + module.exports = __nccwpck_require__(28222); +} else { + module.exports = __nccwpck_require__(35332); +} - pos += lineLength + 1 - } - if (pos === length) { - buf = void 0 - } else if (pos > 0) { - buf = buf.slice(pos) - } - }) - }) +/***/ }), - req.on('error', function (err) { - onConnectionClosed(err.message) - }) +/***/ 35332: +/***/ ((module, exports, __nccwpck_require__) => { - if (req.setNoDelay) req.setNoDelay(true) - req.end() - } +/** + * Module dependencies. + */ - connect() +const tty = __nccwpck_require__(33867); +const util = __nccwpck_require__(31669); - function _emit () { - if (self.listeners(arguments[0]).length > 0) { - self.emit.apply(self, arguments) - } - } +/** + * This is the Node.js implementation of `debug()`. + */ - this._close = function () { - if (readyState === EventSource.CLOSED) return - readyState = EventSource.CLOSED - if (req.abort) req.abort() - if (req.xhr && req.xhr.abort) req.xhr.abort() - } +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.destroy = util.deprecate( + () => {}, + 'Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.' +); - function parseEventStreamLine (buf, pos, fieldLength, lineLength) { - if (lineLength === 0) { - if (data.length > 0) { - var type = eventName || 'message' - _emit(type, new MessageEvent(type, { - data: data.slice(0, -1), // remove trailing newline - lastEventId: lastEventId, - origin: original(url) - })) - data = '' - } - eventName = void 0 - } else if (fieldLength > 0) { - var noValue = fieldLength < 0 - var step = 0 - var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString() +/** + * Colors. + */ - if (noValue) { - step = lineLength - } else if (buf[pos + fieldLength + 1] !== space) { - step = fieldLength + 1 - } else { - step = fieldLength + 2 - } - pos += step +exports.colors = [6, 2, 3, 4, 5, 1]; - var valueLength = lineLength - step - var value = buf.slice(pos, pos + valueLength).toString() +try { + // Optional dependency (as in, doesn't need to be installed, NOT like optionalDependencies in package.json) + // eslint-disable-next-line import/no-extraneous-dependencies + const supportsColor = __nccwpck_require__(59318); - if (field === 'data') { - data += value + '\n' - } else if (field === 'event') { - eventName = value - } else if (field === 'id') { - lastEventId = value - } else if (field === 'retry') { - var retry = parseInt(value, 10) - if (!Number.isNaN(retry)) { - self.reconnectInterval = retry - } - } - } - } + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } +} catch (error) { + // Swallow - we only care if `supports-color` is available; it doesn't have to be. } -module.exports = EventSource +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ -util.inherits(EventSource, events.EventEmitter) -EventSource.prototype.constructor = EventSource; // make stacktraces readable +exports.inspectOpts = Object.keys(process.env).filter(key => { + return /^debug_/i.test(key); +}).reduce((obj, key) => { + // Camel-case + const prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); -['open', 'error', 'message'].forEach(function (method) { - Object.defineProperty(EventSource.prototype, 'on' + method, { - /** - * Returns the current listener - * - * @return {Mixed} the set function or undefined - * @api private - */ - get: function get () { - var listener = this.listeners(method)[0] - return listener ? (listener._listener ? listener._listener : listener) : undefined - }, + // Coerce string value into JS value + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === 'null') { + val = null; + } else { + val = Number(val); + } - /** - * Start listening for events - * - * @param {Function} listener the listener - * @return {Mixed} the set function or undefined - * @api private - */ - set: function set (listener) { - this.removeAllListeners(method) - this.addEventListener(method, listener) - } - }) -}) + obj[prop] = val; + return obj; +}, {}); /** - * Ready states + * Is stdout a TTY? Colored output is enabled when `true`. */ -Object.defineProperty(EventSource, 'CONNECTING', {enumerable: true, value: 0}) -Object.defineProperty(EventSource, 'OPEN', {enumerable: true, value: 1}) -Object.defineProperty(EventSource, 'CLOSED', {enumerable: true, value: 2}) -EventSource.prototype.CONNECTING = 0 -EventSource.prototype.OPEN = 1 -EventSource.prototype.CLOSED = 2 +function useColors() { + return 'colors' in exports.inspectOpts ? + Boolean(exports.inspectOpts.colors) : + tty.isatty(process.stderr.fd); +} /** - * Closes the connection, if one is made, and sets the readyState attribute to 2 (closed) + * Adds ANSI color escape codes if enabled. * - * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close * @api public */ -EventSource.prototype.close = function () { - this._close() + +function formatArgs(args) { + const {namespace: name, useColors} = this; + + if (useColors) { + const c = this.color; + const colorCode = '\u001B[3' + (c < 8 ? c : '8;5;' + c); + const prefix = ` ${colorCode};1m${name} \u001B[0m`; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push(colorCode + 'm+' + module.exports.humanize(this.diff) + '\u001B[0m'); + } else { + args[0] = getDate() + name + ' ' + args[0]; + } } -/** - * Emulates the W3C Browser based WebSocket interface using addEventListener. - * - * @param {String} type A string representing the event type to listen out for - * @param {Function} listener callback - * @see https://developer.mozilla.org/en/DOM/element.addEventListener - * @see http://dev.w3.org/html5/websockets/#the-websocket-interface - * @api public - */ -EventSource.prototype.addEventListener = function addEventListener (type, listener) { - if (typeof listener === 'function') { - // store a reference so we can return the original function again - listener._listener = listener - this.on(type, listener) - } +function getDate() { + if (exports.inspectOpts.hideDate) { + return ''; + } + return new Date().toISOString() + ' '; } /** - * Emulates the W3C Browser based WebSocket interface using dispatchEvent. - * - * @param {Event} event An event to be dispatched - * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent - * @api public + * Invokes `util.format()` with the specified arguments and writes to stderr. */ -EventSource.prototype.dispatchEvent = function dispatchEvent (event) { - if (!event.type) { - throw new Error('UNSPECIFIED_EVENT_TYPE_ERR') - } - // if event is instance of an CustomEvent (or has 'details' property), - // send the detail object as the payload for the event - this.emit(event.type, event.detail) + +function log(...args) { + return process.stderr.write(util.format(...args) + '\n'); } /** - * Emulates the W3C Browser based WebSocket interface using removeEventListener. + * Save `namespaces`. * - * @param {String} type A string representing the event type to remove - * @param {Function} listener callback - * @see https://developer.mozilla.org/en/DOM/element.removeEventListener - * @see http://dev.w3.org/html5/websockets/#the-websocket-interface - * @api public + * @param {String} namespaces + * @api private */ -EventSource.prototype.removeEventListener = function removeEventListener (type, listener) { - if (typeof listener === 'function') { - listener._listener = undefined - this.removeListener(type, listener) - } +function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } } /** - * W3C Event + * Load `namespaces`. * - * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event + * @return {String} returns the previously persisted debug modes * @api private */ -function Event (type, optionalProperties) { - Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) - if (optionalProperties) { - for (var f in optionalProperties) { - if (optionalProperties.hasOwnProperty(f)) { - Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true }) - } - } - } + +function load() { + return process.env.DEBUG; } /** - * W3C MessageEvent + * Init logic for `debug` instances. * - * @see http://www.w3.org/TR/webmessaging/#event-definitions - * @api private + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. */ -function MessageEvent (type, eventInitDict) { - Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) - for (var f in eventInitDict) { - if (eventInitDict.hasOwnProperty(f)) { - Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true }) - } - } -} +function init(debug) { + debug.inspectOpts = {}; -/***/ }), + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} -/***/ 71204: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +module.exports = __nccwpck_require__(46243)(exports); -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed +const {formatters} = module.exports; + +/** + * Map %o to `util.inspect()`, all on a single line. */ +formatters.o = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n') + .map(str => str.trim()) + .join(' '); +}; +/** + * Map %O to `util.inspect()`, allowing multiple lines if needed. + */ -module.exports = __nccwpck_require__(22587); +formatters.O = function (v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; /***/ }), -/***/ 313: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 56323: +/***/ ((module) => { "use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +var isMergeableObject = function isMergeableObject(value) { + return isNonNullObject(value) + && !isSpecial(value) +}; -/** - * Module dependencies. - * @private - */ +function isNonNullObject(value) { + return !!value && typeof value === 'object' +} -var finalhandler = __nccwpck_require__(30810); -var Router = __nccwpck_require__(24963); -var methods = __nccwpck_require__(58752); -var middleware = __nccwpck_require__(92636); -var query = __nccwpck_require__(79768); -var debug = __nccwpck_require__(52529)('express:application'); -var View = __nccwpck_require__(99209); -var http = __nccwpck_require__(98605); -var compileETag = __nccwpck_require__(53561).compileETag; -var compileQueryParser = __nccwpck_require__(53561).compileQueryParser; -var compileTrust = __nccwpck_require__(53561).compileTrust; -var deprecate = __nccwpck_require__(18883)('express'); -var flatten = __nccwpck_require__(62003); -var merge = __nccwpck_require__(44429); -var resolve = __nccwpck_require__(85622).resolve; -var setPrototypeOf = __nccwpck_require__(40414) -var slice = Array.prototype.slice; +function isSpecial(value) { + var stringValue = Object.prototype.toString.call(value); -/** - * Application prototype. - */ + return stringValue === '[object RegExp]' + || stringValue === '[object Date]' + || isReactElement(value) +} -var app = exports = module.exports = {}; +// see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25 +var canUseSymbol = typeof Symbol === 'function' && Symbol.for; +var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7; -/** - * Variable for trust proxy inheritance back-compat - * @private - */ +function isReactElement(value) { + return value.$$typeof === REACT_ELEMENT_TYPE +} -var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; +function emptyTarget(val) { + return Array.isArray(val) ? [] : {} +} -/** - * Initialize the server. - * - * - setup default configuration - * - setup default middleware - * - setup route reflection methods - * - * @private - */ +function cloneUnlessOtherwiseSpecified(value, options) { + return (options.clone !== false && options.isMergeableObject(value)) + ? deepmerge(emptyTarget(value), value, options) + : value +} -app.init = function init() { - this.cache = {}; - this.engines = {}; - this.settings = {}; +function defaultArrayMerge(target, source, options) { + return target.concat(source).map(function(element) { + return cloneUnlessOtherwiseSpecified(element, options) + }) +} - this.defaultConfiguration(); -}; +function getMergeFunction(key, options) { + if (!options.customMerge) { + return deepmerge + } + var customMerge = options.customMerge(key); + return typeof customMerge === 'function' ? customMerge : deepmerge +} -/** - * Initialize application configuration. - * @private - */ +function getEnumerableOwnPropertySymbols(target) { + return Object.getOwnPropertySymbols + ? Object.getOwnPropertySymbols(target).filter(function(symbol) { + return target.propertyIsEnumerable(symbol) + }) + : [] +} -app.defaultConfiguration = function defaultConfiguration() { - var env = process.env.NODE_ENV || 'development'; +function getKeys(target) { + return Object.keys(target).concat(getEnumerableOwnPropertySymbols(target)) +} - // default settings - this.enable('x-powered-by'); - this.set('etag', 'weak'); - this.set('env', env); - this.set('query parser', 'extended'); - this.set('subdomain offset', 2); - this.set('trust proxy', false); +function propertyIsOnObject(object, property) { + try { + return property in object + } catch(_) { + return false + } +} - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: true - }); +// Protects from prototype poisoning and unexpected merging up the prototype chain. +function propertyIsUnsafe(target, key) { + return propertyIsOnObject(target, key) // Properties are safe to merge if they don't exist in the target yet, + && !(Object.hasOwnProperty.call(target, key) // unsafe if they exist up the prototype chain, + && Object.propertyIsEnumerable.call(target, key)) // and also unsafe if they're nonenumerable. +} - debug('booting in %s mode', env); +function mergeObject(target, source, options) { + var destination = {}; + if (options.isMergeableObject(target)) { + getKeys(target).forEach(function(key) { + destination[key] = cloneUnlessOtherwiseSpecified(target[key], options); + }); + } + getKeys(source).forEach(function(key) { + if (propertyIsUnsafe(target, key)) { + return + } - this.on('mount', function onmount(parent) { - // inherit trust proxy - if (this.settings[trustProxyDefaultSymbol] === true - && typeof parent.settings['trust proxy fn'] === 'function') { - delete this.settings['trust proxy']; - delete this.settings['trust proxy fn']; - } + if (propertyIsOnObject(target, key) && options.isMergeableObject(source[key])) { + destination[key] = getMergeFunction(key, options)(target[key], source[key], options); + } else { + destination[key] = cloneUnlessOtherwiseSpecified(source[key], options); + } + }); + return destination +} - // inherit protos - setPrototypeOf(this.request, parent.request) - setPrototypeOf(this.response, parent.response) - setPrototypeOf(this.engines, parent.engines) - setPrototypeOf(this.settings, parent.settings) - }); +function deepmerge(target, source, options) { + options = options || {}; + options.arrayMerge = options.arrayMerge || defaultArrayMerge; + options.isMergeableObject = options.isMergeableObject || isMergeableObject; + // cloneUnlessOtherwiseSpecified is added to `options` so that custom arrayMerge() + // implementations can use it. The caller may not replace it. + options.cloneUnlessOtherwiseSpecified = cloneUnlessOtherwiseSpecified; - // setup locals - this.locals = Object.create(null); + var sourceIsArray = Array.isArray(source); + var targetIsArray = Array.isArray(target); + var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray; - // top-most app is mounted at / - this.mountpath = '/'; + if (!sourceAndTargetTypesMatch) { + return cloneUnlessOtherwiseSpecified(source, options) + } else if (sourceIsArray) { + return options.arrayMerge(target, source, options) + } else { + return mergeObject(target, source, options) + } +} - // default locals - this.locals.settings = this.settings; +deepmerge.all = function deepmergeAll(array, options) { + if (!Array.isArray(array)) { + throw new Error('first argument should be an array') + } - // default configuration - this.set('view', View); - this.set('views', resolve('views')); - this.set('jsonp callback name', 'callback'); + return array.reduce(function(prev, next) { + return deepmerge(prev, next, options) + }, {}) +}; - if (env === 'production') { - this.enable('view cache'); +var deepmerge_1 = deepmerge; + +module.exports = deepmerge_1; + + +/***/ }), + +/***/ 18611: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Stream = __nccwpck_require__(92413).Stream; +var util = __nccwpck_require__(31669); + +module.exports = DelayedStream; +function DelayedStream() { + this.source = null; + this.dataSize = 0; + this.maxDataSize = 1024 * 1024; + this.pauseStream = true; + + this._maxDataSizeExceeded = false; + this._released = false; + this._bufferedEvents = []; +} +util.inherits(DelayedStream, Stream); + +DelayedStream.create = function(source, options) { + var delayedStream = new this(); + + options = options || {}; + for (var option in options) { + delayedStream[option] = options[option]; } - Object.defineProperty(this, 'router', { - get: function() { - throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); - } - }); -}; + delayedStream.source = source; -/** - * lazily adds the base router if it has not yet been added. - * - * We cannot add the base router in the defaultConfiguration because - * it reads app settings which might be set after that has run. - * - * @private - */ -app.lazyrouter = function lazyrouter() { - if (!this._router) { - this._router = new Router({ - caseSensitive: this.enabled('case sensitive routing'), - strict: this.enabled('strict routing') - }); + var realEmit = source.emit; + source.emit = function() { + delayedStream._handleEmit(arguments); + return realEmit.apply(source, arguments); + }; - this._router.use(query(this.get('query parser fn'))); - this._router.use(middleware.init(this)); + source.on('error', function() {}); + if (delayedStream.pauseStream) { + source.pause(); } -}; -/** - * Dispatch a req, res pair into the application. Starts pipeline processing. - * - * If no callback is provided, then default error handlers will respond - * in the event of an error bubbling through the stack. - * - * @private - */ + return delayedStream; +}; -app.handle = function handle(req, res, callback) { - var router = this._router; +Object.defineProperty(DelayedStream.prototype, 'readable', { + configurable: true, + enumerable: true, + get: function() { + return this.source.readable; + } +}); - // final handler - var done = callback || finalhandler(req, res, { - env: this.get('env'), - onerror: logerror.bind(this) - }); +DelayedStream.prototype.setEncoding = function() { + return this.source.setEncoding.apply(this.source, arguments); +}; - // no routes - if (!router) { - debug('no routes defined on app'); - done(); - return; +DelayedStream.prototype.resume = function() { + if (!this._released) { + this.release(); } - router.handle(req, res, done); + this.source.resume(); }; -/** - * Proxy `Router#use()` to add middleware to the app router. - * See Router#use() documentation for details. - * - * If the _fn_ parameter is an express app, then it will be - * mounted at the _route_ specified. - * - * @public - */ +DelayedStream.prototype.pause = function() { + this.source.pause(); +}; -app.use = function use(fn) { - var offset = 0; - var path = '/'; +DelayedStream.prototype.release = function() { + this._released = true; + + this._bufferedEvents.forEach(function(args) { + this.emit.apply(this, args); + }.bind(this)); + this._bufferedEvents = []; +}; - // default path to '/' - // disambiguate app.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; +DelayedStream.prototype.pipe = function() { + var r = Stream.prototype.pipe.apply(this, arguments); + this.resume(); + return r; +}; - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } +DelayedStream.prototype._handleEmit = function(args) { + if (this._released) { + this.emit.apply(this, args); + return; + } - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } + if (args[0] === 'data') { + this.dataSize += args[1].length; + this._checkIfMaxDataSizeExceeded(); } - var fns = flatten(slice.call(arguments, offset)); + this._bufferedEvents.push(args); +}; - if (fns.length === 0) { - throw new TypeError('app.use() requires a middleware function') +DelayedStream.prototype._checkIfMaxDataSizeExceeded = function() { + if (this._maxDataSizeExceeded) { + return; } - // setup router - this.lazyrouter(); - var router = this._router; + if (this.dataSize <= this.maxDataSize) { + return; + } - fns.forEach(function (fn) { - // non-express app - if (!fn || !fn.handle || !fn.set) { - return router.use(path, fn); - } + this._maxDataSizeExceeded = true; + var message = + 'DelayedStream#maxDataSize of ' + this.maxDataSize + ' bytes exceeded.' + this.emit('error', new Error(message)); +}; - debug('.use app under %s', path); - fn.mountpath = path; - fn.parent = this; - // restore .app property on req and res - router.use(path, function mounted_app(req, res, next) { - var orig = req.app; - fn.handle(req, res, function (err) { - setPrototypeOf(req, orig.request) - setPrototypeOf(res, orig.response) - next(err); - }); - }); +/***/ }), - // mounted an app - fn.emit('mount', this); - }, this); +/***/ 42342: +/***/ ((module) => { + +"use strict"; - return this; -}; /** - * Proxy to the app `Router#route()` - * Returns a new `Route` instance for the _path_. - * - * Routes are isolated middleware stacks for specific paths. - * See the Route api docs for details. - * - * @public + * Custom implementation of a double ended queue. */ +function Denque(array, options) { + var options = options || {}; -app.route = function route(path) { - this.lazyrouter(); - return this._router.route(path); -}; + this._head = 0; + this._tail = 0; + this._capacity = options.capacity; + this._capacityMask = 0x3; + this._list = new Array(4); + if (Array.isArray(array)) { + this._fromArray(array); + } +} /** - * Register the given template engine callback `fn` - * as `ext`. - * - * By default will `require()` the engine based on the - * file extension. For example if you try to render - * a "foo.ejs" file Express will invoke the following internally: - * - * app.engine('ejs', require('ejs').__express); - * - * For engines that do not provide `.__express` out of the box, - * or if you wish to "map" a different extension to the template engine - * you may use this method. For example mapping the EJS template engine to - * ".html" files: - * - * app.engine('html', require('ejs').renderFile); - * - * In this case EJS provides a `.renderFile()` method with - * the same signature that Express expects: `(path, options, callback)`, - * though note that it aliases this method as `ejs.__express` internally - * so if you're using ".ejs" extensions you dont need to do anything. - * - * Some template engines do not follow this convention, the - * [Consolidate.js](https://github.com/tj/consolidate.js) - * library was created to map all of node's popular template - * engines to follow this convention, thus allowing them to - * work seamlessly within Express. - * - * @param {String} ext - * @param {Function} fn - * @return {app} for chaining - * @public + * ------------- + * PUBLIC API + * ------------- */ -app.engine = function engine(ext, fn) { - if (typeof fn !== 'function') { - throw new Error('callback function required'); +/** + * Returns the item at the specified index from the list. + * 0 is the first element, 1 is the second, and so on... + * Elements at negative values are that many from the end: -1 is one before the end + * (the last element), -2 is two before the end (one before last), etc. + * @param index + * @returns {*} + */ +Denque.prototype.peekAt = function peekAt(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; } + var len = this.size(); + if (i >= len || i < -len) return undefined; + if (i < 0) i += len; + i = (this._head + i) & this._capacityMask; + return this._list[i]; +}; - // get file extension - var extension = ext[0] !== '.' - ? '.' + ext - : ext; - - // store engine - this.engines[extension] = fn; - - return this; +/** + * Alias for peekAt() + * @param i + * @returns {*} + */ +Denque.prototype.get = function get(i) { + return this.peekAt(i); }; /** - * Proxy to `Router#param()` with one added api feature. The _name_ parameter - * can be an array of names. - * - * See the Router#param() docs for more details. - * - * @param {String|Array} name - * @param {Function} fn - * @return {app} for chaining - * @public + * Returns the first item in the list without removing it. + * @returns {*} */ +Denque.prototype.peek = function peek() { + if (this._head === this._tail) return undefined; + return this._list[this._head]; +}; -app.param = function param(name, fn) { - this.lazyrouter(); +/** + * Alias for peek() + * @returns {*} + */ +Denque.prototype.peekFront = function peekFront() { + return this.peek(); +}; - if (Array.isArray(name)) { - for (var i = 0; i < name.length; i++) { - this.param(name[i], fn); - } +/** + * Returns the item that is at the back of the queue without removing it. + * Uses peekAt(-1) + */ +Denque.prototype.peekBack = function peekBack() { + return this.peekAt(-1); +}; - return this; +/** + * Returns the current length of the queue + * @return {Number} + */ +Object.defineProperty(Denque.prototype, 'length', { + get: function length() { + return this.size(); } +}); - this._router.param(name, fn); +/** + * Return the number of items on the list, or 0 if empty. + * @returns {number} + */ +Denque.prototype.size = function size() { + if (this._head === this._tail) return 0; + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; - return this; +/** + * Add an item at the beginning of the list. + * @param item + */ +Denque.prototype.unshift = function unshift(item) { + if (item === undefined) return this.size(); + var len = this._list.length; + this._head = (this._head - 1 + len) & this._capacityMask; + this._list[this._head] = item; + if (this._tail === this._head) this._growArray(); + if (this._capacity && this.size() > this._capacity) this.pop(); + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); }; /** - * Assign `setting` to `val`, or return `setting`'s value. - * - * app.set('foo', 'bar'); - * app.set('foo'); - * // => "bar" - * - * Mounted servers inherit their parent server's settings. - * - * @param {String} setting - * @param {*} [val] - * @return {Server} for chaining - * @public + * Remove and return the first item on the list, + * Returns undefined if the list is empty. + * @returns {*} */ +Denque.prototype.shift = function shift() { + var head = this._head; + if (head === this._tail) return undefined; + var item = this._list[head]; + this._list[head] = undefined; + this._head = (head + 1) & this._capacityMask; + if (head < 2 && this._tail > 10000 && this._tail <= this._list.length >>> 2) this._shrinkArray(); + return item; +}; -app.set = function set(setting, val) { - if (arguments.length === 1) { - // app.get(setting) - return this.settings[setting]; +/** + * Add an item to the bottom of the list. + * @param item + */ +Denque.prototype.push = function push(item) { + if (item === undefined) return this.size(); + var tail = this._tail; + this._list[tail] = item; + this._tail = (tail + 1) & this._capacityMask; + if (this._tail === this._head) { + this._growArray(); } - - debug('set "%s" to %o', setting, val); - - // set value - this.settings[setting] = val; - - // trigger matched settings - switch (setting) { - case 'etag': - this.set('etag fn', compileETag(val)); - break; - case 'query parser': - this.set('query parser fn', compileQueryParser(val)); - break; - case 'trust proxy': - this.set('trust proxy fn', compileTrust(val)); - - // trust proxy inherit back-compat - Object.defineProperty(this.settings, trustProxyDefaultSymbol, { - configurable: true, - value: false - }); - - break; + if (this._capacity && this.size() > this._capacity) { + this.shift(); } + if (this._head < this._tail) return this._tail - this._head; + else return this._capacityMask + 1 - (this._head - this._tail); +}; - return this; +/** + * Remove and return the last item on the list. + * Returns undefined if the list is empty. + * @returns {*} + */ +Denque.prototype.pop = function pop() { + var tail = this._tail; + if (tail === this._head) return undefined; + var len = this._list.length; + this._tail = (tail - 1 + len) & this._capacityMask; + var item = this._list[this._tail]; + this._list[this._tail] = undefined; + if (this._head < 2 && tail > 10000 && tail <= len >>> 2) this._shrinkArray(); + return item; }; /** - * Return the app's absolute pathname - * based on the parent(s) that have - * mounted it. - * - * For example if the application was - * mounted as "/admin", which itself - * was mounted as "/blog" then the - * return value would be "/blog/admin". - * - * @return {String} - * @private + * Remove and return the item at the specified index from the list. + * Returns undefined if the list is empty. + * @param index + * @returns {*} */ +Denque.prototype.removeOne = function removeOne(index) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size) return void 0; + if (i < 0) i += size; + i = (this._head + i) & this._capacityMask; + var item = this._list[i]; + var k; + if (index < size / 2) { + for (k = index; k > 0; k--) { + this._list[i] = this._list[i = (i - 1 + len) & this._capacityMask]; + } + this._list[i] = void 0; + this._head = (this._head + 1 + len) & this._capacityMask; + } else { + for (k = size - 1 - index; k > 0; k--) { + this._list[i] = this._list[i = ( i + 1 + len) & this._capacityMask]; + } + this._list[i] = void 0; + this._tail = (this._tail - 1 + len) & this._capacityMask; + } + return item; +}; -app.path = function path() { - return this.parent - ? this.parent.path() + this.mountpath - : ''; +/** + * Remove number of items from the specified index from the list. + * Returns array of removed items. + * Returns undefined if the list is empty. + * @param index + * @param count + * @returns {array} + */ +Denque.prototype.remove = function remove(index, count) { + var i = index; + var removed; + var del_count = count; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + if (this._head === this._tail) return void 0; + var size = this.size(); + var len = this._list.length; + if (i >= size || i < -size || count < 1) return void 0; + if (i < 0) i += size; + if (count === 1 || !count) { + removed = new Array(1); + removed[0] = this.removeOne(i); + return removed; + } + if (i === 0 && i + count >= size) { + removed = this.toArray(); + this.clear(); + return removed; + } + if (i + count > size) count = size - i; + var k; + removed = new Array(count); + for (k = 0; k < count; k++) { + removed[k] = this._list[(this._head + i + k) & this._capacityMask]; + } + i = (this._head + i) & this._capacityMask; + if (index + count === size) { + this._tail = (this._tail - count + len) & this._capacityMask; + for (k = count; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + } + return removed; + } + if (index === 0) { + this._head = (this._head + count + len) & this._capacityMask; + for (k = count - 1; k > 0; k--) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + } + return removed; + } + if (i < size / 2) { + this._head = (this._head + index + count + len) & this._capacityMask; + for (k = index; k > 0; k--) { + this.unshift(this._list[i = (i - 1 + len) & this._capacityMask]); + } + i = (this._head - 1 + len) & this._capacityMask; + while (del_count > 0) { + this._list[i = (i - 1 + len) & this._capacityMask] = void 0; + del_count--; + } + if (index < 0) this._tail = i; + } else { + this._tail = i; + i = (i + count + len) & this._capacityMask; + for (k = size - (count + index); k > 0; k--) { + this.push(this._list[i++]); + } + i = this._tail; + while (del_count > 0) { + this._list[i = (i + 1 + len) & this._capacityMask] = void 0; + del_count--; + } + } + if (this._head < 2 && this._tail > 10000 && this._tail <= len >>> 2) this._shrinkArray(); + return removed; }; /** - * Check if `setting` is enabled (truthy). - * - * app.enabled('foo') - * // => false - * - * app.enable('foo') - * app.enabled('foo') - * // => true + * Native splice implementation. + * Remove number of items from the specified index from the list and/or add new elements. + * Returns array of removed items or empty array if count == 0. + * Returns undefined if the list is empty. * - * @param {String} setting - * @return {Boolean} - * @public + * @param index + * @param count + * @param {...*} [elements] + * @returns {array} */ - -app.enabled = function enabled(setting) { - return Boolean(this.set(setting)); +Denque.prototype.splice = function splice(index, count) { + var i = index; + // expect a number or return undefined + if ((i !== (i | 0))) { + return void 0; + } + var size = this.size(); + if (i < 0) i += size; + if (i > size) return void 0; + if (arguments.length > 2) { + var k; + var temp; + var removed; + var arg_len = arguments.length; + var len = this._list.length; + var arguments_index = 2; + if (!size || i < size / 2) { + temp = new Array(i); + for (k = 0; k < i; k++) { + temp[k] = this._list[(this._head + k) & this._capacityMask]; + } + if (count === 0) { + removed = []; + if (i > 0) { + this._head = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._head = (this._head + i + len) & this._capacityMask; + } + while (arg_len > arguments_index) { + this.unshift(arguments[--arg_len]); + } + for (k = i; k > 0; k--) { + this.unshift(temp[k - 1]); + } + } else { + temp = new Array(size - (i + count)); + var leng = temp.length; + for (k = 0; k < leng; k++) { + temp[k] = this._list[(this._head + i + count + k) & this._capacityMask]; + } + if (count === 0) { + removed = []; + if (i != size) { + this._tail = (this._head + i + len) & this._capacityMask; + } + } else { + removed = this.remove(i, count); + this._tail = (this._tail - leng + len) & this._capacityMask; + } + while (arguments_index < arg_len) { + this.push(arguments[arguments_index++]); + } + for (k = 0; k < leng; k++) { + this.push(temp[k]); + } + } + return removed; + } else { + return this.remove(i, count); + } }; /** - * Check if `setting` is disabled. - * - * app.disabled('foo') - * // => true - * - * app.enable('foo') - * app.disabled('foo') - * // => false - * - * @param {String} setting - * @return {Boolean} - * @public + * Soft clear - does not reset capacity. */ - -app.disabled = function disabled(setting) { - return !this.set(setting); +Denque.prototype.clear = function clear() { + this._head = 0; + this._tail = 0; }; /** - * Enable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @public + * Returns true or false whether the list is empty. + * @returns {boolean} */ - -app.enable = function enable(setting) { - return this.set(setting, true); +Denque.prototype.isEmpty = function isEmpty() { + return this._head === this._tail; }; /** - * Disable `setting`. - * - * @param {String} setting - * @return {app} for chaining - * @public + * Returns an array of all queue items. + * @returns {Array} */ - -app.disable = function disable(setting) { - return this.set(setting, false); +Denque.prototype.toArray = function toArray() { + return this._copyArray(false); }; /** - * Delegate `.VERB(...)` calls to `router.VERB(...)`. + * ------------- + * INTERNALS + * ------------- */ -methods.forEach(function(method){ - app[method] = function(path){ - if (method === 'get' && arguments.length === 1) { - // app.get(setting) - return this.set(path); - } - - this.lazyrouter(); - - var route = this._router.route(path); - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; -}); - /** - * Special-cased "all" method, applying the given route `path`, - * middleware, and callback to _every_ HTTP method. - * - * @param {String} path - * @param {Function} ... - * @return {app} for chaining - * @public + * Fills the queue with items from an array + * For use in the constructor + * @param array + * @private */ - -app.all = function all(path) { - this.lazyrouter(); - - var route = this._router.route(path); - var args = slice.call(arguments, 1); - - for (var i = 0; i < methods.length; i++) { - route[methods[i]].apply(route, args); - } - - return this; +Denque.prototype._fromArray = function _fromArray(array) { + for (var i = 0; i < array.length; i++) this.push(array[i]); }; -// del -> delete alias - -app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); - /** - * Render the given view `name` name with `options` - * and a callback accepting an error and the - * rendered template string. - * - * Example: * - * app.render('email', { name: 'Tobi' }, function(err, html){ - * // ... - * }) - * - * @param {String} name - * @param {Object|Function} options or fn - * @param {Function} callback - * @public + * @param fullCopy + * @returns {Array} + * @private */ - -app.render = function render(name, options, callback) { - var cache = this.cache; - var done = callback; - var engines = this.engines; - var opts = options; - var renderOptions = {}; - var view; - - // support callback function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } - - // merge app.locals - merge(renderOptions, this.locals); - - // merge options._locals - if (opts._locals) { - merge(renderOptions, opts._locals); - } - - // merge options - merge(renderOptions, opts); - - // set .cache unless explicitly provided - if (renderOptions.cache == null) { - renderOptions.cache = this.enabled('view cache'); - } - - // primed cache - if (renderOptions.cache) { - view = cache[name]; - } - - // view - if (!view) { - var View = this.get('view'); - - view = new View(name, { - defaultEngine: this.get('view engine'), - root: this.get('views'), - engines: engines - }); - - if (!view.path) { - var dirs = Array.isArray(view.root) && view.root.length > 1 - ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' - : 'directory "' + view.root + '"' - var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); - err.view = view; - return done(err); - } - - // prime the cache - if (renderOptions.cache) { - cache[name] = view; - } +Denque.prototype._copyArray = function _copyArray(fullCopy) { + var newArray = []; + var list = this._list; + var len = list.length; + var i; + if (fullCopy || this._head > this._tail) { + for (i = this._head; i < len; i++) newArray.push(list[i]); + for (i = 0; i < this._tail; i++) newArray.push(list[i]); + } else { + for (i = this._head; i < this._tail; i++) newArray.push(list[i]); } - - // render - tryRender(view, renderOptions, done); + return newArray; }; /** - * Listen for connections. - * - * A node `http.Server` is returned, with this - * application (which is a `Function`) as its - * callback. If you wish to create both an HTTP - * and HTTPS server you may do so with the "http" - * and "https" modules as shown here: - * - * var http = require('http') - * , https = require('https') - * , express = require('express') - * , app = express(); - * - * http.createServer(app).listen(80); - * https.createServer({ ... }, app).listen(443); - * - * @return {http.Server} - * @public + * Grows the internal list array. + * @private */ +Denque.prototype._growArray = function _growArray() { + if (this._head) { + // copy existing data, head to end, then beginning to tail. + this._list = this._copyArray(true); + this._head = 0; + } -app.listen = function listen() { - var server = http.createServer(this); - return server.listen.apply(server, arguments); + // head is at 0 and array is now full, safe to extend + this._tail = this._list.length; + + this._list.length <<= 1; + this._capacityMask = (this._capacityMask << 1) | 1; }; /** - * Log error using console.error. - * - * @param {Error} err + * Shrinks the internal list array. * @private */ +Denque.prototype._shrinkArray = function _shrinkArray() { + this._list.length >>>= 1; + this._capacityMask >>>= 1; +}; -function logerror(err) { - /* istanbul ignore next */ - if (this.get('env') !== 'test') console.error(err.stack || err.toString()); -} - -/** - * Try rendering a view. - * @private - */ -function tryRender(view, options, callback) { - try { - view.render(options, callback); - } catch (err) { - callback(err); - } -} +module.exports = Denque; /***/ }), -/***/ 22587: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 18883: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; /*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson + * depd + * Copyright(c) 2014-2017 Douglas Christopher Wilson * MIT Licensed */ - - /** * Module dependencies. */ -var bodyParser = __nccwpck_require__(97076) -var EventEmitter = __nccwpck_require__(28614).EventEmitter; -var mixin = __nccwpck_require__(11149); -var proto = __nccwpck_require__(313); -var Route = __nccwpck_require__(23699); -var Router = __nccwpck_require__(24963); -var req = __nccwpck_require__(71260); -var res = __nccwpck_require__(64934); +var callSiteToString = __nccwpck_require__(69829).callSiteToString +var eventListenerCount = __nccwpck_require__(69829).eventListenerCount +var relative = __nccwpck_require__(85622).relative /** - * Expose `createApplication()`. + * Module exports. */ -exports = module.exports = createApplication; +module.exports = depd /** - * Create an express application. - * - * @return {Function} - * @api public + * Get the path to base files on. */ -function createApplication() { - var app = function(req, res, next) { - app.handle(req, res, next); - }; +var basePath = process.cwd() - mixin(app, EventEmitter.prototype, false); - mixin(app, proto, false); +/** + * Determine if namespace is contained in the string. + */ - // expose the prototype that will get set on requests - app.request = Object.create(req, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) +function containsNamespace (str, namespace) { + var vals = str.split(/[ ,]+/) + var ns = String(namespace).toLowerCase() - // expose the prototype that will get set on responses - app.response = Object.create(res, { - app: { configurable: true, enumerable: true, writable: true, value: app } - }) + for (var i = 0; i < vals.length; i++) { + var val = vals[i] - app.init(); - return app; + // namespace contained + if (val && (val === '*' || val.toLowerCase() === ns)) { + return true + } + } + + return false } /** - * Expose the prototypes. + * Convert a data descriptor to accessor descriptor. */ -exports.application = proto; -exports.request = req; -exports.response = res; +function convertDataDescriptorToAccessor (obj, prop, message) { + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) + var value = descriptor.value + + descriptor.get = function getter () { return value } + + if (descriptor.writable) { + descriptor.set = function setter (val) { return (value = val) } + } + + delete descriptor.value + delete descriptor.writable + + Object.defineProperty(obj, prop, descriptor) + + return descriptor +} /** - * Expose constructors. + * Create arguments string to keep arity. */ -exports.Route = Route; -exports.Router = Router; +function createArgumentsString (arity) { + var str = '' + + for (var i = 0; i < arity; i++) { + str += ', arg' + i + } + + return str.substr(2) +} /** - * Expose middleware + * Create stack string from stack. */ -exports.json = bodyParser.json -exports.query = __nccwpck_require__(79768); -exports.raw = bodyParser.raw -exports.static = __nccwpck_require__(13146); -exports.text = bodyParser.text -exports.urlencoded = bodyParser.urlencoded +function createStackString (stack) { + var str = this.name + ': ' + this.namespace + + if (this.message) { + str += ' deprecated ' + this.message + } + + for (var i = 0; i < stack.length; i++) { + str += '\n at ' + callSiteToString(stack[i]) + } + + return str +} /** - * Replace removed middleware with an appropriate error message. + * Create deprecate for namespace in caller. */ -var removedMiddlewares = [ - 'bodyParser', - 'compress', - 'cookieSession', - 'session', - 'logger', - 'cookieParser', - 'favicon', - 'responseTime', - 'errorHandler', - 'timeout', - 'methodOverride', - 'vhost', - 'csrf', - 'directory', - 'limit', - 'multipart', - 'staticCache' -] +function depd (namespace) { + if (!namespace) { + throw new TypeError('argument namespace is required') + } -removedMiddlewares.forEach(function (name) { - Object.defineProperty(exports, name, { - get: function () { - throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); - }, - configurable: true - }); -}); + var stack = getStack() + var site = callSiteLocation(stack[1]) + var file = site[0] + function deprecate (message) { + // call to self as log + log.call(deprecate, message) + } -/***/ }), + deprecate._file = file + deprecate._ignored = isignored(namespace) + deprecate._namespace = namespace + deprecate._traced = istraced(namespace) + deprecate._warned = Object.create(null) -/***/ 92636: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + deprecate.function = wrapfunction + deprecate.property = wrapproperty -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed + return deprecate +} + +/** + * Determine if namespace is ignored. */ +function isignored (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.noDeprecation) { + // --no-deprecation support + return true + } + + var str = process.env.NO_DEPRECATION || '' + // namespace ignored + return containsNamespace(str, namespace) +} /** - * Module dependencies. - * @private + * Determine if namespace is traced. */ -var setPrototypeOf = __nccwpck_require__(40414) +function istraced (namespace) { + /* istanbul ignore next: tested in a child processs */ + if (process.traceDeprecation) { + // --trace-deprecation support + return true + } + + var str = process.env.TRACE_DEPRECATION || '' + + // namespace traced + return containsNamespace(str, namespace) +} /** - * Initialization middleware, exposing the - * request and response to each other, as well - * as defaulting the X-Powered-By header field. - * - * @param {Function} app - * @return {Function} - * @api private + * Display deprecation message. */ -exports.init = function(app){ - return function expressInit(req, res, next){ - if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); - req.res = res; - res.req = req; - req.next = next; +function log (message, site) { + var haslisteners = eventListenerCount(process, 'deprecation') !== 0 - setPrototypeOf(req, app.request) - setPrototypeOf(res, app.response) + // abort early if no destination + if (!haslisteners && this._ignored) { + return + } + + var caller + var callFile + var callSite + var depSite + var i = 0 + var seen = false + var stack = getStack() + var file = this._file + + if (site) { + // provided site + depSite = site + callSite = callSiteLocation(stack[1]) + callSite.name = depSite.name + file = callSite[0] + } else { + // get call site + i = 2 + depSite = callSiteLocation(stack[i]) + callSite = depSite + } + + // get caller of deprecated thing in relation to file + for (; i < stack.length; i++) { + caller = callSiteLocation(stack[i]) + callFile = caller[0] + + if (callFile === file) { + seen = true + } else if (callFile === this._file) { + file = this._file + } else if (seen) { + break + } + } - res.locals = res.locals || Object.create(null); + var key = caller + ? depSite.join(':') + '__' + caller.join(':') + : undefined - next(); - }; -}; + if (key !== undefined && key in this._warned) { + // already warned + return + } + this._warned[key] = true + // generate automatic message from call site + var msg = message + if (!msg) { + msg = callSite === depSite || !callSite.name + ? defaultMessage(depSite) + : defaultMessage(callSite) + } -/***/ }), + // emit deprecation if listeners exist + if (haslisteners) { + var err = DeprecationError(this._namespace, msg, stack.slice(i)) + process.emit('deprecation', err) + return + } -/***/ 79768: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // format and write message + var format = process.stderr.isTTY + ? formatColor + : formatPlain + var output = format.call(this, msg, caller, stack.slice(i)) + process.stderr.write(output + '\n', 'utf8') +} -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed +/** + * Get call site location as array. */ +function callSiteLocation (callSite) { + var file = callSite.getFileName() || '' + var line = callSite.getLineNumber() + var colm = callSite.getColumnNumber() + + if (callSite.isEval()) { + file = callSite.getEvalOrigin() + ', ' + file + } + var site = [file, line, colm] -/** - * Module dependencies. - */ + site.callSite = callSite + site.name = callSite.getFunctionName() -var merge = __nccwpck_require__(44429) -var parseUrl = __nccwpck_require__(89808); -var qs = __nccwpck_require__(22760); + return site +} /** - * @param {Object} options - * @return {Function} - * @api public + * Generate a default message from the site. */ -module.exports = function query(options) { - var opts = merge({}, options) - var queryparse = qs.parse; +function defaultMessage (site) { + var callSite = site.callSite + var funcName = site.name - if (typeof options === 'function') { - queryparse = options; - opts = undefined; + // make useful anonymous name + if (!funcName) { + funcName = '' } - if (opts !== undefined && opts.allowPrototypes === undefined) { - // back-compat for qs module - opts.allowPrototypes = true; + var context = callSite.getThis() + var typeName = context && callSite.getTypeName() + + // ignore useless type name + if (typeName === 'Object') { + typeName = undefined } - return function query(req, res, next){ - if (!req.query) { - var val = parseUrl(req).query; - req.query = queryparse(val, opts); - } + // make useful type name + if (typeName === 'Function') { + typeName = context.name || typeName + } - next(); - }; -}; + return typeName && callSite.getMethodName() + ? typeName + '.' + funcName + : funcName +} +/** + * Format deprecation message without color. + */ -/***/ }), +function formatPlain (msg, caller, stack) { + var timestamp = new Date().toUTCString() -/***/ 71260: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var formatted = timestamp + + ' ' + this._namespace + + ' deprecated ' + msg -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n at ' + callSiteToString(stack[i]) + } + + return formatted + } + if (caller) { + formatted += ' at ' + formatLocation(caller) + } + return formatted +} /** - * Module dependencies. - * @private + * Format deprecation message with color. */ -var accepts = __nccwpck_require__(83633); -var deprecate = __nccwpck_require__(18883)('express'); -var isIP = __nccwpck_require__(11631).isIP; -var typeis = __nccwpck_require__(71159); -var http = __nccwpck_require__(98605); -var fresh = __nccwpck_require__(83136); -var parseRange = __nccwpck_require__(26435); -var parse = __nccwpck_require__(89808); -var proxyaddr = __nccwpck_require__(80140); +function formatColor (msg, caller, stack) { + var formatted = '\x1b[36;1m' + this._namespace + '\x1b[22;39m' + // bold cyan + ' \x1b[33;1mdeprecated\x1b[22;39m' + // bold yellow + ' \x1b[0m' + msg + '\x1b[39m' // reset -/** - * Request prototype. - * @public - */ + // add stack trace + if (this._traced) { + for (var i = 0; i < stack.length; i++) { + formatted += '\n \x1b[36mat ' + callSiteToString(stack[i]) + '\x1b[39m' // cyan + } -var req = Object.create(http.IncomingMessage.prototype) + return formatted + } + + if (caller) { + formatted += ' \x1b[36m' + formatLocation(caller) + '\x1b[39m' // cyan + } + + return formatted +} /** - * Module exports. - * @public + * Format call site location. */ -module.exports = req +function formatLocation (callSite) { + return relative(basePath, callSite[0]) + + ':' + callSite[1] + + ':' + callSite[2] +} /** - * Return request header. - * - * The `Referrer` header field is special-cased, - * both `Referrer` and `Referer` are interchangeable. - * - * Examples: - * - * req.get('Content-Type'); - * // => "text/plain" - * - * req.get('content-type'); - * // => "text/plain" - * - * req.get('Something'); - * // => undefined - * - * Aliased as `req.header()`. - * - * @param {String} name - * @return {String} - * @public + * Get the stack as array of call sites. */ -req.get = -req.header = function header(name) { - if (!name) { - throw new TypeError('name argument is required to req.get'); - } +function getStack () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace - if (typeof name !== 'string') { - throw new TypeError('name must be a string to req.get'); - } + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = Math.max(10, limit) - var lc = name.toLowerCase(); + // capture the stack + Error.captureStackTrace(obj) - switch (lc) { - case 'referer': - case 'referrer': - return this.headers.referrer - || this.headers.referer; - default: - return this.headers[lc]; - } -}; + // slice this function off the top + var stack = obj.stack.slice(1) -/** - * To do: update docs. - * - * Check if the given `type(s)` is acceptable, returning - * the best match when true, otherwise `undefined`, in which - * case you should respond with 406 "Not Acceptable". - * - * The `type` value may be a single MIME type string - * such as "application/json", an extension name - * such as "json", a comma-delimited list such as "json, html, text/plain", - * an argument list such as `"json", "html", "text/plain"`, - * or an array `["json", "html", "text/plain"]`. When a list - * or array is given, the _best_ match, if any is returned. - * - * Examples: - * - * // Accept: text/html - * req.accepts('html'); - * // => "html" - * - * // Accept: text/*, application/json - * req.accepts('html'); - * // => "html" - * req.accepts('text/html'); - * // => "text/html" - * req.accepts('json, text'); - * // => "json" - * req.accepts('application/json'); - * // => "application/json" - * - * // Accept: text/*, application/json - * req.accepts('image/png'); - * req.accepts('png'); - * // => undefined - * - * // Accept: text/*;q=.5, application/json - * req.accepts(['html', 'json']); - * req.accepts('html', 'json'); - * req.accepts('html, json'); - * // => "json" - * - * @param {String|Array} type(s) - * @return {String|Array|Boolean} - * @public - */ + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit -req.accepts = function(){ - var accept = accepts(this); - return accept.types.apply(accept, arguments); -}; + return stack +} /** - * Check if the given `encoding`s are accepted. - * - * @param {String} ...encoding - * @return {String|Array} - * @public + * Capture call site stack from v8. */ -req.acceptsEncodings = function(){ - var accept = accepts(this); - return accept.encodings.apply(accept, arguments); -}; - -req.acceptsEncoding = deprecate.function(req.acceptsEncodings, - 'req.acceptsEncoding: Use acceptsEncodings instead'); +function prepareObjectStackTrace (obj, stack) { + return stack +} /** - * Check if the given `charset`s are acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} ...charset - * @return {String|Array} - * @public + * Return a wrapped function in a deprecation message. */ -req.acceptsCharsets = function(){ - var accept = accepts(this); - return accept.charsets.apply(accept, arguments); -}; +function wrapfunction (fn, message) { + if (typeof fn !== 'function') { + throw new TypeError('argument fn must be a function') + } -req.acceptsCharset = deprecate.function(req.acceptsCharsets, - 'req.acceptsCharset: Use acceptsCharsets instead'); + var args = createArgumentsString(fn.length) + var deprecate = this // eslint-disable-line no-unused-vars + var stack = getStack() + var site = callSiteLocation(stack[1]) -/** - * Check if the given `lang`s are acceptable, - * otherwise you should respond with 406 "Not Acceptable". - * - * @param {String} ...lang - * @return {String|Array} - * @public - */ + site.name = fn.name -req.acceptsLanguages = function(){ - var accept = accepts(this); - return accept.languages.apply(accept, arguments); -}; + // eslint-disable-next-line no-eval + var deprecatedfn = eval('(function (' + args + ') {\n' + + '"use strict"\n' + + 'log.call(deprecate, message, site)\n' + + 'return fn.apply(this, arguments)\n' + + '})') -req.acceptsLanguage = deprecate.function(req.acceptsLanguages, - 'req.acceptsLanguage: Use acceptsLanguages instead'); + return deprecatedfn +} /** - * Parse Range header field, capping to the given `size`. - * - * Unspecified ranges such as "0-" require knowledge of your resource length. In - * the case of a byte range this is of course the total number of bytes. If the - * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, - * and `-2` when syntactically invalid. - * - * When ranges are returned, the array has a "type" property which is the type of - * range that is required (most commonly, "bytes"). Each array element is an object - * with a "start" and "end" property for the portion of the range. - * - * The "combine" option can be set to `true` and overlapping & adjacent ranges - * will be combined into a single range. - * - * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" - * should respond with 4 users when available, not 3. - * - * @param {number} size - * @param {object} [options] - * @param {boolean} [options.combine=false] - * @return {number|array} - * @public + * Wrap property in a deprecation message. */ -req.range = function range(size, options) { - var range = this.get('Range'); - if (!range) return; - return parseRange(size, range, options); -}; +function wrapproperty (obj, prop, message) { + if (!obj || (typeof obj !== 'object' && typeof obj !== 'function')) { + throw new TypeError('argument obj must be object') + } -/** - * Return the value of param `name` when present or `defaultValue`. - * - * - Checks route placeholders, ex: _/user/:id_ - * - Checks body params, ex: id=12, {"id":12} - * - Checks query string params, ex: ?id=12 - * - * To utilize request bodies, `req.body` - * should be an object. This can be done by using - * the `bodyParser()` middleware. - * - * @param {String} name - * @param {Mixed} [defaultValue] - * @return {String} - * @public - */ + var descriptor = Object.getOwnPropertyDescriptor(obj, prop) -req.param = function param(name, defaultValue) { - var params = this.params || {}; - var body = this.body || {}; - var query = this.query || {}; + if (!descriptor) { + throw new TypeError('must call property on owner object') + } - var args = arguments.length === 1 - ? 'name' - : 'name, default'; - deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); + if (!descriptor.configurable) { + throw new TypeError('property must be configurable') + } - if (null != params[name] && params.hasOwnProperty(name)) return params[name]; - if (null != body[name]) return body[name]; - if (null != query[name]) return query[name]; + var deprecate = this + var stack = getStack() + var site = callSiteLocation(stack[1]) - return defaultValue; -}; + // set site name + site.name = prop -/** - * Check if the incoming request contains the "Content-Type" - * header field, and it contains the give mime `type`. - * - * Examples: - * - * // With Content-Type: text/html; charset=utf-8 - * req.is('html'); - * req.is('text/html'); - * req.is('text/*'); - * // => true - * - * // When Content-Type is application/json - * req.is('json'); - * req.is('application/json'); - * req.is('application/*'); - * // => true - * - * req.is('html'); - * // => false - * - * @param {String|Array} types... - * @return {String|false|null} - * @public - */ + // convert data descriptor + if ('value' in descriptor) { + descriptor = convertDataDescriptorToAccessor(obj, prop, message) + } -req.is = function is(types) { - var arr = types; + var get = descriptor.get + var set = descriptor.set - // support flattened arguments - if (!Array.isArray(types)) { - arr = new Array(arguments.length); - for (var i = 0; i < arr.length; i++) { - arr[i] = arguments[i]; + // wrap getter + if (typeof get === 'function') { + descriptor.get = function getter () { + log.call(deprecate, message, site) + return get.apply(this, arguments) } } - return typeis(this, arr); -}; + // wrap setter + if (typeof set === 'function') { + descriptor.set = function setter () { + log.call(deprecate, message, site) + return set.apply(this, arguments) + } + } + + Object.defineProperty(obj, prop, descriptor) +} /** - * Return the protocol string "http" or "https" - * when requested with TLS. When the "trust proxy" - * setting trusts the socket address, the - * "X-Forwarded-Proto" header field will be trusted - * and used if present. - * - * If you're running behind a reverse proxy that - * supplies https for you this may be enabled. - * - * @return {String} - * @public + * Create DeprecationError for deprecation */ -defineGetter(req, 'protocol', function protocol(){ - var proto = this.connection.encrypted - ? 'https' - : 'http'; - var trust = this.app.get('trust proxy fn'); +function DeprecationError (namespace, message, stack) { + var error = new Error() + var stackString + + Object.defineProperty(error, 'constructor', { + value: DeprecationError + }) + + Object.defineProperty(error, 'message', { + configurable: true, + enumerable: false, + value: message, + writable: true + }) + + Object.defineProperty(error, 'name', { + enumerable: false, + configurable: true, + value: 'DeprecationError', + writable: true + }) + + Object.defineProperty(error, 'namespace', { + configurable: true, + enumerable: false, + value: namespace, + writable: true + }) + + Object.defineProperty(error, 'stack', { + configurable: true, + enumerable: false, + get: function () { + if (stackString !== undefined) { + return stackString + } - if (!trust(this.connection.remoteAddress, 0)) { - return proto; - } + // prepare stack trace + return (stackString = createStackString.call(this, stack)) + }, + set: function setter (val) { + stackString = val + } + }) - // Note: X-Forwarded-Proto is normally only ever a - // single value, but this is to be safe. - var header = this.get('X-Forwarded-Proto') || proto - var index = header.indexOf(',') + return error +} - return index !== -1 - ? header.substring(0, index).trim() - : header.trim() -}); -/** - * Short-hand for: - * - * req.protocol === 'https' - * - * @return {Boolean} - * @public - */ +/***/ }), -defineGetter(req, 'secure', function secure(){ - return this.protocol === 'https'; -}); +/***/ 35554: +/***/ ((module) => { -/** - * Return the remote address from the trusted proxy. - * - * The is the remote address on the socket unless - * "trust proxy" is set. - * - * @return {String} - * @public +"use strict"; +/*! + * depd + * Copyright(c) 2014 Douglas Christopher Wilson + * MIT Licensed */ -defineGetter(req, 'ip', function ip(){ - var trust = this.app.get('trust proxy fn'); - return proxyaddr(this, trust); -}); + /** - * When "trust proxy" is set, trusted proxy addresses + client. - * - * For example if the value were "client, proxy1, proxy2" - * you would receive the array `["client", "proxy1", "proxy2"]` - * where "proxy2" is the furthest down-stream and "proxy1" and - * "proxy2" were trusted. - * - * @return {Array} - * @public + * Module exports. */ -defineGetter(req, 'ips', function ips() { - var trust = this.app.get('trust proxy fn'); - var addrs = proxyaddr.all(this, trust); - - // reverse the order (to farthest -> closest) - // and remove socket address - addrs.reverse().pop() - - return addrs -}); +module.exports = callSiteToString /** - * Return subdomains as an array. - * - * Subdomains are the dot-separated parts of the host before the main domain of - * the app. By default, the domain of the app is assumed to be the last two - * parts of the host. This can be changed by setting "subdomain offset". - * - * For example, if the domain is "tobi.ferrets.example.com": - * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. - * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. - * - * @return {Array} - * @public + * Format a CallSite file location to a string. */ -defineGetter(req, 'subdomains', function subdomains() { - var hostname = this.hostname; +function callSiteFileLocation (callSite) { + var fileName + var fileLocation = '' - if (!hostname) return []; + if (callSite.isNative()) { + fileLocation = 'native' + } else if (callSite.isEval()) { + fileName = callSite.getScriptNameOrSourceURL() + if (!fileName) { + fileLocation = callSite.getEvalOrigin() + } + } else { + fileName = callSite.getFileName() + } - var offset = this.app.get('subdomain offset'); - var subdomains = !isIP(hostname) - ? hostname.split('.').reverse() - : [hostname]; + if (fileName) { + fileLocation += fileName - return subdomains.slice(offset); -}); + var lineNumber = callSite.getLineNumber() + if (lineNumber != null) { + fileLocation += ':' + lineNumber -/** - * Short-hand for `url.parse(req.url).pathname`. - * - * @return {String} - * @public - */ + var columnNumber = callSite.getColumnNumber() + if (columnNumber) { + fileLocation += ':' + columnNumber + } + } + } -defineGetter(req, 'path', function path() { - return parse(this).pathname; -}); + return fileLocation || 'unknown source' +} /** - * Parse the "Host" header field to a hostname. - * - * When the "trust proxy" setting trusts the socket - * address, the "X-Forwarded-Host" header field will - * be trusted. - * - * @return {String} - * @public + * Format a CallSite to a string. */ -defineGetter(req, 'hostname', function hostname(){ - var trust = this.app.get('trust proxy fn'); - var host = this.get('X-Forwarded-Host'); +function callSiteToString (callSite) { + var addSuffix = true + var fileLocation = callSiteFileLocation(callSite) + var functionName = callSite.getFunctionName() + var isConstructor = callSite.isConstructor() + var isMethodCall = !(callSite.isToplevel() || isConstructor) + var line = '' - if (!host || !trust(this.connection.remoteAddress, 0)) { - host = this.get('Host'); - } else if (host.indexOf(',') !== -1) { - // Note: X-Forwarded-Host is normally only ever a - // single value, but this is to be safe. - host = host.substring(0, host.indexOf(',')).trimRight() - } + if (isMethodCall) { + var methodName = callSite.getMethodName() + var typeName = getConstructorName(callSite) - if (!host) return; + if (functionName) { + if (typeName && functionName.indexOf(typeName) !== 0) { + line += typeName + '.' + } - // IPv6 literal support - var offset = host[0] === '[' - ? host.indexOf(']') + 1 - : 0; - var index = host.indexOf(':', offset); + line += functionName - return index !== -1 - ? host.substring(0, index) - : host; -}); + if (methodName && functionName.lastIndexOf('.' + methodName) !== functionName.length - methodName.length - 1) { + line += ' [as ' + methodName + ']' + } + } else { + line += typeName + '.' + (methodName || '') + } + } else if (isConstructor) { + line += 'new ' + (functionName || '') + } else if (functionName) { + line += functionName + } else { + addSuffix = false + line += fileLocation + } -// TODO: change req.host to return host in next major + if (addSuffix) { + line += ' (' + fileLocation + ')' + } -defineGetter(req, 'host', deprecate.function(function host(){ - return this.hostname; -}, 'req.host: Use req.hostname instead')); + return line +} /** - * Check if the request is fresh, aka - * Last-Modified and/or the ETag - * still match. - * - * @return {Boolean} - * @public + * Get constructor name of reviver. */ -defineGetter(req, 'fresh', function(){ - var method = this.method; - var res = this.res - var status = res.statusCode +function getConstructorName (obj) { + var receiver = obj.receiver + return (receiver.constructor && receiver.constructor.name) || null +} - // GET or HEAD for weak freshness validation only - if ('GET' !== method && 'HEAD' !== method) return false; - // 2xx or 304 as per rfc2616 14.26 - if ((status >= 200 && status < 300) || 304 === status) { - return fresh(this.headers, { - 'etag': res.get('ETag'), - 'last-modified': res.get('Last-Modified') - }) - } +/***/ }), - return false; -}); +/***/ 12078: +/***/ ((module) => { -/** - * Check if the request is stale, aka - * "Last-Modified" and / or the "ETag" for the - * resource has changed. - * - * @return {Boolean} - * @public +"use strict"; +/*! + * depd + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed */ -defineGetter(req, 'stale', function stale(){ - return !this.fresh; -}); + /** - * Check if the request was an _XMLHttpRequest_. - * - * @return {Boolean} + * Module exports. * @public */ -defineGetter(req, 'xhr', function xhr(){ - var val = this.get('X-Requested-With') || ''; - return val.toLowerCase() === 'xmlhttprequest'; -}); +module.exports = eventListenerCount /** - * Helper function for creating a getter on an object. - * - * @param {Object} obj - * @param {String} name - * @param {Function} getter - * @private + * Get the count of listeners on an event emitter of a specific type. */ -function defineGetter(obj, name, getter) { - Object.defineProperty(obj, name, { - configurable: true, - enumerable: true, - get: getter - }); + +function eventListenerCount (emitter, type) { + return emitter.listeners(type).length } /***/ }), -/***/ 64934: +/***/ 69829: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk + * depd * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ @@ -45161,1999 +48826,1572 @@ function defineGetter(obj, name, getter) { * @private */ -var Buffer = __nccwpck_require__(21867).Buffer -var contentDisposition = __nccwpck_require__(53921); -var deprecate = __nccwpck_require__(18883)('express'); -var encodeUrl = __nccwpck_require__(16592); -var escapeHtml = __nccwpck_require__(94070); -var http = __nccwpck_require__(98605); -var isAbsolute = __nccwpck_require__(53561).isAbsolute; -var onFinished = __nccwpck_require__(92098); -var path = __nccwpck_require__(85622); -var statuses = __nccwpck_require__(57415) -var merge = __nccwpck_require__(44429); -var sign = __nccwpck_require__(61579).sign; -var normalizeType = __nccwpck_require__(53561).normalizeType; -var normalizeTypes = __nccwpck_require__(53561).normalizeTypes; -var setCharset = __nccwpck_require__(53561).setCharset; -var cookie = __nccwpck_require__(93658); -var send = __nccwpck_require__(95287); -var extname = path.extname; -var mime = send.mime; -var resolve = path.resolve; -var vary = __nccwpck_require__(85931); - -/** - * Response prototype. - * @public - */ - -var res = Object.create(http.ServerResponse.prototype) +var EventEmitter = __nccwpck_require__(28614).EventEmitter /** * Module exports. * @public */ -module.exports = res - -/** - * Module variables. - * @private - */ - -var charsetRegExp = /;\s*charset\s*=/; - -/** - * Set status `code`. - * - * @param {Number} code - * @return {ServerResponse} - * @public - */ - -res.status = function status(code) { - this.statusCode = code; - return this; -}; - -/** - * Set Link header field with the given `links`. - * - * Examples: - * - * res.links({ - * next: 'http://api.example.com/users?page=2', - * last: 'http://api.example.com/users?page=5' - * }); - * - * @param {Object} links - * @return {ServerResponse} - * @public - */ - -res.links = function(links){ - var link = this.get('Link') || ''; - if (link) link += ', '; - return this.set('Link', link + Object.keys(links).map(function(rel){ - return '<' + links[rel] + '>; rel="' + rel + '"'; - }).join(', ')); -}; - -/** - * Send a response. - * - * Examples: - * - * res.send(Buffer.from('wahoo')); - * res.send({ some: 'json' }); - * res.send('

some html

'); - * - * @param {string|number|boolean|object|Buffer} body - * @public - */ - -res.send = function send(body) { - var chunk = body; - var encoding; - var req = this.req; - var type; - - // settings - var app = this.app; - - // allow status / body - if (arguments.length === 2) { - // res.send(body, status) backwards compat - if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { - deprecate('res.send(body, status): Use res.status(status).send(body) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.send(status, body): Use res.status(status).send(body) instead'); - this.statusCode = arguments[0]; - chunk = arguments[1]; - } - } - - // disambiguate res.send(status) and res.send(status, num) - if (typeof chunk === 'number' && arguments.length === 1) { - // res.send(status) will set status message as text string - if (!this.get('Content-Type')) { - this.type('txt'); - } +lazyProperty(module.exports, 'callSiteToString', function callSiteToString () { + var limit = Error.stackTraceLimit + var obj = {} + var prep = Error.prepareStackTrace - deprecate('res.send(status): Use res.sendStatus(status) instead'); - this.statusCode = chunk; - chunk = statuses[chunk] + function prepareObjectStackTrace (obj, stack) { + return stack } - switch (typeof chunk) { - // string defaulting to html - case 'string': - if (!this.get('Content-Type')) { - this.type('html'); - } - break; - case 'boolean': - case 'number': - case 'object': - if (chunk === null) { - chunk = ''; - } else if (Buffer.isBuffer(chunk)) { - if (!this.get('Content-Type')) { - this.type('bin'); - } - } else { - return this.json(chunk); - } - break; - } + Error.prepareStackTrace = prepareObjectStackTrace + Error.stackTraceLimit = 2 - // write strings in utf-8 - if (typeof chunk === 'string') { - encoding = 'utf8'; - type = this.get('Content-Type'); + // capture the stack + Error.captureStackTrace(obj) - // reflect this in content-type - if (typeof type === 'string') { - this.set('Content-Type', setCharset(type, 'utf-8')); - } - } + // slice the stack + var stack = obj.stack.slice() - // determine if ETag should be generated - var etagFn = app.get('etag fn') - var generateETag = !this.get('ETag') && typeof etagFn === 'function' + Error.prepareStackTrace = prep + Error.stackTraceLimit = limit - // populate Content-Length - var len - if (chunk !== undefined) { - if (Buffer.isBuffer(chunk)) { - // get length of Buffer - len = chunk.length - } else if (!generateETag && chunk.length < 1000) { - // just calculate length when no ETag + small chunk - len = Buffer.byteLength(chunk, encoding) - } else { - // convert chunk to Buffer and calculate - chunk = Buffer.from(chunk, encoding) - encoding = undefined; - len = chunk.length - } + return stack[0].toString ? toString : __nccwpck_require__(35554) +}) - this.set('Content-Length', len); - } +lazyProperty(module.exports, 'eventListenerCount', function eventListenerCount () { + return EventEmitter.listenerCount || __nccwpck_require__(12078) +}) - // populate ETag - var etag; - if (generateETag && len !== undefined) { - if ((etag = etagFn(chunk, encoding))) { - this.set('ETag', etag); - } - } +/** + * Define a lazy property. + */ - // freshness - if (req.fresh) this.statusCode = 304; +function lazyProperty (obj, prop, getter) { + function get () { + var val = getter() - // strip irrelevant headers - if (204 === this.statusCode || 304 === this.statusCode) { - this.removeHeader('Content-Type'); - this.removeHeader('Content-Length'); - this.removeHeader('Transfer-Encoding'); - chunk = ''; - } + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + value: val + }) - if (req.method === 'HEAD') { - // skip body for HEAD - this.end(); - } else { - // respond - this.end(chunk, encoding); + return val } - return this; -}; + Object.defineProperty(obj, prop, { + configurable: true, + enumerable: true, + get: get + }) +} /** - * Send JSON response. - * - * Examples: - * - * res.json(null); - * res.json({ user: 'tj' }); - * - * @param {string|number|boolean|object} obj - * @public + * Call toString() on the obj */ -res.json = function json(obj) { - var val = obj; +function toString (obj) { + return obj.toString() +} - // allow status / body - if (arguments.length === 2) { - // res.json(body, status) backwards compat - if (typeof arguments[1] === 'number') { - deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[0]; - val = arguments[1]; - } - } - // settings - var app = this.app; - var escape = app.get('json escape') - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = stringify(val, replacer, spaces, escape) +/***/ }), - // content-type - if (!this.get('Content-Type')) { - this.set('Content-Type', 'application/json'); - } +/***/ 58932: +/***/ ((__unused_webpack_module, exports) => { - return this.send(body); -}; +"use strict"; -/** - * Send JSON response with JSONP callback support. - * - * Examples: - * - * res.jsonp(null); - * res.jsonp({ user: 'tj' }); - * - * @param {string|number|boolean|object} obj - * @public - */ -res.jsonp = function jsonp(obj) { - var val = obj; +Object.defineProperty(exports, "__esModule", ({ value: true })); - // allow status / body - if (arguments.length === 2) { - // res.json(body, status) backwards compat - if (typeof arguments[1] === 'number') { - deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead'); - this.statusCode = arguments[1]; - } else { - deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); - this.statusCode = arguments[0]; - val = arguments[1]; +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); } + + this.name = 'Deprecation'; } - // settings - var app = this.app; - var escape = app.get('json escape') - var replacer = app.get('json replacer'); - var spaces = app.get('json spaces'); - var body = stringify(val, replacer, spaces, escape) - var callback = this.req.query[app.get('jsonp callback name')]; +} - // content-type - if (!this.get('Content-Type')) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'application/json'); - } +exports.Deprecation = Deprecation; - // fixup callback - if (Array.isArray(callback)) { - callback = callback[0]; - } - // jsonp - if (typeof callback === 'string' && callback.length !== 0) { - this.set('X-Content-Type-Options', 'nosniff'); - this.set('Content-Type', 'text/javascript'); +/***/ }), - // restrict callback charset - callback = callback.replace(/[^\[\]\w$.]/g, ''); +/***/ 43225: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // replace chars not allowed in JavaScript that are in JSON - body = body - .replace(/\u2028/g, '\\u2028') - .replace(/\u2029/g, '\\u2029'); +"use strict"; +/*! + * destroy + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ - // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" - // the typeof check is just to reduce client error noise - body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; - } - return this.send(body); -}; /** - * Send given HTTP status code. - * - * Sets the response status to `statusCode` and the body of the - * response to the standard description from node's http.STATUS_CODES - * or the statusCode number if no description. - * - * Examples: - * - * res.sendStatus(200); - * - * @param {number} statusCode - * @public + * Module dependencies. + * @private */ -res.sendStatus = function sendStatus(statusCode) { - var body = statuses[statusCode] || String(statusCode) +var ReadStream = __nccwpck_require__(35747).ReadStream +var Stream = __nccwpck_require__(92413) - this.statusCode = statusCode; - this.type('txt'); +/** + * Module exports. + * @public + */ - return this.send(body); -}; +module.exports = destroy /** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `callback(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendFile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendFile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendFile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); + * Destroy a stream. * + * @param {object} stream * @public */ -res.sendFile = function sendFile(path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; - - if (!path) { - throw new TypeError('path argument is required to res.sendFile'); +function destroy(stream) { + if (stream instanceof ReadStream) { + return destroyReadStream(stream) } - if (typeof path !== 'string') { - throw new TypeError('path must be a string to res.sendFile') + if (!(stream instanceof Stream)) { + return stream } - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; + if (typeof stream.destroy === 'function') { + stream.destroy() } - if (!opts.root && !isAbsolute(path)) { - throw new TypeError('path must be absolute or specify root to res.sendFile'); - } + return stream +} - // create file stream - var pathname = encodeURI(path); - var file = send(req, pathname, opts); +/** + * Destroy a ReadStream. + * + * @param {object} stream + * @private + */ - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); +function destroyReadStream(stream) { + stream.destroy() - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); - } - }); -}; + if (typeof stream.close === 'function') { + // node.js core bug work-around + stream.on('open', onOpenClose) + } + + return stream +} /** - * Transfer the file at the given `path`. - * - * Automatically sets the _Content-Type_ response header field. - * The callback `callback(err)` is invoked when the transfer is complete - * or when an error occurs. Be sure to check `res.sentHeader` - * if you wish to attempt responding, as the header and some data - * may have already been transferred. - * - * Options: - * - * - `maxAge` defaulting to 0 (can be string converted by `ms`) - * - `root` root directory for relative filenames - * - `headers` object of headers to serve with file - * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them - * - * Other options are passed along to `send`. - * - * Examples: - * - * The following example illustrates how `res.sendfile()` may - * be used as an alternative for the `static()` middleware for - * dynamic situations. The code backing `res.sendfile()` is actually - * the same code, so HTTP cache support etc is identical. - * - * app.get('/user/:uid/photos/:file', function(req, res){ - * var uid = req.params.uid - * , file = req.params.file; - * - * req.user.mayViewFilesFrom(uid, function(yes){ - * if (yes) { - * res.sendfile('/uploads/' + uid + '/' + file); - * } else { - * res.send(403, 'Sorry! you cant see that.'); - * } - * }); - * }); - * - * @public + * On open handler to close stream. + * @private */ -res.sendfile = function (path, options, callback) { - var done = callback; - var req = this.req; - var res = this; - var next = req.next; - var opts = options || {}; - - // support function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; +function onOpenClose() { + if (typeof this.fd === 'number') { + // actually close down the fd + this.close() } +} - // create file stream - var file = send(req, path, opts); - // transfer - sendfile(res, file, opts, function (err) { - if (done) return done(err); - if (err && err.code === 'EISDIR') return next(); +/***/ }), - // next() all but write errors - if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { - next(err); - } - }); -}; +/***/ 12437: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -res.sendfile = deprecate.function(res.sendfile, - 'res.sendfile: Use res.sendFile instead'); +/* @flow */ +/*:: -/** - * Transfer the file at the given `path` as an attachment. - * - * Optionally providing an alternate attachment `filename`, - * and optional callback `callback(err)`. The callback is invoked - * when the data transfer is complete, or when an error has - * ocurred. Be sure to check `res.headersSent` if you plan to respond. - * - * Optionally providing an `options` object to use with `res.sendFile()`. - * This function will set the `Content-Disposition` header, overriding - * any `Content-Disposition` header passed as header options in order - * to set the attachment and filename. - * - * This method uses `res.sendFile()`. - * - * @public - */ +type DotenvParseOptions = { + debug?: boolean +} -res.download = function download (path, filename, options, callback) { - var done = callback; - var name = filename; - var opts = options || null +// keys and values from src +type DotenvParseOutput = { [string]: string } - // support function as second or third arg - if (typeof filename === 'function') { - done = filename; - name = null; - opts = null - } else if (typeof options === 'function') { - done = options - opts = null - } +type DotenvConfigOptions = { + path?: string, // path to .env file + encoding?: string, // encoding of .env file + debug?: string // turn on logging for debugging purposes +} - // set Content-Disposition when file is sent - var headers = { - 'Content-Disposition': contentDisposition(name || path) - }; +type DotenvConfigOutput = { + parsed?: DotenvParseOutput, + error?: Error +} - // merge user-provided headers - if (opts && opts.headers) { - var keys = Object.keys(opts.headers) - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - if (key.toLowerCase() !== 'content-disposition') { - headers[key] = opts.headers[key] - } - } - } +*/ - // merge user-provided options - opts = Object.create(opts) - opts.headers = headers +const fs = __nccwpck_require__(35747) +const path = __nccwpck_require__(85622) - // Resolve the full path for sendFile - var fullPath = resolve(path); +function log (message /*: string */) { + console.log(`[dotenv][DEBUG] ${message}`) +} - // send file - return this.sendFile(fullPath, opts, done) -}; +const NEWLINE = '\n' +const RE_INI_KEY_VAL = /^\s*([\w.-]+)\s*=\s*(.*)?\s*$/ +const RE_NEWLINES = /\\n/g +const NEWLINES_MATCH = /\n|\r|\r\n/ -/** - * Set _Content-Type_ response header with `type` through `mime.lookup()` - * when it does not contain "/", or set the Content-Type to `type` otherwise. - * - * Examples: - * - * res.type('.html'); - * res.type('html'); - * res.type('json'); - * res.type('application/json'); - * res.type('png'); - * - * @param {String} type - * @return {ServerResponse} for chaining - * @public - */ +// Parses src into an Object +function parse (src /*: string | Buffer */, options /*: ?DotenvParseOptions */) /*: DotenvParseOutput */ { + const debug = Boolean(options && options.debug) + const obj = {} -res.contentType = -res.type = function contentType(type) { - var ct = type.indexOf('/') === -1 - ? mime.lookup(type) - : type; + // convert Buffers before splitting into lines and processing + src.toString().split(NEWLINES_MATCH).forEach(function (line, idx) { + // matching "KEY' and 'VAL' in 'KEY=VAL' + const keyValueArr = line.match(RE_INI_KEY_VAL) + // matched? + if (keyValueArr != null) { + const key = keyValueArr[1] + // default undefined or missing values to empty string + let val = (keyValueArr[2] || '') + const end = val.length - 1 + const isDoubleQuoted = val[0] === '"' && val[end] === '"' + const isSingleQuoted = val[0] === "'" && val[end] === "'" - return this.set('Content-Type', ct); -}; + // if single or double quoted, remove quotes + if (isSingleQuoted || isDoubleQuoted) { + val = val.substring(1, end) -/** - * Respond to the Acceptable formats using an `obj` - * of mime-type callbacks. - * - * This method uses `req.accepted`, an array of - * acceptable types ordered by their quality values. - * When "Accept" is not present the _first_ callback - * is invoked, otherwise the first match is used. When - * no match is performed the server responds with - * 406 "Not Acceptable". - * - * Content-Type is set for you, however if you choose - * you may alter this within the callback using `res.type()` - * or `res.set('Content-Type', ...)`. - * - * res.format({ - * 'text/plain': function(){ - * res.send('hey'); - * }, - * - * 'text/html': function(){ - * res.send('

hey

'); - * }, - * - * 'appliation/json': function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * In addition to canonicalized MIME types you may - * also use extnames mapped to these types: - * - * res.format({ - * text: function(){ - * res.send('hey'); - * }, - * - * html: function(){ - * res.send('

hey

'); - * }, - * - * json: function(){ - * res.send({ message: 'hey' }); - * } - * }); - * - * By default Express passes an `Error` - * with a `.status` of 406 to `next(err)` - * if a match is not made. If you provide - * a `.default` callback it will be invoked - * instead. - * - * @param {Object} obj - * @return {ServerResponse} for chaining - * @public - */ + // if double quoted, expand newlines + if (isDoubleQuoted) { + val = val.replace(RE_NEWLINES, NEWLINE) + } + } else { + // remove surrounding whitespace + val = val.trim() + } -res.format = function(obj){ - var req = this.req; - var next = req.next; + obj[key] = val + } else if (debug) { + log(`did not match key and value when parsing line ${idx + 1}: ${line}`) + } + }) + + return obj +} + +// Populates process.env from .env file +function config (options /*: ?DotenvConfigOptions */) /*: DotenvConfigOutput */ { + let dotenvPath = path.resolve(process.cwd(), '.env') + let encoding /*: string */ = 'utf8' + let debug = false - var fn = obj.default; - if (fn) delete obj.default; - var keys = Object.keys(obj); + if (options) { + if (options.path != null) { + dotenvPath = options.path + } + if (options.encoding != null) { + encoding = options.encoding + } + if (options.debug != null) { + debug = true + } + } - var key = keys.length > 0 - ? req.accepts(keys) - : false; + try { + // specifying an encoding returns a string instead of a buffer + const parsed = parse(fs.readFileSync(dotenvPath, { encoding }), { debug }) - this.vary("Accept"); + Object.keys(parsed).forEach(function (key) { + if (!Object.prototype.hasOwnProperty.call(process.env, key)) { + process.env[key] = parsed[key] + } else if (debug) { + log(`"${key}" is already defined in \`process.env\` and will not be overwritten`) + } + }) - if (key) { - this.set('Content-Type', normalizeType(key).value); - obj[key](req, this, next); - } else if (fn) { - fn(); - } else { - var err = new Error('Not Acceptable'); - err.status = err.statusCode = 406; - err.types = normalizeTypes(keys).map(function(o){ return o.value }); - next(err); + return { parsed } + } catch (e) { + return { error: e } } +} - return this; -}; +module.exports.config = config +module.exports.parse = parse -/** - * Set _Content-Disposition_ header to _attachment_ with optional `filename`. - * - * @param {String} filename - * @return {ServerResponse} - * @public - */ -res.attachment = function attachment(filename) { - if (filename) { - this.type(extname(filename)); - } +/***/ }), - this.set('Content-Disposition', contentDisposition(filename)); +/***/ 11728: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return this; -}; +"use strict"; -/** - * Append additional header `field` with value `val`. - * - * Example: - * - * res.append('Link', ['', '']); - * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); - * res.append('Warning', '199 Miscellaneous warning'); - * - * @param {String} field - * @param {String|Array} val - * @return {ServerResponse} for chaining - * @public - */ -res.append = function append(field, val) { - var prev = this.get(field); - var value = val; +var Buffer = __nccwpck_require__(21867).Buffer; - if (prev) { - // concat the new and prev vals - value = Array.isArray(prev) ? prev.concat(val) - : Array.isArray(val) ? [prev].concat(val) - : [prev, val]; - } +var getParamBytesForAlg = __nccwpck_require__(30528); - return this.set(field, value); -}; +var MAX_OCTET = 0x80, + CLASS_UNIVERSAL = 0, + PRIMITIVE_BIT = 0x20, + TAG_SEQ = 0x10, + TAG_INT = 0x02, + ENCODED_TAG_SEQ = (TAG_SEQ | PRIMITIVE_BIT) | (CLASS_UNIVERSAL << 6), + ENCODED_TAG_INT = TAG_INT | (CLASS_UNIVERSAL << 6); -/** - * Set header `field` to `val`, or pass - * an object of header fields. - * - * Examples: - * - * res.set('Foo', ['bar', 'baz']); - * res.set('Accept', 'application/json'); - * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); - * - * Aliased as `res.header()`. - * - * @param {String|Object} field - * @param {String|Array} val - * @return {ServerResponse} for chaining - * @public - */ +function base64Url(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} -res.set = -res.header = function header(field, val) { - if (arguments.length === 2) { - var value = Array.isArray(val) - ? val.map(String) - : String(val); +function signatureAsBuffer(signature) { + if (Buffer.isBuffer(signature)) { + return signature; + } else if ('string' === typeof signature) { + return Buffer.from(signature, 'base64'); + } - // add charset to content-type - if (field.toLowerCase() === 'content-type') { - if (Array.isArray(value)) { - throw new TypeError('Content-Type cannot be set to an Array'); - } - if (!charsetRegExp.test(value)) { - var charset = mime.charsets.lookup(value.split(';')[0]); - if (charset) value += '; charset=' + charset.toLowerCase(); - } - } + throw new TypeError('ECDSA signature must be a Base64 string or a Buffer'); +} - this.setHeader(field, value); - } else { - for (var key in field) { - this.set(key, field[key]); - } - } - return this; -}; +function derToJose(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); -/** - * Get value for header `field`. - * - * @param {String} field - * @return {String} - * @public - */ + // the DER encoded param should at most be the param size, plus a padding + // zero, since due to being a signed integer + var maxEncodedParamLength = paramBytes + 1; -res.get = function(field){ - return this.getHeader(field); -}; + var inputLength = signature.length; -/** - * Clear cookie `name`. - * - * @param {String} name - * @param {Object} [options] - * @return {ServerResponse} for chaining - * @public - */ + var offset = 0; + if (signature[offset++] !== ENCODED_TAG_SEQ) { + throw new Error('Could not find expected "seq"'); + } -res.clearCookie = function clearCookie(name, options) { - var opts = merge({ expires: new Date(1), path: '/' }, options); + var seqLength = signature[offset++]; + if (seqLength === (MAX_OCTET | 1)) { + seqLength = signature[offset++]; + } - return this.cookie(name, '', opts); -}; + if (inputLength - offset < seqLength) { + throw new Error('"seq" specified length of "' + seqLength + '", only "' + (inputLength - offset) + '" remaining'); + } -/** - * Set cookie `name` to `value`, with the given `options`. - * - * Options: - * - * - `maxAge` max-age in milliseconds, converted to `expires` - * - `signed` sign the cookie - * - `path` defaults to "/" - * - * Examples: - * - * // "Remember Me" for 15 minutes - * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); - * - * // same as above - * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) - * - * @param {String} name - * @param {String|Object} value - * @param {Object} [options] - * @return {ServerResponse} for chaining - * @public - */ + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "r"'); + } -res.cookie = function (name, value, options) { - var opts = merge({}, options); - var secret = this.req.secret; - var signed = opts.signed; + var rLength = signature[offset++]; - if (signed && !secret) { - throw new Error('cookieParser("secret") required for signed cookies'); - } + if (inputLength - offset - 2 < rLength) { + throw new Error('"r" specified length of "' + rLength + '", only "' + (inputLength - offset - 2) + '" available'); + } - var val = typeof value === 'object' - ? 'j:' + JSON.stringify(value) - : String(value); + if (maxEncodedParamLength < rLength) { + throw new Error('"r" specified length of "' + rLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } - if (signed) { - val = 's:' + sign(val, secret); - } + var rOffset = offset; + offset += rLength; - if ('maxAge' in opts) { - opts.expires = new Date(Date.now() + opts.maxAge); - opts.maxAge /= 1000; - } + if (signature[offset++] !== ENCODED_TAG_INT) { + throw new Error('Could not find expected "int" for "s"'); + } - if (opts.path == null) { - opts.path = '/'; - } + var sLength = signature[offset++]; - this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); + if (inputLength - offset !== sLength) { + throw new Error('"s" specified length of "' + sLength + '", expected "' + (inputLength - offset) + '"'); + } - return this; -}; + if (maxEncodedParamLength < sLength) { + throw new Error('"s" specified length of "' + sLength + '", max of "' + maxEncodedParamLength + '" is acceptable'); + } -/** - * Set the location header to `url`. - * - * The given `url` can also be "back", which redirects - * to the _Referrer_ or _Referer_ headers or "/". - * - * Examples: - * - * res.location('/foo/bar').; - * res.location('http://example.com'); - * res.location('../login'); - * - * @param {String} url - * @return {ServerResponse} for chaining - * @public - */ + var sOffset = offset; + offset += sLength; -res.location = function location(url) { - var loc = url; + if (offset !== inputLength) { + throw new Error('Expected to consume entire buffer, but "' + (inputLength - offset) + '" bytes remain'); + } - // "back" is an alias for the referrer - if (url === 'back') { - loc = this.req.get('Referrer') || '/'; - } + var rPadding = paramBytes - rLength, + sPadding = paramBytes - sLength; - // set location - return this.set('Location', encodeUrl(loc)); -}; + var dst = Buffer.allocUnsafe(rPadding + rLength + sPadding + sLength); -/** - * Redirect to the given `url` with optional response `status` - * defaulting to 302. - * - * The resulting `url` is determined by `res.location()`, so - * it will play nicely with mounted apps, relative paths, - * `"back"` etc. - * - * Examples: - * - * res.redirect('/foo/bar'); - * res.redirect('http://example.com'); - * res.redirect(301, 'http://example.com'); - * res.redirect('../login'); // /blog/post/1 -> /blog/login - * - * @public - */ + for (offset = 0; offset < rPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, rOffset + Math.max(-rPadding, 0), rOffset + rLength); -res.redirect = function redirect(url) { - var address = url; - var body; - var status = 302; + offset = paramBytes; - // allow status / url - if (arguments.length === 2) { - if (typeof arguments[0] === 'number') { - status = arguments[0]; - address = arguments[1]; - } else { - deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); - status = arguments[1]; - } - } + for (var o = offset; offset < o + sPadding; ++offset) { + dst[offset] = 0; + } + signature.copy(dst, offset, sOffset + Math.max(-sPadding, 0), sOffset + sLength); - // Set location header - address = this.location(address).get('Location'); + dst = dst.toString('base64'); + dst = base64Url(dst); - // Support text/{plain,html} by default - this.format({ - text: function(){ - body = statuses[status] + '. Redirecting to ' + address - }, + return dst; +} - html: function(){ - var u = escapeHtml(address); - body = '

' + statuses[status] + '. Redirecting to ' + u + '

' - }, +function countPadding(buf, start, stop) { + var padding = 0; + while (start + padding < stop && buf[start + padding] === 0) { + ++padding; + } - default: function(){ - body = ''; - } - }); + var needsSign = buf[start + padding] >= MAX_OCTET; + if (needsSign) { + --padding; + } - // Respond - this.statusCode = status; - this.set('Content-Length', Buffer.byteLength(body)); + return padding; +} - if (this.req.method === 'HEAD') { - this.end(); - } else { - this.end(body); - } +function joseToDer(signature, alg) { + signature = signatureAsBuffer(signature); + var paramBytes = getParamBytesForAlg(alg); + + var signatureBytes = signature.length; + if (signatureBytes !== paramBytes * 2) { + throw new TypeError('"' + alg + '" signatures must be "' + paramBytes * 2 + '" bytes, saw "' + signatureBytes + '"'); + } + + var rPadding = countPadding(signature, 0, paramBytes); + var sPadding = countPadding(signature, paramBytes, signature.length); + var rLength = paramBytes - rPadding; + var sLength = paramBytes - sPadding; + + var rsBytes = 1 + 1 + rLength + 1 + 1 + sLength; + + var shortLength = rsBytes < MAX_OCTET; + + var dst = Buffer.allocUnsafe((shortLength ? 2 : 3) + rsBytes); + + var offset = 0; + dst[offset++] = ENCODED_TAG_SEQ; + if (shortLength) { + // Bit 8 has value "0" + // bits 7-1 give the length. + dst[offset++] = rsBytes; + } else { + // Bit 8 of first octet has value "1" + // bits 7-1 give the number of additional length octets. + dst[offset++] = MAX_OCTET | 1; + // length, base 256 + dst[offset++] = rsBytes & 0xff; + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = rLength; + if (rPadding < 0) { + dst[offset++] = 0; + offset += signature.copy(dst, offset, 0, paramBytes); + } else { + offset += signature.copy(dst, offset, rPadding, paramBytes); + } + dst[offset++] = ENCODED_TAG_INT; + dst[offset++] = sLength; + if (sPadding < 0) { + dst[offset++] = 0; + signature.copy(dst, offset, paramBytes); + } else { + signature.copy(dst, offset, paramBytes + sPadding); + } + + return dst; +} + +module.exports = { + derToJose: derToJose, + joseToDer: joseToDer }; -/** - * Add `field` to Vary. If already present in the Vary set, then - * this call is simply ignored. - * - * @param {Array|String} field - * @return {ServerResponse} for chaining - * @public - */ -res.vary = function(field){ - // checks for back-compat - if (!field || (Array.isArray(field) && !field.length)) { - deprecate('res.vary(): Provide a field name'); - return this; - } +/***/ }), - vary(this, field); +/***/ 30528: +/***/ ((module) => { - return this; +"use strict"; + + +function getParamSize(keySize) { + var result = ((keySize / 8) | 0) + (keySize % 8 === 0 ? 0 : 1); + return result; +} + +var paramBytesForAlg = { + ES256: getParamSize(256), + ES384: getParamSize(384), + ES512: getParamSize(521) }; -/** - * Render `view` with the given `options` and optional callback `fn`. - * When a callback function is given a response will _not_ be made - * automatically, otherwise a response of _200_ and _text/html_ is given. - * - * Options: - * - * - `cache` boolean hinting to the engine it should cache - * - `filename` filename of the view being rendered - * - * @public - */ +function getParamBytesForAlg(alg) { + var paramBytes = paramBytesForAlg[alg]; + if (paramBytes) { + return paramBytes; + } -res.render = function render(view, options, callback) { - var app = this.req.app; - var done = callback; - var opts = options || {}; - var req = this.req; - var self = this; + throw new Error('Unknown algorithm "' + alg + '"'); +} - // support callback function as second arg - if (typeof options === 'function') { - done = options; - opts = {}; - } +module.exports = getParamBytesForAlg; - // merge res.locals - opts._locals = self.locals; - // default callback to respond - done = done || function (err, str) { - if (err) return req.next(err); - self.send(str); - }; +/***/ }), + +/***/ 14401: +/***/ ((module) => { + +"use strict"; +/*! + * ee-first + * Copyright(c) 2014 Jonathan Ong + * MIT Licensed + */ - // render - app.render(view, opts, done); -}; -// pipe the send file stream -function sendfile(res, file, options, callback) { - var done = false; - var streaming; - // request aborted - function onaborted() { - if (done) return; - done = true; +/** + * Module exports. + * @public + */ - var err = new Error('Request aborted'); - err.code = 'ECONNABORTED'; - callback(err); - } +module.exports = first - // directory - function ondirectory() { - if (done) return; - done = true; +/** + * Get the first event in a set of event emitters and event pairs. + * + * @param {array} stuff + * @param {function} done + * @public + */ - var err = new Error('EISDIR, read'); - err.code = 'EISDIR'; - callback(err); - } +function first(stuff, done) { + if (!Array.isArray(stuff)) + throw new TypeError('arg must be an array of [ee, events...] arrays') - // errors - function onerror(err) { - if (done) return; - done = true; - callback(err); - } + var cleanups = [] - // ended - function onend() { - if (done) return; - done = true; - callback(); - } + for (var i = 0; i < stuff.length; i++) { + var arr = stuff[i] - // file - function onfile() { - streaming = false; - } + if (!Array.isArray(arr) || arr.length < 2) + throw new TypeError('each array member must be [ee, events...]') - // finished - function onfinish(err) { - if (err && err.code === 'ECONNRESET') return onaborted(); - if (err) return onerror(err); - if (done) return; + var ee = arr[0] - setImmediate(function () { - if (streaming !== false && !done) { - onaborted(); - return; - } + for (var j = 1; j < arr.length; j++) { + var event = arr[j] + var fn = listener(event, callback) - if (done) return; - done = true; - callback(); - }); + // listen to the event + ee.on(event, fn) + // push this listener to the list of cleanups + cleanups.push({ + ee: ee, + event: event, + fn: fn, + }) + } } - // streaming - function onstream() { - streaming = true; + function callback() { + cleanup() + done.apply(null, arguments) } - file.on('directory', ondirectory); - file.on('end', onend); - file.on('error', onerror); - file.on('file', onfile); - file.on('stream', onstream); - onFinished(res, onfinish); - - if (options.headers) { - // set headers on successful transfer - file.on('headers', function headers(res) { - var obj = options.headers; - var keys = Object.keys(obj); + function cleanup() { + var x + for (var i = 0; i < cleanups.length; i++) { + x = cleanups[i] + x.ee.removeListener(x.event, x.fn) + } + } - for (var i = 0; i < keys.length; i++) { - var k = keys[i]; - res.setHeader(k, obj[k]); - } - }); + function thunk(fn) { + done = fn } - // pipe - file.pipe(res); + thunk.cancel = cleanup + + return thunk } /** - * Stringify JSON, like JSON.stringify, but v8 optimized, with the - * ability to escape characters that can trigger HTML sniffing. - * - * @param {*} value - * @param {function} replaces - * @param {number} spaces - * @param {boolean} escape - * @returns {string} + * Create the event listener. * @private */ -function stringify (value, replacer, spaces, escape) { - // v8 checks arguments.length for optimizing simple call - // https://bugs.chromium.org/p/v8/issues/detail?id=4730 - var json = replacer || spaces - ? JSON.stringify(value, replacer, spaces) - : JSON.stringify(value); +function listener(event, done) { + return function onevent(arg1) { + var args = new Array(arguments.length) + var ee = this + var err = event === 'error' + ? arg1 + : null - if (escape) { - json = json.replace(/[<>&]/g, function (c) { - switch (c.charCodeAt(0)) { - case 0x3c: - return '\\u003c' - case 0x3e: - return '\\u003e' - case 0x26: - return '\\u0026' - /* istanbul ignore next: unreachable default */ - default: - return c - } - }) - } + // copy args to prevent arguments escaping scope + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } - return json + done(err, ee, event, args) + } } /***/ }), -/***/ 24963: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 16592: +/***/ ((module) => { "use strict"; /*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson + * encodeurl + * Copyright(c) 2016 Douglas Christopher Wilson * MIT Licensed */ /** - * Module dependencies. - * @private + * Module exports. + * @public */ -var Route = __nccwpck_require__(23699); -var Layer = __nccwpck_require__(25624); -var methods = __nccwpck_require__(58752); -var mixin = __nccwpck_require__(44429); -var debug = __nccwpck_require__(52529)('express:router'); -var deprecate = __nccwpck_require__(18883)('express'); -var flatten = __nccwpck_require__(62003); -var parseUrl = __nccwpck_require__(89808); -var setPrototypeOf = __nccwpck_require__(40414) +module.exports = encodeUrl /** - * Module variables. + * RegExp to match non-URL code points, *after* encoding (i.e. not including "%") + * and including invalid escape sequences. * @private */ -var objectRegExp = /^\[object (\S+)\]$/; -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; +var ENCODE_CHARS_REGEXP = /(?:[^\x21\x25\x26-\x3B\x3D\x3F-\x5B\x5D\x5F\x61-\x7A\x7E]|%(?:[^0-9A-Fa-f]|[0-9A-Fa-f][^0-9A-Fa-f]|$))+/g /** - * Initialize a new `Router` with the given `options`. - * - * @param {Object} [options] - * @return {Router} which is an callable function - * @public + * RegExp to match unmatched surrogate pair. + * @private */ -var proto = module.exports = function(options) { - var opts = options || {}; - - function router(req, res, next) { - router.handle(req, res, next); - } - - // mixin Router class functions - setPrototypeOf(router, proto) +var UNMATCHED_SURROGATE_PAIR_REGEXP = /(^|[^\uD800-\uDBFF])[\uDC00-\uDFFF]|[\uD800-\uDBFF]([^\uDC00-\uDFFF]|$)/g - router.params = {}; - router._params = []; - router.caseSensitive = opts.caseSensitive; - router.mergeParams = opts.mergeParams; - router.strict = opts.strict; - router.stack = []; +/** + * String to replace unmatched surrogate pair with. + * @private + */ - return router; -}; +var UNMATCHED_SURROGATE_PAIR_REPLACE = '$1\uFFFD$2' /** - * Map the given param placeholder `name`(s) to the given callback. - * - * Parameter mapping is used to provide pre-conditions to routes - * which use normalized placeholders. For example a _:user_id_ parameter - * could automatically load a user's information from the database without - * any additional code, - * - * The callback uses the same signature as middleware, the only difference - * being that the value of the placeholder is passed, in this case the _id_ - * of the user. Once the `next()` function is invoked, just like middleware - * it will continue on to execute the route, or subsequent parameter functions. + * Encode a URL to a percent-encoded form, excluding already-encoded sequences. * - * Just like in middleware, you must either respond to the request or call next - * to avoid stalling the request. + * This function will take an already-encoded URL and encode all the non-URL + * code points. This function will not encode the "%" character unless it is + * not part of a valid sequence (`%20` will be left as-is, but `%foo` will + * be encoded as `%25foo`). * - * app.param('user_id', function(req, res, next, id){ - * User.find(id, function(err, user){ - * if (err) { - * return next(err); - * } else if (!user) { - * return next(new Error('failed to load user')); - * } - * req.user = user; - * next(); - * }); - * }); + * This encode is meant to be "safe" and does not throw errors. It will try as + * hard as it can to properly encode the given URL, including replacing any raw, + * unpaired surrogate pairs with the Unicode replacement character prior to + * encoding. * - * @param {String} name - * @param {Function} fn - * @return {app} for chaining + * @param {string} url + * @return {string} * @public */ -proto.param = function param(name, fn) { - // param logic - if (typeof name === 'function') { - deprecate('router.param(fn): Refactor to use path params'); - this._params.push(name); - return; - } +function encodeUrl (url) { + return String(url) + .replace(UNMATCHED_SURROGATE_PAIR_REGEXP, UNMATCHED_SURROGATE_PAIR_REPLACE) + .replace(ENCODE_CHARS_REGEXP, encodeURI) +} - // apply param functions - var params = this._params; - var len = params.length; - var ret; - if (name[0] === ':') { - deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); - name = name.substr(1); - } +/***/ }), - for (var i = 0; i < len; ++i) { - if (ret = params[i](name, fn)) { - fn = ret; - } - } +/***/ 23505: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // ensure we end up with a - // middleware function - if ('function' !== typeof fn) { - throw new Error('invalid param() call for ' + name + ', got ' + fn); - } +"use strict"; - (this.params[name] = this.params[name] || []).push(fn); - return this; + +var util = __nccwpck_require__(31669); +var isArrayish = __nccwpck_require__(7604); + +var errorEx = function errorEx(name, properties) { + if (!name || name.constructor !== String) { + properties = name || {}; + name = Error.name; + } + + var errorExError = function ErrorEXError(message) { + if (!this) { + return new ErrorEXError(message); + } + + message = message instanceof Error + ? message.message + : (message || this.message); + + Error.call(this, message); + Error.captureStackTrace(this, errorExError); + + this.name = name; + + Object.defineProperty(this, 'message', { + configurable: true, + enumerable: false, + get: function () { + var newMessage = message.split(/\r?\n/g); + + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } + + var modifier = properties[key]; + + if ('message' in modifier) { + newMessage = modifier.message(this[key], newMessage) || newMessage; + if (!isArrayish(newMessage)) { + newMessage = [newMessage]; + } + } + } + + return newMessage.join('\n'); + }, + set: function (v) { + message = v; + } + }); + + var overwrittenStack = null; + + var stackDescriptor = Object.getOwnPropertyDescriptor(this, 'stack'); + var stackGetter = stackDescriptor.get; + var stackValue = stackDescriptor.value; + delete stackDescriptor.value; + delete stackDescriptor.writable; + + stackDescriptor.set = function (newstack) { + overwrittenStack = newstack; + }; + + stackDescriptor.get = function () { + var stack = (overwrittenStack || ((stackGetter) + ? stackGetter.call(this) + : stackValue)).split(/\r?\n+/g); + + // starting in Node 7, the stack builder caches the message. + // just replace it. + if (!overwrittenStack) { + stack[0] = this.name + ': ' + this.message; + } + + var lineCount = 1; + for (var key in properties) { + if (!properties.hasOwnProperty(key)) { + continue; + } + + var modifier = properties[key]; + + if ('line' in modifier) { + var line = modifier.line(this[key]); + if (line) { + stack.splice(lineCount++, 0, ' ' + line); + } + } + + if ('stack' in modifier) { + modifier.stack(this[key], stack); + } + } + + return stack.join('\n'); + }; + + Object.defineProperty(this, 'stack', stackDescriptor); + }; + + if (Object.setPrototypeOf) { + Object.setPrototypeOf(errorExError.prototype, Error.prototype); + Object.setPrototypeOf(errorExError, Error); + } else { + util.inherits(errorExError, Error); + } + + return errorExError; }; -/** - * Dispatch a req, res into the router. - * @private - */ +errorEx.append = function (str, def) { + return { + message: function (v, message) { + v = v || def; -proto.handle = function handle(req, res, out) { - var self = this; + if (v) { + message[0] += ' ' + str.replace('%s', v.toString()); + } - debug('dispatching %s %s', req.method, req.url); + return message; + } + }; +}; - var idx = 0; - var protohost = getProtohost(req.url) || '' - var removed = ''; - var slashAdded = false; - var paramcalled = {}; +errorEx.line = function (str, def) { + return { + line: function (v) { + v = v || def; - // store options for OPTIONS request - // only used if OPTIONS request - var options = []; + if (v) { + return str.replace('%s', v.toString()); + } - // middleware and routes - var stack = self.stack; + return null; + } + }; +}; - // manage inter-router variables - var parentParams = req.params; - var parentUrl = req.baseUrl || ''; - var done = restore(out, req, 'baseUrl', 'next', 'params'); +module.exports = errorEx; - // setup next layer - req.next = next; - // for options requests, respond with a default if nothing else responds - if (req.method === 'OPTIONS') { - done = wrap(done, function(old, err) { - if (err || options.length === 0) return old(err); - sendOptionsResponse(res, options, old); - }); - } +/***/ }), - // setup basic req values - req.baseUrl = parentUrl; - req.originalUrl = req.originalUrl || req.url; +/***/ 94070: +/***/ ((module) => { - next(); +"use strict"; +/*! + * escape-html + * Copyright(c) 2012-2013 TJ Holowaychuk + * Copyright(c) 2015 Andreas Lubbe + * Copyright(c) 2015 Tiancheng "Timothy" Gu + * MIT Licensed + */ - function next(err) { - var layerError = err === 'route' - ? null - : err; - // remove added slash - if (slashAdded) { - req.url = req.url.substr(1); - slashAdded = false; - } - // restore altered req.url - if (removed.length !== 0) { - req.baseUrl = parentUrl; - req.url = protohost + removed + req.url.substr(protohost.length); - removed = ''; - } +/** + * Module variables. + * @private + */ - // signal to exit router - if (layerError === 'router') { - setImmediate(done, null) - return - } +var matchHtmlRegExp = /["'&<>]/; - // no more matching layers - if (idx >= stack.length) { - setImmediate(done, layerError); - return; - } +/** + * Module exports. + * @public + */ - // get pathname of request - var path = getPathname(req); +module.exports = escapeHtml; - if (path == null) { - return done(layerError); - } +/** + * Escape special characters in the given string of html. + * + * @param {string} string The string to escape for inserting into HTML + * @return {string} + * @public + */ - // find next matching layer - var layer; - var match; - var route; +function escapeHtml(string) { + var str = '' + string; + var match = matchHtmlRegExp.exec(str); - while (match !== true && idx < stack.length) { - layer = stack[idx++]; - match = matchLayer(layer, path); - route = layer.route; + if (!match) { + return str; + } - if (typeof match !== 'boolean') { - // hold on to layerError - layerError = layerError || match; - } + var escape; + var html = ''; + var index = 0; + var lastIndex = 0; - if (match !== true) { + for (index = match.index; index < str.length; index++) { + switch (str.charCodeAt(index)) { + case 34: // " + escape = '"'; + break; + case 38: // & + escape = '&'; + break; + case 39: // ' + escape = '''; + break; + case 60: // < + escape = '<'; + break; + case 62: // > + escape = '>'; + break; + default: continue; - } + } - if (!route) { - // process non-route handlers normally - continue; - } + if (lastIndex !== index) { + html += str.substring(lastIndex, index); + } - if (layerError) { - // routes do not match with a pending error - match = false; - continue; - } + lastIndex = index + 1; + html += escape; + } - var method = req.method; - var has_method = route._handles_method(method); + return lastIndex !== index + ? html + str.substring(lastIndex, index) + : html; +} - // build up automatic options response - if (!has_method && method === 'OPTIONS') { - appendMethods(options, route._options()); - } - // don't even bother matching route - if (!has_method && method !== 'HEAD') { - match = false; - continue; - } - } +/***/ }), - // no match - if (match !== true) { - return done(layerError); - } +/***/ 98691: +/***/ ((module) => { - // store route for dispatch on change - if (route) { - req.route = route; - } +"use strict"; - // Capture one-time layer values - req.params = self.mergeParams - ? mergeParams(layer.params, parentParams) - : layer.params; - var layerPath = layer.path; - // this should be done for the layer - self.process_params(layer, paramcalled, req, res, function (err) { - if (err) { - return next(layerError || err); - } +module.exports = string => { + if (typeof string !== 'string') { + throw new TypeError('Expected a string'); + } - if (route) { - return layer.handle_request(req, res, next); - } + // Escape characters with special meaning either inside or outside character sets. + // Use a simple backslash escape when it’s always valid, and a \unnnn escape when the simpler form would be disallowed by Unicode patterns’ stricter grammar. + return string + .replace(/[|\\{}()[\]^$+*?.]/g, '\\$&') + .replace(/-/g, '\\x2d'); +}; - trim_prefix(layer, layerError, layerPath, path); - }); - } - function trim_prefix(layer, layerError, layerPath, path) { - if (layerPath.length !== 0) { - // Validate path breaks on a path separator - var c = path[layerPath.length] - if (c && c !== '/' && c !== '.') return next(layerError) +/***/ }), - // Trim off the part of the url that matches the route - // middleware (.use stuff) needs to have the path stripped - debug('trim prefix (%s) from url %s', layerPath, req.url); - removed = layerPath; - req.url = protohost + req.url.substr(protohost.length + removed.length); +/***/ 69972: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // Ensure leading slash - if (!protohost && req.url[0] !== '/') { - req.url = '/' + req.url; - slashAdded = true; - } +"use strict"; +/*! + * etag + * Copyright(c) 2014-2016 Douglas Christopher Wilson + * MIT Licensed + */ - // Setup base URL (no trailing slash) - req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' - ? removed.substring(0, removed.length - 1) - : removed); - } - debug('%s %s : %s', layer.name, layerPath, req.originalUrl); - if (layerError) { - layer.handle_error(layerError, req, res, next); - } else { - layer.handle_request(req, res, next); - } - } -}; +/** + * Module exports. + * @public + */ + +module.exports = etag /** - * Process any parameters for the layer. + * Module dependencies. * @private */ -proto.process_params = function process_params(layer, called, req, res, done) { - var params = this.params; +var crypto = __nccwpck_require__(76417) +var Stats = __nccwpck_require__(35747).Stats - // captured parameters from the layer, keys and values - var keys = layer.keys; +/** + * Module variables. + * @private + */ - // fast track - if (!keys || keys.length === 0) { - return done(); - } +var toString = Object.prototype.toString - var i = 0; - var name; - var paramIndex = 0; - var key; - var paramVal; - var paramCallbacks; - var paramCalled; +/** + * Generate an entity tag. + * + * @param {Buffer|string} entity + * @return {string} + * @private + */ - // process params in order - // param callbacks can be async - function param(err) { - if (err) { - return done(err); - } +function entitytag (entity) { + if (entity.length === 0) { + // fast-path empty + return '"0-2jmj7l5rSw0yVb/vlWAYkK/YBwk"' + } - if (i >= keys.length ) { - return done(); - } + // compute hash of entity + var hash = crypto + .createHash('sha1') + .update(entity, 'utf8') + .digest('base64') + .substring(0, 27) - paramIndex = 0; - key = keys[i++]; - name = key.name; - paramVal = req.params[name]; - paramCallbacks = params[name]; - paramCalled = called[name]; + // compute length of entity + var len = typeof entity === 'string' + ? Buffer.byteLength(entity, 'utf8') + : entity.length - if (paramVal === undefined || !paramCallbacks) { - return param(); - } + return '"' + len.toString(16) + '-' + hash + '"' +} - // param previously called with same value or error occurred - if (paramCalled && (paramCalled.match === paramVal - || (paramCalled.error && paramCalled.error !== 'route'))) { - // restore value - req.params[name] = paramCalled.value; +/** + * Create a simple ETag. + * + * @param {string|Buffer|Stats} entity + * @param {object} [options] + * @param {boolean} [options.weak] + * @return {String} + * @public + */ - // next param - return param(paramCalled.error); - } +function etag (entity, options) { + if (entity == null) { + throw new TypeError('argument entity is required') + } - called[name] = paramCalled = { - error: null, - match: paramVal, - value: paramVal - }; + // support fs.Stats object + var isStats = isstats(entity) + var weak = options && typeof options.weak === 'boolean' + ? options.weak + : isStats - paramCallback(); + // validate argument + if (!isStats && typeof entity !== 'string' && !Buffer.isBuffer(entity)) { + throw new TypeError('argument entity must be string, Buffer, or fs.Stats') } - // single param callbacks - function paramCallback(err) { - var fn = paramCallbacks[paramIndex++]; - - // store updated value - paramCalled.value = req.params[key.name]; + // generate entity tag + var tag = isStats + ? stattag(entity) + : entitytag(entity) - if (err) { - // store error - paramCalled.error = err; - param(err); - return; - } + return weak + ? 'W/' + tag + : tag +} - if (!fn) return param(); +/** + * Determine if object is a Stats object. + * + * @param {object} obj + * @return {boolean} + * @api private + */ - try { - fn(req, res, paramCallback, paramVal, key.name); - } catch (e) { - paramCallback(e); - } +function isstats (obj) { + // genuine fs.Stats + if (typeof Stats === 'function' && obj instanceof Stats) { + return true } - param(); -}; + // quack quack + return obj && typeof obj === 'object' && + 'ctime' in obj && toString.call(obj.ctime) === '[object Date]' && + 'mtime' in obj && toString.call(obj.mtime) === '[object Date]' && + 'ino' in obj && typeof obj.ino === 'number' && + 'size' in obj && typeof obj.size === 'number' +} /** - * Use the given middleware function, with optional path, defaulting to "/". - * - * Use (like `.all`) will run for any http METHOD, but it will not add - * handlers for those methods so OPTIONS requests will not consider `.use` - * functions even if they could respond. - * - * The other difference is that _route_ path is stripped and not visible - * to the handler function. The main effect of this feature is that mounted - * handlers can operate without any code changes regardless of the "prefix" - * pathname. + * Generate a tag for a stat. * - * @public + * @param {object} stat + * @return {string} + * @private */ -proto.use = function use(fn) { - var offset = 0; - var path = '/'; +function stattag (stat) { + var mtime = stat.mtime.getTime().toString(16) + var size = stat.size.toString(16) - // default path to '/' - // disambiguate router.use([fn]) - if (typeof fn !== 'function') { - var arg = fn; + return '"' + size + '-' + mtime + '"' +} - while (Array.isArray(arg) && arg.length !== 0) { - arg = arg[0]; - } - // first arg is the path - if (typeof arg !== 'function') { - offset = 1; - path = fn; - } - } +/***/ }), - var callbacks = flatten(slice.call(arguments, offset)); +/***/ 68883: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (callbacks.length === 0) { - throw new TypeError('Router.use() requires a middleware function') - } +var original = __nccwpck_require__(80086) +var parse = __nccwpck_require__(78835).parse +var events = __nccwpck_require__(28614) +var https = __nccwpck_require__(57211) +var http = __nccwpck_require__(98605) +var util = __nccwpck_require__(31669) - for (var i = 0; i < callbacks.length; i++) { - var fn = callbacks[i]; +var httpsOptions = [ + 'pfx', 'key', 'passphrase', 'cert', 'ca', 'ciphers', + 'rejectUnauthorized', 'secureProtocol', 'servername', 'checkServerIdentity' +] - if (typeof fn !== 'function') { - throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) +var bom = [239, 187, 191] +var colon = 58 +var space = 32 +var lineFeed = 10 +var carriageReturn = 13 + +function hasBom (buf) { + return bom.every(function (charCode, index) { + return buf[index] === charCode + }) +} + +/** + * Creates a new EventSource object + * + * @param {String} url the URL to which to connect + * @param {Object} [eventSourceInitDict] extra init params. See README for details. + * @api public + **/ +function EventSource (url, eventSourceInitDict) { + var readyState = EventSource.CONNECTING + Object.defineProperty(this, 'readyState', { + get: function () { + return readyState } + }) - // add the middleware - debug('use %o %s', path, fn.name || '') + Object.defineProperty(this, 'url', { + get: function () { + return url + } + }) - var layer = new Layer(path, { - sensitive: this.caseSensitive, - strict: false, - end: false - }, fn); + var self = this + self.reconnectInterval = 1000 + self.connectionInProgress = false - layer.route = undefined; + function onConnectionClosed (message) { + if (readyState === EventSource.CLOSED) return + readyState = EventSource.CONNECTING + _emit('error', new Event('error', {message: message})) - this.stack.push(layer); + // The url may have been changed by a temporary + // redirect. If that's the case, revert it now. + if (reconnectUrl) { + url = reconnectUrl + reconnectUrl = null + } + setTimeout(function () { + if (readyState !== EventSource.CONNECTING || self.connectionInProgress) { + return + } + self.connectionInProgress = true + connect() + }, self.reconnectInterval) } - return this; -}; + var req + var lastEventId = '' + if (eventSourceInitDict && eventSourceInitDict.headers && eventSourceInitDict.headers['Last-Event-ID']) { + lastEventId = eventSourceInitDict.headers['Last-Event-ID'] + delete eventSourceInitDict.headers['Last-Event-ID'] + } -/** - * Create a new Route for the given path. - * - * Each route contains a separate middleware stack and VERB handlers. - * - * See the Route api documentation for details on adding handlers - * and middleware to routes. - * - * @param {String} path - * @return {Route} - * @public - */ + var discardTrailingNewline = false + var data = '' + var eventName = '' -proto.route = function route(path) { - var route = new Route(path); + var reconnectUrl = null - var layer = new Layer(path, { - sensitive: this.caseSensitive, - strict: this.strict, - end: true - }, route.dispatch.bind(route)); + function connect () { + var options = parse(url) + var isSecure = options.protocol === 'https:' + options.headers = { 'Cache-Control': 'no-cache', 'Accept': 'text/event-stream' } + if (lastEventId) options.headers['Last-Event-ID'] = lastEventId + if (eventSourceInitDict && eventSourceInitDict.headers) { + for (var i in eventSourceInitDict.headers) { + var header = eventSourceInitDict.headers[i] + if (header) { + options.headers[i] = header + } + } + } - layer.route = route; + // Legacy: this should be specified as `eventSourceInitDict.https.rejectUnauthorized`, + // but for now exists as a backwards-compatibility layer + options.rejectUnauthorized = !(eventSourceInitDict && !eventSourceInitDict.rejectUnauthorized) - this.stack.push(layer); - return route; -}; + if (eventSourceInitDict && eventSourceInitDict.createConnection !== undefined) { + options.createConnection = eventSourceInitDict.createConnection + } -// create Router#VERB functions -methods.concat('all').forEach(function(method){ - proto[method] = function(path){ - var route = this.route(path) - route[method].apply(route, slice.call(arguments, 1)); - return this; - }; -}); + // If specify http proxy, make the request to sent to the proxy server, + // and include the original url in path and Host headers + var useProxy = eventSourceInitDict && eventSourceInitDict.proxy + if (useProxy) { + var proxy = parse(eventSourceInitDict.proxy) + isSecure = proxy.protocol === 'https:' + + options.protocol = isSecure ? 'https:' : 'http:' + options.path = url + options.headers.Host = options.host + options.hostname = proxy.hostname + options.host = proxy.host + options.port = proxy.port + } + + // If https options are specified, merge them into the request options + if (eventSourceInitDict && eventSourceInitDict.https) { + for (var optName in eventSourceInitDict.https) { + if (httpsOptions.indexOf(optName) === -1) { + continue + } + + var option = eventSourceInitDict.https[optName] + if (option !== undefined) { + options[optName] = option + } + } + } -// append methods to a list of methods -function appendMethods(list, addition) { - for (var i = 0; i < addition.length; i++) { - var method = addition[i]; - if (list.indexOf(method) === -1) { - list.push(method); + // Pass this on to the XHR + if (eventSourceInitDict && eventSourceInitDict.withCredentials !== undefined) { + options.withCredentials = eventSourceInitDict.withCredentials } - } -} -// get pathname of request -function getPathname(req) { - try { - return parseUrl(req).pathname; - } catch (err) { - return undefined; - } -} + req = (isSecure ? https : http).request(options, function (res) { + self.connectionInProgress = false + // Handle HTTP errors + if (res.statusCode === 500 || res.statusCode === 502 || res.statusCode === 503 || res.statusCode === 504) { + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + onConnectionClosed() + return + } -// Get get protocol + host for a URL -function getProtohost(url) { - if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { - return undefined - } + // Handle HTTP redirects + if (res.statusCode === 301 || res.statusCode === 302 || res.statusCode === 307) { + if (!res.headers.location) { + // Server sent redirect response without Location header. + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + return + } + if (res.statusCode === 307) reconnectUrl = url + url = res.headers.location + process.nextTick(connect) + return + } - var searchIndex = url.indexOf('?') - var pathLength = searchIndex !== -1 - ? searchIndex - : url.length - var fqdnIndex = url.substr(0, pathLength).indexOf('://') + if (res.statusCode !== 200) { + _emit('error', new Event('error', {status: res.statusCode, message: res.statusMessage})) + return self.close() + } - return fqdnIndex !== -1 - ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) - : undefined -} + readyState = EventSource.OPEN + res.on('close', function () { + res.removeAllListeners('close') + res.removeAllListeners('end') + onConnectionClosed() + }) -// get type for error message -function gettype(obj) { - var type = typeof obj; + res.on('end', function () { + res.removeAllListeners('close') + res.removeAllListeners('end') + onConnectionClosed() + }) + _emit('open', new Event('open')) - if (type !== 'object') { - return type; - } + // text/event-stream parser adapted from webkit's + // Source/WebCore/page/EventSource.cpp + var isFirst = true + var buf + var startingPos = 0 + var startingFieldLength = -1 + res.on('data', function (chunk) { + buf = buf ? Buffer.concat([buf, chunk]) : chunk + if (isFirst && hasBom(buf)) { + buf = buf.slice(bom.length) + } - // inspect [[Class]] for objects - return toString.call(obj) - .replace(objectRegExp, '$1'); -} + isFirst = false + var pos = 0 + var length = buf.length -/** - * Match path to a layer. - * - * @param {Layer} layer - * @param {string} path - * @private - */ + while (pos < length) { + if (discardTrailingNewline) { + if (buf[pos] === lineFeed) { + ++pos + } + discardTrailingNewline = false + } -function matchLayer(layer, path) { - try { - return layer.match(path); - } catch (err) { - return err; - } -} + var lineLength = -1 + var fieldLength = startingFieldLength + var c -// merge params with parent params -function mergeParams(params, parent) { - if (typeof parent !== 'object' || !parent) { - return params; - } + for (var i = startingPos; lineLength < 0 && i < length; ++i) { + c = buf[i] + if (c === colon) { + if (fieldLength < 0) { + fieldLength = i - pos + } + } else if (c === carriageReturn) { + discardTrailingNewline = true + lineLength = i - pos + } else if (c === lineFeed) { + lineLength = i - pos + } + } - // make copy of parent for base - var obj = mixin({}, parent); + if (lineLength < 0) { + startingPos = length - pos + startingFieldLength = fieldLength + break + } else { + startingPos = 0 + startingFieldLength = -1 + } - // simple non-numeric merging - if (!(0 in params) || !(0 in parent)) { - return mixin(obj, params); - } + parseEventStreamLine(buf, pos, fieldLength, lineLength) - var i = 0; - var o = 0; + pos += lineLength + 1 + } - // determine numeric gaps - while (i in params) { - i++; - } + if (pos === length) { + buf = void 0 + } else if (pos > 0) { + buf = buf.slice(pos) + } + }) + }) - while (o in parent) { - o++; + req.on('error', function (err) { + self.connectionInProgress = false + onConnectionClosed(err.message) + }) + + if (req.setNoDelay) req.setNoDelay(true) + req.end() } - // offset numeric indices in params before merge - for (i--; i >= 0; i--) { - params[i + o] = params[i]; + connect() - // create holes for the merge when necessary - if (i < o) { - delete params[i]; + function _emit () { + if (self.listeners(arguments[0]).length > 0) { + self.emit.apply(self, arguments) } } - return mixin(obj, params); -} - -// restore obj props after function -function restore(fn, obj) { - var props = new Array(arguments.length - 2); - var vals = new Array(arguments.length - 2); - - for (var i = 0; i < props.length; i++) { - props[i] = arguments[i + 2]; - vals[i] = obj[props[i]]; + this._close = function () { + if (readyState === EventSource.CLOSED) return + readyState = EventSource.CLOSED + if (req.abort) req.abort() + if (req.xhr && req.xhr.abort) req.xhr.abort() } - return function () { - // restore vals - for (var i = 0; i < props.length; i++) { - obj[props[i]] = vals[i]; - } - - return fn.apply(this, arguments); - }; -} + function parseEventStreamLine (buf, pos, fieldLength, lineLength) { + if (lineLength === 0) { + if (data.length > 0) { + var type = eventName || 'message' + _emit(type, new MessageEvent(type, { + data: data.slice(0, -1), // remove trailing newline + lastEventId: lastEventId, + origin: original(url) + })) + data = '' + } + eventName = void 0 + } else if (fieldLength > 0) { + var noValue = fieldLength < 0 + var step = 0 + var field = buf.slice(pos, pos + (noValue ? lineLength : fieldLength)).toString() -// send an OPTIONS response -function sendOptionsResponse(res, options, next) { - try { - var body = options.join(','); - res.set('Allow', body); - res.send(body); - } catch (err) { - next(err); - } -} + if (noValue) { + step = lineLength + } else if (buf[pos + fieldLength + 1] !== space) { + step = fieldLength + 1 + } else { + step = fieldLength + 2 + } + pos += step -// wrap a function -function wrap(old, fn) { - return function proxy() { - var args = new Array(arguments.length + 1); + var valueLength = lineLength - step + var value = buf.slice(pos, pos + valueLength).toString() - args[0] = old; - for (var i = 0, len = arguments.length; i < len; i++) { - args[i + 1] = arguments[i]; + if (field === 'data') { + data += value + '\n' + } else if (field === 'event') { + eventName = value + } else if (field === 'id') { + lastEventId = value + } else if (field === 'retry') { + var retry = parseInt(value, 10) + if (!Number.isNaN(retry)) { + self.reconnectInterval = retry + } + } } - - fn.apply(this, args); - }; + } } +module.exports = EventSource -/***/ }), - -/***/ 25624: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2013 Roman Shtylman - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed - */ +util.inherits(EventSource, events.EventEmitter) +EventSource.prototype.constructor = EventSource; // make stacktraces readable +['open', 'error', 'message'].forEach(function (method) { + Object.defineProperty(EventSource.prototype, 'on' + method, { + /** + * Returns the current listener + * + * @return {Mixed} the set function or undefined + * @api private + */ + get: function get () { + var listener = this.listeners(method)[0] + return listener ? (listener._listener ? listener._listener : listener) : undefined + }, + /** + * Start listening for events + * + * @param {Function} listener the listener + * @return {Mixed} the set function or undefined + * @api private + */ + set: function set (listener) { + this.removeAllListeners(method) + this.addEventListener(method, listener) + } + }) +}) /** - * Module dependencies. - * @private + * Ready states */ +Object.defineProperty(EventSource, 'CONNECTING', {enumerable: true, value: 0}) +Object.defineProperty(EventSource, 'OPEN', {enumerable: true, value: 1}) +Object.defineProperty(EventSource, 'CLOSED', {enumerable: true, value: 2}) -var pathRegexp = __nccwpck_require__(37819); -var debug = __nccwpck_require__(52529)('express:router:layer'); +EventSource.prototype.CONNECTING = 0 +EventSource.prototype.OPEN = 1 +EventSource.prototype.CLOSED = 2 /** - * Module variables. - * @private + * Closes the connection, if one is made, and sets the readyState attribute to 2 (closed) + * + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventSource/close + * @api public */ - -var hasOwnProperty = Object.prototype.hasOwnProperty; +EventSource.prototype.close = function () { + this._close() +} /** - * Module exports. - * @public + * Emulates the W3C Browser based WebSocket interface using addEventListener. + * + * @param {String} type A string representing the event type to listen out for + * @param {Function} listener callback + * @see https://developer.mozilla.org/en/DOM/element.addEventListener + * @see http://dev.w3.org/html5/websockets/#the-websocket-interface + * @api public */ - -module.exports = Layer; - -function Layer(path, options, fn) { - if (!(this instanceof Layer)) { - return new Layer(path, options, fn); +EventSource.prototype.addEventListener = function addEventListener (type, listener) { + if (typeof listener === 'function') { + // store a reference so we can return the original function again + listener._listener = listener + this.on(type, listener) } - - debug('new %o', path) - var opts = options || {}; - - this.handle = fn; - this.name = fn.name || ''; - this.params = undefined; - this.path = undefined; - this.regexp = pathRegexp(path, this.keys = [], opts); - - // set fast path flags - this.regexp.fast_star = path === '*' - this.regexp.fast_slash = path === '/' && opts.end === false } /** - * Handle the error for the layer. + * Emulates the W3C Browser based WebSocket interface using dispatchEvent. * - * @param {Error} error - * @param {Request} req - * @param {Response} res - * @param {function} next - * @api private + * @param {Event} event An event to be dispatched + * @see https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent + * @api public */ - -Layer.prototype.handle_error = function handle_error(error, req, res, next) { - var fn = this.handle; - - if (fn.length !== 4) { - // not a standard error handler - return next(error); +EventSource.prototype.dispatchEvent = function dispatchEvent (event) { + if (!event.type) { + throw new Error('UNSPECIFIED_EVENT_TYPE_ERR') } + // if event is instance of an CustomEvent (or has 'details' property), + // send the detail object as the payload for the event + this.emit(event.type, event.detail) +} - try { - fn(error, req, res, next); - } catch (err) { - next(err); +/** + * Emulates the W3C Browser based WebSocket interface using removeEventListener. + * + * @param {String} type A string representing the event type to remove + * @param {Function} listener callback + * @see https://developer.mozilla.org/en/DOM/element.removeEventListener + * @see http://dev.w3.org/html5/websockets/#the-websocket-interface + * @api public + */ +EventSource.prototype.removeEventListener = function removeEventListener (type, listener) { + if (typeof listener === 'function') { + listener._listener = undefined + this.removeListener(type, listener) } -}; +} /** - * Handle the request for the layer. + * W3C Event * - * @param {Request} req - * @param {Response} res - * @param {function} next + * @see http://www.w3.org/TR/DOM-Level-3-Events/#interface-Event * @api private */ - -Layer.prototype.handle_request = function handle(req, res, next) { - var fn = this.handle; - - if (fn.length > 3) { - // not a standard request handler - return next(); - } - - try { - fn(req, res, next); - } catch (err) { - next(err); +function Event (type, optionalProperties) { + Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) + if (optionalProperties) { + for (var f in optionalProperties) { + if (optionalProperties.hasOwnProperty(f)) { + Object.defineProperty(this, f, { writable: false, value: optionalProperties[f], enumerable: true }) + } + } } -}; +} /** - * Check if this route matches `path`, if so - * populate `.params`. + * W3C MessageEvent * - * @param {String} path - * @return {Boolean} + * @see http://www.w3.org/TR/webmessaging/#event-definitions * @api private */ - -Layer.prototype.match = function match(path) { - var match - - if (path != null) { - // fast path non-ending match for / (any path matches) - if (this.regexp.fast_slash) { - this.params = {} - this.path = '' - return true - } - - // fast path for * (everything matched in a param) - if (this.regexp.fast_star) { - this.params = {'0': decode_param(path)} - this.path = path - return true +function MessageEvent (type, eventInitDict) { + Object.defineProperty(this, 'type', { writable: false, value: type, enumerable: true }) + for (var f in eventInitDict) { + if (eventInitDict.hasOwnProperty(f)) { + Object.defineProperty(this, f, { writable: false, value: eventInitDict[f], enumerable: true }) } - - // match the path - match = this.regexp.exec(path) - } - - if (!match) { - this.params = undefined; - this.path = undefined; - return false; } +} - // store values - this.params = {}; - this.path = match[0] - - var keys = this.keys; - var params = this.params; - - for (var i = 1; i < match.length; i++) { - var key = keys[i - 1]; - var prop = key.name; - var val = decode_param(match[i]) - if (val !== undefined || !(hasOwnProperty.call(params, prop))) { - params[prop] = val; - } - } +/***/ }), - return true; -}; +/***/ 71204: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Decode param value. - * - * @param {string} val - * @return {string} - * @private +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -function decode_param(val) { - if (typeof val !== 'string' || val.length === 0) { - return val; - } - try { - return decodeURIComponent(val); - } catch (err) { - if (err instanceof URIError) { - err.message = 'Failed to decode param \'' + val + '\''; - err.status = err.statusCode = 400; - } - throw err; - } -} +module.exports = __nccwpck_require__(22587); /***/ }), -/***/ 23699: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 313: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; /*! @@ -47171,527 +50409,641 @@ function decode_param(val) { * @private */ -var debug = __nccwpck_require__(52529)('express:router:route'); -var flatten = __nccwpck_require__(62003); -var Layer = __nccwpck_require__(25624); +var finalhandler = __nccwpck_require__(30810); +var Router = __nccwpck_require__(24963); var methods = __nccwpck_require__(58752); +var middleware = __nccwpck_require__(92636); +var query = __nccwpck_require__(79768); +var debug = __nccwpck_require__(52529)('express:application'); +var View = __nccwpck_require__(99209); +var http = __nccwpck_require__(98605); +var compileETag = __nccwpck_require__(53561).compileETag; +var compileQueryParser = __nccwpck_require__(53561).compileQueryParser; +var compileTrust = __nccwpck_require__(53561).compileTrust; +var deprecate = __nccwpck_require__(18883)('express'); +var flatten = __nccwpck_require__(62003); +var merge = __nccwpck_require__(44429); +var resolve = __nccwpck_require__(85622).resolve; +var setPrototypeOf = __nccwpck_require__(40414) +var slice = Array.prototype.slice; /** - * Module variables. - * @private + * Application prototype. */ -var slice = Array.prototype.slice; -var toString = Object.prototype.toString; +var app = exports = module.exports = {}; /** - * Module exports. - * @public + * Variable for trust proxy inheritance back-compat + * @private */ -module.exports = Route; +var trustProxyDefaultSymbol = '@@symbol:trust_proxy_default'; /** - * Initialize `Route` with the given `path`, + * Initialize the server. * - * @param {String} path - * @public + * - setup default configuration + * - setup default middleware + * - setup route reflection methods + * + * @private */ -function Route(path) { - this.path = path; - this.stack = []; - - debug('new %o', path) +app.init = function init() { + this.cache = {}; + this.engines = {}; + this.settings = {}; - // route handlers for various http methods - this.methods = {}; -} + this.defaultConfiguration(); +}; /** - * Determine if the route handles a given method. + * Initialize application configuration. * @private */ -Route.prototype._handles_method = function _handles_method(method) { - if (this.methods._all) { - return true; - } +app.defaultConfiguration = function defaultConfiguration() { + var env = process.env.NODE_ENV || 'development'; - var name = method.toLowerCase(); + // default settings + this.enable('x-powered-by'); + this.set('etag', 'weak'); + this.set('env', env); + this.set('query parser', 'extended'); + this.set('subdomain offset', 2); + this.set('trust proxy', false); - if (name === 'head' && !this.methods['head']) { - name = 'get'; + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: true + }); + + debug('booting in %s mode', env); + + this.on('mount', function onmount(parent) { + // inherit trust proxy + if (this.settings[trustProxyDefaultSymbol] === true + && typeof parent.settings['trust proxy fn'] === 'function') { + delete this.settings['trust proxy']; + delete this.settings['trust proxy fn']; + } + + // inherit protos + setPrototypeOf(this.request, parent.request) + setPrototypeOf(this.response, parent.response) + setPrototypeOf(this.engines, parent.engines) + setPrototypeOf(this.settings, parent.settings) + }); + + // setup locals + this.locals = Object.create(null); + + // top-most app is mounted at / + this.mountpath = '/'; + + // default locals + this.locals.settings = this.settings; + + // default configuration + this.set('view', View); + this.set('views', resolve('views')); + this.set('jsonp callback name', 'callback'); + + if (env === 'production') { + this.enable('view cache'); } - return Boolean(this.methods[name]); + Object.defineProperty(this, 'router', { + get: function() { + throw new Error('\'app.router\' is deprecated!\nPlease see the 3.x to 4.x migration guide for details on how to update your app.'); + } + }); }; /** - * @return {Array} supported HTTP methods + * lazily adds the base router if it has not yet been added. + * + * We cannot add the base router in the defaultConfiguration because + * it reads app settings which might be set after that has run. + * * @private */ +app.lazyrouter = function lazyrouter() { + if (!this._router) { + this._router = new Router({ + caseSensitive: this.enabled('case sensitive routing'), + strict: this.enabled('strict routing') + }); -Route.prototype._options = function _options() { - var methods = Object.keys(this.methods); - - // append automatic head - if (this.methods.get && !this.methods.head) { - methods.push('head'); - } - - for (var i = 0; i < methods.length; i++) { - // make upper case - methods[i] = methods[i].toUpperCase(); + this._router.use(query(this.get('query parser fn'))); + this._router.use(middleware.init(this)); } - - return methods; }; /** - * dispatch req, res into this route + * Dispatch a req, res pair into the application. Starts pipeline processing. + * + * If no callback is provided, then default error handlers will respond + * in the event of an error bubbling through the stack. + * * @private */ -Route.prototype.dispatch = function dispatch(req, res, done) { - var idx = 0; - var stack = this.stack; - if (stack.length === 0) { - return done(); - } +app.handle = function handle(req, res, callback) { + var router = this._router; - var method = req.method.toLowerCase(); - if (method === 'head' && !this.methods['head']) { - method = 'get'; + // final handler + var done = callback || finalhandler(req, res, { + env: this.get('env'), + onerror: logerror.bind(this) + }); + + // no routes + if (!router) { + debug('no routes defined on app'); + done(); + return; } - req.route = this; + router.handle(req, res, done); +}; - next(); +/** + * Proxy `Router#use()` to add middleware to the app router. + * See Router#use() documentation for details. + * + * If the _fn_ parameter is an express app, then it will be + * mounted at the _route_ specified. + * + * @public + */ - function next(err) { - // signal to exit route - if (err && err === 'route') { - return done(); - } +app.use = function use(fn) { + var offset = 0; + var path = '/'; - // signal to exit router - if (err && err === 'router') { - return done(err) - } + // default path to '/' + // disambiguate app.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; - var layer = stack[idx++]; - if (!layer) { - return done(err); + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; } - if (layer.method && layer.method !== method) { - return next(err); + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; } + } - if (err) { - layer.handle_error(err, req, res, next); - } else { - layer.handle_request(req, res, next); - } + var fns = flatten(slice.call(arguments, offset)); + + if (fns.length === 0) { + throw new TypeError('app.use() requires a middleware function') } + + // setup router + this.lazyrouter(); + var router = this._router; + + fns.forEach(function (fn) { + // non-express app + if (!fn || !fn.handle || !fn.set) { + return router.use(path, fn); + } + + debug('.use app under %s', path); + fn.mountpath = path; + fn.parent = this; + + // restore .app property on req and res + router.use(path, function mounted_app(req, res, next) { + var orig = req.app; + fn.handle(req, res, function (err) { + setPrototypeOf(req, orig.request) + setPrototypeOf(res, orig.response) + next(err); + }); + }); + + // mounted an app + fn.emit('mount', this); + }, this); + + return this; }; /** - * Add a handler for all HTTP verbs to this route. + * Proxy to the app `Router#route()` + * Returns a new `Route` instance for the _path_. * - * Behaves just like middleware and can respond or call `next` - * to continue processing. + * Routes are isolated middleware stacks for specific paths. + * See the Route api docs for details. * - * You can use multiple `.all` call to add multiple handlers. + * @public + */ + +app.route = function route(path) { + this.lazyrouter(); + return this._router.route(path); +}; + +/** + * Register the given template engine callback `fn` + * as `ext`. * - * function check_something(req, res, next){ - * next(); - * }; + * By default will `require()` the engine based on the + * file extension. For example if you try to render + * a "foo.ejs" file Express will invoke the following internally: * - * function validate_user(req, res, next){ - * next(); - * }; + * app.engine('ejs', require('ejs').__express); * - * route - * .all(validate_user) - * .all(check_something) - * .get(function(req, res, next){ - * res.send('hello world'); - * }); + * For engines that do not provide `.__express` out of the box, + * or if you wish to "map" a different extension to the template engine + * you may use this method. For example mapping the EJS template engine to + * ".html" files: * - * @param {function} handler - * @return {Route} for chaining - * @api public + * app.engine('html', require('ejs').renderFile); + * + * In this case EJS provides a `.renderFile()` method with + * the same signature that Express expects: `(path, options, callback)`, + * though note that it aliases this method as `ejs.__express` internally + * so if you're using ".ejs" extensions you dont need to do anything. + * + * Some template engines do not follow this convention, the + * [Consolidate.js](https://github.com/tj/consolidate.js) + * library was created to map all of node's popular template + * engines to follow this convention, thus allowing them to + * work seamlessly within Express. + * + * @param {String} ext + * @param {Function} fn + * @return {app} for chaining + * @public */ -Route.prototype.all = function all() { - var handles = flatten(slice.call(arguments)); - - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; - - if (typeof handle !== 'function') { - var type = toString.call(handle); - var msg = 'Route.all() requires a callback function but got a ' + type - throw new TypeError(msg); - } +app.engine = function engine(ext, fn) { + if (typeof fn !== 'function') { + throw new Error('callback function required'); + } - var layer = Layer('/', {}, handle); - layer.method = undefined; + // get file extension + var extension = ext[0] !== '.' + ? '.' + ext + : ext; - this.methods._all = true; - this.stack.push(layer); - } + // store engine + this.engines[extension] = fn; return this; }; -methods.forEach(function(method){ - Route.prototype[method] = function(){ - var handles = flatten(slice.call(arguments)); - - for (var i = 0; i < handles.length; i++) { - var handle = handles[i]; - - if (typeof handle !== 'function') { - var type = toString.call(handle); - var msg = 'Route.' + method + '() requires a callback function but got a ' + type - throw new Error(msg); - } - - debug('%s %o', method, this.path) +/** + * Proxy to `Router#param()` with one added api feature. The _name_ parameter + * can be an array of names. + * + * See the Router#param() docs for more details. + * + * @param {String|Array} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ - var layer = Layer('/', {}, handle); - layer.method = method; +app.param = function param(name, fn) { + this.lazyrouter(); - this.methods[method] = true; - this.stack.push(layer); + if (Array.isArray(name)) { + for (var i = 0; i < name.length; i++) { + this.param(name[i], fn); } return this; - }; -}); - + } -/***/ }), + this._router.param(name, fn); -/***/ 53561: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + return this; +}; -"use strict"; -/*! - * express - * Copyright(c) 2009-2013 TJ Holowaychuk - * Copyright(c) 2014-2015 Douglas Christopher Wilson - * MIT Licensed +/** + * Assign `setting` to `val`, or return `setting`'s value. + * + * app.set('foo', 'bar'); + * app.set('foo'); + * // => "bar" + * + * Mounted servers inherit their parent server's settings. + * + * @param {String} setting + * @param {*} [val] + * @return {Server} for chaining + * @public */ +app.set = function set(setting, val) { + if (arguments.length === 1) { + // app.get(setting) + return this.settings[setting]; + } + debug('set "%s" to %o', setting, val); -/** - * Module dependencies. - * @api private - */ + // set value + this.settings[setting] = val; -var Buffer = __nccwpck_require__(21867).Buffer -var contentDisposition = __nccwpck_require__(53921); -var contentType = __nccwpck_require__(99915); -var deprecate = __nccwpck_require__(18883)('express'); -var flatten = __nccwpck_require__(62003); -var mime = __nccwpck_require__(95287).mime; -var etag = __nccwpck_require__(69972); -var proxyaddr = __nccwpck_require__(80140); -var qs = __nccwpck_require__(22760); -var querystring = __nccwpck_require__(71191); + // trigger matched settings + switch (setting) { + case 'etag': + this.set('etag fn', compileETag(val)); + break; + case 'query parser': + this.set('query parser fn', compileQueryParser(val)); + break; + case 'trust proxy': + this.set('trust proxy fn', compileTrust(val)); -/** - * Return strong ETag for `body`. - * - * @param {String|Buffer} body - * @param {String} [encoding] - * @return {String} - * @api private - */ + // trust proxy inherit back-compat + Object.defineProperty(this.settings, trustProxyDefaultSymbol, { + configurable: true, + value: false + }); -exports.etag = createETagGenerator({ weak: false }) + break; + } + + return this; +}; /** - * Return weak ETag for `body`. + * Return the app's absolute pathname + * based on the parent(s) that have + * mounted it. + * + * For example if the application was + * mounted as "/admin", which itself + * was mounted as "/blog" then the + * return value would be "/blog/admin". * - * @param {String|Buffer} body - * @param {String} [encoding] * @return {String} - * @api private + * @private */ -exports.wetag = createETagGenerator({ weak: true }) +app.path = function path() { + return this.parent + ? this.parent.path() + this.mountpath + : ''; +}; /** - * Check if `path` looks absolute. + * Check if `setting` is enabled (truthy). * - * @param {String} path + * app.enabled('foo') + * // => false + * + * app.enable('foo') + * app.enabled('foo') + * // => true + * + * @param {String} setting * @return {Boolean} - * @api private + * @public */ -exports.isAbsolute = function(path){ - if ('/' === path[0]) return true; - if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path - if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path +app.enabled = function enabled(setting) { + return Boolean(this.set(setting)); }; /** - * Flatten the given `arr`. + * Check if `setting` is disabled. * - * @param {Array} arr - * @return {Array} - * @api private - */ - -exports.flatten = deprecate.function(flatten, - 'utils.flatten: use array-flatten npm module instead'); - -/** - * Normalize the given `type`, for example "html" becomes "text/html". + * app.disabled('foo') + * // => true + * + * app.enable('foo') + * app.disabled('foo') + * // => false * - * @param {String} type - * @return {Object} - * @api private + * @param {String} setting + * @return {Boolean} + * @public */ -exports.normalizeType = function(type){ - return ~type.indexOf('/') - ? acceptParams(type) - : { value: mime.lookup(type), params: {} }; +app.disabled = function disabled(setting) { + return !this.set(setting); }; /** - * Normalize `types`, for example "html" becomes "text/html". + * Enable `setting`. * - * @param {Array} types - * @return {Array} - * @api private + * @param {String} setting + * @return {app} for chaining + * @public */ -exports.normalizeTypes = function(types){ - var ret = []; - - for (var i = 0; i < types.length; ++i) { - ret.push(exports.normalizeType(types[i])); - } - - return ret; +app.enable = function enable(setting) { + return this.set(setting, true); }; /** - * Generate Content-Disposition header appropriate for the filename. - * non-ascii filenames are urlencoded and a filename* parameter is added + * Disable `setting`. * - * @param {String} filename - * @return {String} - * @api private + * @param {String} setting + * @return {app} for chaining + * @public */ -exports.contentDisposition = deprecate.function(contentDisposition, - 'utils.contentDisposition: use content-disposition npm module instead'); +app.disable = function disable(setting) { + return this.set(setting, false); +}; /** - * Parse accept params `str` returning an - * object with `.value`, `.quality` and `.params`. - * also includes `.originalIndex` for stable sorting - * - * @param {String} str - * @return {Object} - * @api private + * Delegate `.VERB(...)` calls to `router.VERB(...)`. */ -function acceptParams(str, index) { - var parts = str.split(/ *; */); - var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; - - for (var i = 1; i < parts.length; ++i) { - var pms = parts[i].split(/ *= */); - if ('q' === pms[0]) { - ret.quality = parseFloat(pms[1]); - } else { - ret.params[pms[0]] = pms[1]; +methods.forEach(function(method){ + app[method] = function(path){ + if (method === 'get' && arguments.length === 1) { + // app.get(setting) + return this.set(path); } - } - return ret; -} + this.lazyrouter(); + + var route = this._router.route(path); + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); /** - * Compile "etag" value to function. + * Special-cased "all" method, applying the given route `path`, + * middleware, and callback to _every_ HTTP method. * - * @param {Boolean|String|Function} val - * @return {Function} - * @api private + * @param {String} path + * @param {Function} ... + * @return {app} for chaining + * @public */ -exports.compileETag = function(val) { - var fn; +app.all = function all(path) { + this.lazyrouter(); - if (typeof val === 'function') { - return val; - } + var route = this._router.route(path); + var args = slice.call(arguments, 1); - switch (val) { - case true: - fn = exports.wetag; - break; - case false: - break; - case 'strong': - fn = exports.etag; - break; - case 'weak': - fn = exports.wetag; - break; - default: - throw new TypeError('unknown value for etag function: ' + val); + for (var i = 0; i < methods.length; i++) { + route[methods[i]].apply(route, args); } - return fn; -} + return this; +}; + +// del -> delete alias + +app.del = deprecate.function(app.delete, 'app.del: Use app.delete instead'); /** - * Compile "query parser" value to function. + * Render the given view `name` name with `options` + * and a callback accepting an error and the + * rendered template string. * - * @param {String|Function} val - * @return {Function} - * @api private + * Example: + * + * app.render('email', { name: 'Tobi' }, function(err, html){ + * // ... + * }) + * + * @param {String} name + * @param {Object|Function} options or fn + * @param {Function} callback + * @public */ -exports.compileQueryParser = function compileQueryParser(val) { - var fn; - - if (typeof val === 'function') { - return val; - } +app.render = function render(name, options, callback) { + var cache = this.cache; + var done = callback; + var engines = this.engines; + var opts = options; + var renderOptions = {}; + var view; - switch (val) { - case true: - fn = querystring.parse; - break; - case false: - fn = newObject; - break; - case 'extended': - fn = parseExtendedQueryString; - break; - case 'simple': - fn = querystring.parse; - break; - default: - throw new TypeError('unknown value for query parser function: ' + val); + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; } - return fn; -} + // merge app.locals + merge(renderOptions, this.locals); -/** - * Compile "proxy trust" value to function. - * - * @param {Boolean|String|Number|Array|Function} val - * @return {Function} - * @api private - */ + // merge options._locals + if (opts._locals) { + merge(renderOptions, opts._locals); + } -exports.compileTrust = function(val) { - if (typeof val === 'function') return val; + // merge options + merge(renderOptions, opts); - if (val === true) { - // Support plain true/false - return function(){ return true }; + // set .cache unless explicitly provided + if (renderOptions.cache == null) { + renderOptions.cache = this.enabled('view cache'); } - if (typeof val === 'number') { - // Support trusting hop count - return function(a, i){ return i < val }; + // primed cache + if (renderOptions.cache) { + view = cache[name]; } - if (typeof val === 'string') { - // Support comma-separated values - val = val.split(/ *, */); - } + // view + if (!view) { + var View = this.get('view'); - return proxyaddr.compile(val || []); -} + view = new View(name, { + defaultEngine: this.get('view engine'), + root: this.get('views'), + engines: engines + }); -/** - * Set the charset in a given Content-Type string. - * - * @param {String} type - * @param {String} charset - * @return {String} - * @api private - */ + if (!view.path) { + var dirs = Array.isArray(view.root) && view.root.length > 1 + ? 'directories "' + view.root.slice(0, -1).join('", "') + '" or "' + view.root[view.root.length - 1] + '"' + : 'directory "' + view.root + '"' + var err = new Error('Failed to lookup view "' + name + '" in views ' + dirs); + err.view = view; + return done(err); + } -exports.setCharset = function setCharset(type, charset) { - if (!type || !charset) { - return type; + // prime the cache + if (renderOptions.cache) { + cache[name] = view; + } } - // parse type - var parsed = contentType.parse(type); - - // set charset - parsed.parameters.charset = charset; - - // format type - return contentType.format(parsed); + // render + tryRender(view, renderOptions, done); }; /** - * Create an ETag generator function, generating ETags with - * the given options. + * Listen for connections. * - * @param {object} options - * @return {function} - * @private + * A node `http.Server` is returned, with this + * application (which is a `Function`) as its + * callback. If you wish to create both an HTTP + * and HTTPS server you may do so with the "http" + * and "https" modules as shown here: + * + * var http = require('http') + * , https = require('https') + * , express = require('express') + * , app = express(); + * + * http.createServer(app).listen(80); + * https.createServer({ ... }, app).listen(443); + * + * @return {http.Server} + * @public */ -function createETagGenerator (options) { - return function generateETag (body, encoding) { - var buf = !Buffer.isBuffer(body) - ? Buffer.from(body, encoding) - : body - - return etag(buf, options) - } -} +app.listen = function listen() { + var server = http.createServer(this); + return server.listen.apply(server, arguments); +}; /** - * Parse an extended query string with qs. + * Log error using console.error. * - * @return {Object} + * @param {Error} err * @private */ -function parseExtendedQueryString(str) { - return qs.parse(str, { - allowPrototypes: true - }); +function logerror(err) { + /* istanbul ignore next */ + if (this.get('env') !== 'test') console.error(err.stack || err.toString()); } /** - * Return new empty object. - * - * @return {Object} - * @api private + * Try rendering a view. + * @private */ -function newObject() { - return {}; +function tryRender(view, options, callback) { + try { + view.render(options, callback); + } catch (err) { + callback(err); + } } /***/ }), -/***/ 99209: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 22587: +/***/ ((module, exports, __nccwpck_require__) => { "use strict"; /*! @@ -47706,2778 +51058,2582 @@ function newObject() { /** * Module dependencies. - * @private - */ - -var debug = __nccwpck_require__(52529)('express:view'); -var path = __nccwpck_require__(85622); -var fs = __nccwpck_require__(35747); - -/** - * Module variables. - * @private */ -var dirname = path.dirname; -var basename = path.basename; -var extname = path.extname; -var join = path.join; -var resolve = path.resolve; +var bodyParser = __nccwpck_require__(97076) +var EventEmitter = __nccwpck_require__(28614).EventEmitter; +var mixin = __nccwpck_require__(11149); +var proto = __nccwpck_require__(313); +var Route = __nccwpck_require__(23699); +var Router = __nccwpck_require__(24963); +var req = __nccwpck_require__(71260); +var res = __nccwpck_require__(64934); /** - * Module exports. - * @public + * Expose `createApplication()`. */ -module.exports = View; +exports = module.exports = createApplication; /** - * Initialize a new `View` with the given `name`. - * - * Options: - * - * - `defaultEngine` the default template engine name - * - `engines` template engine require() cache - * - `root` root path for view lookup + * Create an express application. * - * @param {string} name - * @param {object} options - * @public + * @return {Function} + * @api public */ -function View(name, options) { - var opts = options || {}; - - this.defaultEngine = opts.defaultEngine; - this.ext = extname(name); - this.name = name; - this.root = opts.root; - - if (!this.ext && !this.defaultEngine) { - throw new Error('No default engine was specified and no extension was provided.'); - } - - var fileName = name; - - if (!this.ext) { - // get extension from default engine name - this.ext = this.defaultEngine[0] !== '.' - ? '.' + this.defaultEngine - : this.defaultEngine; - - fileName += this.ext; - } - - if (!opts.engines[this.ext]) { - // load engine - var mod = this.ext.substr(1) - debug('require "%s"', mod) - - // default engine export - var fn = require(mod).__express +function createApplication() { + var app = function(req, res, next) { + app.handle(req, res, next); + }; - if (typeof fn !== 'function') { - throw new Error('Module "' + mod + '" does not provide a view engine.') - } + mixin(app, EventEmitter.prototype, false); + mixin(app, proto, false); - opts.engines[this.ext] = fn - } + // expose the prototype that will get set on requests + app.request = Object.create(req, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) - // store loaded engine - this.engine = opts.engines[this.ext]; + // expose the prototype that will get set on responses + app.response = Object.create(res, { + app: { configurable: true, enumerable: true, writable: true, value: app } + }) - // lookup path - this.path = this.lookup(fileName); + app.init(); + return app; } /** - * Lookup view by the given `name` - * - * @param {string} name - * @private + * Expose the prototypes. */ -View.prototype.lookup = function lookup(name) { - var path; - var roots = [].concat(this.root); - - debug('lookup "%s"', name); - - for (var i = 0; i < roots.length && !path; i++) { - var root = roots[i]; - - // resolve the path - var loc = resolve(root, name); - var dir = dirname(loc); - var file = basename(loc); - - // resolve the file - path = this.resolve(dir, file); - } - - return path; -}; +exports.application = proto; +exports.request = req; +exports.response = res; /** - * Render with the given options. - * - * @param {object} options - * @param {function} callback - * @private + * Expose constructors. */ -View.prototype.render = function render(options, callback) { - debug('render "%s"', this.path); - this.engine(this.path, options, callback); -}; +exports.Route = Route; +exports.Router = Router; /** - * Resolve the file within the given directory. - * - * @param {string} dir - * @param {string} file - * @private + * Expose middleware */ -View.prototype.resolve = function resolve(dir, file) { - var ext = this.ext; - - // . - var path = join(dir, file); - var stat = tryStat(path); - - if (stat && stat.isFile()) { - return path; - } - - // /index. - path = join(dir, basename(file, ext), 'index' + ext); - stat = tryStat(path); - - if (stat && stat.isFile()) { - return path; - } -}; +exports.json = bodyParser.json +exports.query = __nccwpck_require__(79768); +exports.raw = bodyParser.raw +exports.static = __nccwpck_require__(13146); +exports.text = bodyParser.text +exports.urlencoded = bodyParser.urlencoded /** - * Return a stat, maybe. - * - * @param {string} path - * @return {fs.Stats} - * @private + * Replace removed middleware with an appropriate error message. */ -function tryStat(path) { - debug('stat "%s"', path); - - try { - return fs.statSync(path); - } catch (e) { - return undefined; - } -} +var removedMiddlewares = [ + 'bodyParser', + 'compress', + 'cookieSession', + 'session', + 'logger', + 'cookieParser', + 'favicon', + 'responseTime', + 'errorHandler', + 'timeout', + 'methodOverride', + 'vhost', + 'csrf', + 'directory', + 'limit', + 'multipart', + 'staticCache' +] + +removedMiddlewares.forEach(function (name) { + Object.defineProperty(exports, name, { + get: function () { + throw new Error('Most middleware (like ' + name + ') is no longer bundled with Express and must be installed separately. Please see https://github.com/senchalabs/connect#middleware.'); + }, + configurable: true + }); +}); /***/ }), -/***/ 36654: -/***/ ((module, exports, __nccwpck_require__) => { +/***/ 92636: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -exports = module.exports = __nccwpck_require__(86991); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); + /** - * Colors. + * Module dependencies. + * @private */ -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; +var setPrototypeOf = __nccwpck_require__(40414) /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. + * Initialization middleware, exposing the + * request and response to each other, as well + * as defaulting the X-Powered-By header field. * - * TODO: add a `localStorage` variable to explicitly enable/disable colors + * @param {Function} app + * @return {Function} + * @api private */ -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } +exports.init = function(app){ + return function expressInit(req, res, next){ + if (app.enabled('x-powered-by')) res.setHeader('X-Powered-By', 'Express'); + req.res = res; + res.req = req; + req.next = next; - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} + setPrototypeOf(req, app.request) + setPrototypeOf(res, app.response) -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + res.locals = res.locals || Object.create(null); -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } + next(); + }; }; -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return; - - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); +/***/ }), - args.splice(lastC, 0, c); -} +/***/ 79768: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} + /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private + * Module dependencies. */ -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} -} +var merge = __nccwpck_require__(44429) +var parseUrl = __nccwpck_require__(89808); +var qs = __nccwpck_require__(22760); /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private + * @param {Object} options + * @return {Function} + * @api public */ -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} +module.exports = function query(options) { + var opts = merge({}, options) + var queryparse = qs.parse; - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; + if (typeof options === 'function') { + queryparse = options; + opts = undefined; } - return r; -} - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ - -exports.enable(load()); + if (opts !== undefined && opts.allowPrototypes === undefined) { + // back-compat for qs module + opts.allowPrototypes = true; + } -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ + return function query(req, res, next){ + if (!req.query) { + var val = parseUrl(req).query; + req.query = queryparse(val, opts); + } -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} + next(); + }; +}; /***/ }), -/***/ 86991: -/***/ ((module, exports, __nccwpck_require__) => { - +/***/ 71260: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = __nccwpck_require__(27025); + /** - * The currently active debug mode names, and names to skip. + * Module dependencies. + * @private */ -exports.names = []; -exports.skips = []; +var accepts = __nccwpck_require__(83633); +var deprecate = __nccwpck_require__(18883)('express'); +var isIP = __nccwpck_require__(11631).isIP; +var typeis = __nccwpck_require__(71159); +var http = __nccwpck_require__(98605); +var fresh = __nccwpck_require__(83136); +var parseRange = __nccwpck_require__(26435); +var parse = __nccwpck_require__(89808); +var proxyaddr = __nccwpck_require__(80140); /** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + * Request prototype. + * @public */ -exports.formatters = {}; +var req = Object.create(http.IncomingMessage.prototype) /** - * Previous log timestamp. + * Module exports. + * @public */ -var prevTime; +module.exports = req /** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private + * Return request header. + * + * The `Referrer` header field is special-cased, + * both `Referrer` and `Referer` are interchangeable. + * + * Examples: + * + * req.get('Content-Type'); + * // => "text/plain" + * + * req.get('content-type'); + * // => "text/plain" + * + * req.get('Something'); + * // => undefined + * + * Aliased as `req.header()`. + * + * @param {String} name + * @return {String} + * @public */ -function selectColor(namespace) { - var hash = 0, i; +req.get = +req.header = function header(name) { + if (!name) { + throw new TypeError('name argument is required to req.get'); + } - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer + if (typeof name !== 'string') { + throw new TypeError('name must be a string to req.get'); } - return exports.colors[Math.abs(hash) % exports.colors.length]; -} + var lc = name.toLowerCase(); + + switch (lc) { + case 'referer': + case 'referrer': + return this.headers.referrer + || this.headers.referer; + default: + return this.headers[lc]; + } +}; /** - * Create a debugger with the given `namespace`. + * To do: update docs. * - * @param {String} namespace - * @return {Function} - * @api public + * Check if the given `type(s)` is acceptable, returning + * the best match when true, otherwise `undefined`, in which + * case you should respond with 406 "Not Acceptable". + * + * The `type` value may be a single MIME type string + * such as "application/json", an extension name + * such as "json", a comma-delimited list such as "json, html, text/plain", + * an argument list such as `"json", "html", "text/plain"`, + * or an array `["json", "html", "text/plain"]`. When a list + * or array is given, the _best_ match, if any is returned. + * + * Examples: + * + * // Accept: text/html + * req.accepts('html'); + * // => "html" + * + * // Accept: text/*, application/json + * req.accepts('html'); + * // => "html" + * req.accepts('text/html'); + * // => "text/html" + * req.accepts('json, text'); + * // => "json" + * req.accepts('application/json'); + * // => "application/json" + * + * // Accept: text/*, application/json + * req.accepts('image/png'); + * req.accepts('png'); + * // => undefined + * + * // Accept: text/*;q=.5, application/json + * req.accepts(['html', 'json']); + * req.accepts('html', 'json'); + * req.accepts('html, json'); + * // => "json" + * + * @param {String|Array} type(s) + * @return {String|Array|Boolean} + * @public */ -function createDebug(namespace) { - - function debug() { - // disabled? - if (!debug.enabled) return; - - var self = debug; +req.accepts = function(){ + var accept = accepts(this); + return accept.types.apply(accept, arguments); +}; - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; +/** + * Check if the given `encoding`s are accepted. + * + * @param {String} ...encoding + * @return {String|Array} + * @public + */ - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } +req.acceptsEncodings = function(){ + var accept = accepts(this); + return accept.encodings.apply(accept, arguments); +}; - args[0] = exports.coerce(args[0]); +req.acceptsEncoding = deprecate.function(req.acceptsEncodings, + 'req.acceptsEncoding: Use acceptsEncodings instead'); - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } +/** + * Check if the given `charset`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...charset + * @return {String|Array} + * @public + */ - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); +req.acceptsCharsets = function(){ + var accept = accepts(this); + return accept.charsets.apply(accept, arguments); +}; - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); +req.acceptsCharset = deprecate.function(req.acceptsCharsets, + 'req.acceptsCharset: Use acceptsCharsets instead'); - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); +/** + * Check if the given `lang`s are acceptable, + * otherwise you should respond with 406 "Not Acceptable". + * + * @param {String} ...lang + * @return {String|Array} + * @public + */ - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } +req.acceptsLanguages = function(){ + var accept = accepts(this); + return accept.languages.apply(accept, arguments); +}; - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); +req.acceptsLanguage = deprecate.function(req.acceptsLanguages, + 'req.acceptsLanguage: Use acceptsLanguages instead'); - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } +/** + * Parse Range header field, capping to the given `size`. + * + * Unspecified ranges such as "0-" require knowledge of your resource length. In + * the case of a byte range this is of course the total number of bytes. If the + * Range header field is not given `undefined` is returned, `-1` when unsatisfiable, + * and `-2` when syntactically invalid. + * + * When ranges are returned, the array has a "type" property which is the type of + * range that is required (most commonly, "bytes"). Each array element is an object + * with a "start" and "end" property for the portion of the range. + * + * The "combine" option can be set to `true` and overlapping & adjacent ranges + * will be combined into a single range. + * + * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3" + * should respond with 4 users when available, not 3. + * + * @param {number} size + * @param {object} [options] + * @param {boolean} [options.combine=false] + * @return {number|array} + * @public + */ - return debug; -} +req.range = function range(size, options) { + var range = this.get('Range'); + if (!range) return; + return parseRange(size, range, options); +}; /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. + * Return the value of param `name` when present or `defaultValue`. + * + * - Checks route placeholders, ex: _/user/:id_ + * - Checks body params, ex: id=12, {"id":12} + * - Checks query string params, ex: ?id=12 + * + * To utilize request bodies, `req.body` + * should be an object. This can be done by using + * the `bodyParser()` middleware. * - * @param {String} namespaces - * @api public + * @param {String} name + * @param {Mixed} [defaultValue] + * @return {String} + * @public */ -function enable(namespaces) { - exports.save(namespaces); +req.param = function param(name, defaultValue) { + var params = this.params || {}; + var body = this.body || {}; + var query = this.query || {}; - exports.names = []; - exports.skips = []; + var args = arguments.length === 1 + ? 'name' + : 'name, default'; + deprecate('req.param(' + args + '): Use req.params, req.body, or req.query instead'); - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; + if (null != params[name] && params.hasOwnProperty(name)) return params[name]; + if (null != body[name]) return body[name]; + if (null != query[name]) return query[name]; - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } -} + return defaultValue; +}; /** - * Disable debug output. + * Check if the incoming request contains the "Content-Type" + * header field, and it contains the give mime `type`. * - * @api public - */ - -function disable() { - exports.enable(''); -} - -/** - * Returns true if the given mode name is enabled, false otherwise. + * Examples: * - * @param {String} name - * @return {Boolean} - * @api public + * // With Content-Type: text/html; charset=utf-8 + * req.is('html'); + * req.is('text/html'); + * req.is('text/*'); + * // => true + * + * // When Content-Type is application/json + * req.is('json'); + * req.is('application/json'); + * req.is('application/*'); + * // => true + * + * req.is('html'); + * // => false + * + * @param {String|Array} types... + * @return {String|false|null} + * @public */ -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; +req.is = function is(types) { + var arr = types; + + // support flattened arguments + if (!Array.isArray(types)) { + arr = new Array(arguments.length); + for (var i = 0; i < arr.length; i++) { + arr[i] = arguments[i]; } } - return false; -} + + return typeis(this, arr); +}; /** - * Coerce `val`. + * Return the protocol string "http" or "https" + * when requested with TLS. When the "trust proxy" + * setting trusts the socket address, the + * "X-Forwarded-Proto" header field will be trusted + * and used if present. * - * @param {Mixed} val - * @return {Mixed} - * @api private + * If you're running behind a reverse proxy that + * supplies https for you this may be enabled. + * + * @return {String} + * @public */ -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} +defineGetter(req, 'protocol', function protocol(){ + var proto = this.connection.encrypted + ? 'https' + : 'http'; + var trust = this.app.get('trust proxy fn'); + if (!trust(this.connection.remoteAddress, 0)) { + return proto; + } -/***/ }), + // Note: X-Forwarded-Proto is normally only ever a + // single value, but this is to be safe. + var header = this.get('X-Forwarded-Proto') || proto + var index = header.indexOf(',') -/***/ 52529: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return index !== -1 + ? header.substring(0, index).trim() + : header.trim() +}); /** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. + * Short-hand for: + * + * req.protocol === 'https' + * + * @return {Boolean} + * @public */ -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(36654); -} else { - module.exports = __nccwpck_require__(25696); -} - - -/***/ }), - -/***/ 25696: -/***/ ((module, exports, __nccwpck_require__) => { +defineGetter(req, 'secure', function secure(){ + return this.protocol === 'https'; +}); /** - * Module dependencies. + * Return the remote address from the trusted proxy. + * + * The is the remote address on the socket unless + * "trust proxy" is set. + * + * @return {String} + * @public */ -var tty = __nccwpck_require__(33867); -var util = __nccwpck_require__(31669); +defineGetter(req, 'ip', function ip(){ + var trust = this.app.get('trust proxy fn'); + return proxyaddr(this, trust); +}); /** - * This is the Node.js implementation of `debug()`. + * When "trust proxy" is set, trusted proxy addresses + client. * - * Expose `debug()` as the module. + * For example if the value were "client, proxy1, proxy2" + * you would receive the array `["client", "proxy1", "proxy2"]` + * where "proxy2" is the furthest down-stream and "proxy1" and + * "proxy2" were trusted. + * + * @return {Array} + * @public */ -exports = module.exports = __nccwpck_require__(86991); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; +defineGetter(req, 'ips', function ips() { + var trust = this.app.get('trust proxy fn'); + var addrs = proxyaddr.all(this, trust); -/** - * Colors. - */ + // reverse the order (to farthest -> closest) + // and remove socket address + addrs.reverse().pop() -exports.colors = [6, 2, 3, 4, 5, 1]; + return addrs +}); /** - * Build up the default `inspectOpts` object from the environment variables. + * Return subdomains as an array. * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * Subdomains are the dot-separated parts of the host before the main domain of + * the app. By default, the domain of the app is assumed to be the last two + * parts of the host. This can be changed by setting "subdomain offset". + * + * For example, if the domain is "tobi.ferrets.example.com": + * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. + * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. + * + * @return {Array} + * @public */ -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); +defineGetter(req, 'subdomains', function subdomains() { + var hostname = this.hostname; - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); + if (!hostname) return []; - obj[prop] = val; - return obj; -}, {}); + var offset = this.app.get('subdomain offset'); + var subdomains = !isIP(hostname) + ? hostname.split('.').reverse() + : [hostname]; + + return subdomains.slice(offset); +}); /** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * Short-hand for `url.parse(req.url).pathname`. * - * $ DEBUG_FD=3 node script.js 3>debug.log + * @return {String} + * @public */ -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - -if (1 !== fd && 2 !== fd) { - util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() -} - -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); +defineGetter(req, 'path', function path() { + return parse(this).pathname; +}); /** - * Is stdout a TTY? Colored output is enabled when `true`. + * Parse the "Host" header field to a hostname. + * + * When the "trust proxy" setting trusts the socket + * address, the "X-Forwarded-Host" header field will + * be trusted. + * + * @return {String} + * @public */ -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); -} +defineGetter(req, 'hostname', function hostname(){ + var trust = this.app.get('trust proxy fn'); + var host = this.get('X-Forwarded-Host'); -/** - * Map %o to `util.inspect()`, all on a single line. - */ + if (!host || !trust(this.connection.remoteAddress, 0)) { + host = this.get('Host'); + } else if (host.indexOf(',') !== -1) { + // Note: X-Forwarded-Host is normally only ever a + // single value, but this is to be safe. + host = host.substring(0, host.indexOf(',')).trimRight() + } -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; + if (!host) return; -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ + // IPv6 literal support + var offset = host[0] === '[' + ? host.indexOf(']') + 1 + : 0; + var index = host.indexOf(':', offset); -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; + return index !== -1 + ? host.substring(0, index) + : host; +}); + +// TODO: change req.host to return host in next major + +defineGetter(req, 'host', deprecate.function(function host(){ + return this.hostname; +}, 'req.host: Use req.hostname instead')); /** - * Adds ANSI color escape codes if enabled. + * Check if the request is fresh, aka + * Last-Modified and/or the ETag + * still match. * - * @api public + * @return {Boolean} + * @public */ -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; +defineGetter(req, 'fresh', function(){ + var method = this.method; + var res = this.res + var status = res.statusCode - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + // GET or HEAD for weak freshness validation only + if ('GET' !== method && 'HEAD' !== method) return false; - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; + // 2xx or 304 as per rfc2616 14.26 + if ((status >= 200 && status < 300) || 304 === status) { + return fresh(this.headers, { + 'etag': res.get('ETag'), + 'last-modified': res.get('Last-Modified') + }) } -} - -/** - * Invokes `util.format()` with the specified arguments and writes to `stream`. - */ -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); -} + return false; +}); /** - * Save `namespaces`. + * Check if the request is stale, aka + * "Last-Modified" and / or the "ETag" for the + * resource has changed. * - * @param {String} namespaces - * @api private + * @return {Boolean} + * @public */ -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } -} +defineGetter(req, 'stale', function stale(){ + return !this.fresh; +}); /** - * Load `namespaces`. + * Check if the request was an _XMLHttpRequest_. * - * @return {String} returns the previously persisted debug modes - * @api private + * @return {Boolean} + * @public */ -function load() { - return process.env.DEBUG; -} +defineGetter(req, 'xhr', function xhr(){ + var val = this.get('X-Requested-With') || ''; + return val.toLowerCase() === 'xmlhttprequest'; +}); /** - * Copied from `node/src/node.js`. + * Helper function for creating a getter on an object. * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + * @param {Object} obj + * @param {String} name + * @param {Function} getter + * @private */ +function defineGetter(obj, name, getter) { + Object.defineProperty(obj, name, { + configurable: true, + enumerable: true, + get: getter + }); +} -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); - - // Note stream._type is used for test-module-load-list.js - - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; - - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; - - case 'FILE': - var fs = __nccwpck_require__(35747); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; - - case 'PIPE': - case 'TCP': - var net = __nccwpck_require__(11631); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); - - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; +/***/ }), - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } +/***/ 64934: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // For supporting legacy API we put the FD here. - stream.fd = fd; +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - stream._isStdio = true; - return stream; -} /** - * Init logic for `debug` instances. - * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * Module dependencies. + * @private */ -function init (debug) { - debug.inspectOpts = {}; - - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} +var Buffer = __nccwpck_require__(41894).Buffer +var contentDisposition = __nccwpck_require__(53921); +var deprecate = __nccwpck_require__(18883)('express'); +var encodeUrl = __nccwpck_require__(16592); +var escapeHtml = __nccwpck_require__(94070); +var http = __nccwpck_require__(98605); +var isAbsolute = __nccwpck_require__(53561).isAbsolute; +var onFinished = __nccwpck_require__(92098); +var path = __nccwpck_require__(85622); +var statuses = __nccwpck_require__(57415) +var merge = __nccwpck_require__(44429); +var sign = __nccwpck_require__(61579).sign; +var normalizeType = __nccwpck_require__(53561).normalizeType; +var normalizeTypes = __nccwpck_require__(53561).normalizeTypes; +var setCharset = __nccwpck_require__(53561).setCharset; +var cookie = __nccwpck_require__(66515); +var send = __nccwpck_require__(95287); +var extname = path.extname; +var mime = send.mime; +var resolve = path.resolve; +var vary = __nccwpck_require__(85931); /** - * Enable namespaces listed in `process.env.DEBUG` initially. + * Response prototype. + * @public */ -exports.enable(load()); - +var res = Object.create(http.ServerResponse.prototype) -/***/ }), +/** + * Module exports. + * @public + */ -/***/ 27025: -/***/ ((module) => { +module.exports = res /** - * Helpers. + * Module variables. + * @private */ -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; +var charsetRegExp = /;\s*charset\s*=/; /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] + * Set status `code`. * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public + * @param {Number} code + * @return {ServerResponse} + * @public */ -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); - } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); +res.status = function status(code) { + this.statusCode = code; + return this; }; /** - * Parse the given `str` and return milliseconds. + * Set Link header field with the given `links`. * - * @param {String} str - * @return {Number} - * @api private + * Examples: + * + * res.links({ + * next: 'http://api.example.com/users?page=2', + * last: 'http://api.example.com/users?page=5' + * }); + * + * @param {Object} links + * @return {ServerResponse} + * @public */ -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; - } -} +res.links = function(links){ + var link = this.get('Link') || ''; + if (link) link += ', '; + return this.set('Link', link + Object.keys(links).map(function(rel){ + return '<' + links[rel] + '>; rel="' + rel + '"'; + }).join(', ')); +}; /** - * Short format for `ms`. + * Send a response. * - * @param {Number} ms - * @return {String} - * @api private + * Examples: + * + * res.send(Buffer.from('wahoo')); + * res.send({ some: 'json' }); + * res.send('

some html

'); + * + * @param {string|number|boolean|object|Buffer} body + * @public */ -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; +res.send = function send(body) { + var chunk = body; + var encoding; + var req = this.req; + var type; + + // settings + var app = this.app; + + // allow status / body + if (arguments.length === 2) { + // res.send(body, status) backwards compat + if (typeof arguments[0] !== 'number' && typeof arguments[1] === 'number') { + deprecate('res.send(body, status): Use res.status(status).send(body) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.send(status, body): Use res.status(status).send(body) instead'); + this.statusCode = arguments[0]; + chunk = arguments[1]; + } } - if (ms >= m) { - return Math.round(ms / m) + 'm'; + + // disambiguate res.send(status) and res.send(status, num) + if (typeof chunk === 'number' && arguments.length === 1) { + // res.send(status) will set status message as text string + if (!this.get('Content-Type')) { + this.type('txt'); + } + + deprecate('res.send(status): Use res.sendStatus(status) instead'); + this.statusCode = chunk; + chunk = statuses[chunk] } - if (ms >= s) { - return Math.round(ms / s) + 's'; + + switch (typeof chunk) { + // string defaulting to html + case 'string': + if (!this.get('Content-Type')) { + this.type('html'); + } + break; + case 'boolean': + case 'number': + case 'object': + if (chunk === null) { + chunk = ''; + } else if (Buffer.isBuffer(chunk)) { + if (!this.get('Content-Type')) { + this.type('bin'); + } + } else { + return this.json(chunk); + } + break; } - return ms + 'ms'; -} -/** - * Long format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private - */ + // write strings in utf-8 + if (typeof chunk === 'string') { + encoding = 'utf8'; + type = this.get('Content-Type'); -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} + // reflect this in content-type + if (typeof type === 'string') { + this.set('Content-Type', setCharset(type, 'utf-8')); + } + } -/** - * Pluralization helper. - */ + // determine if ETag should be generated + var etagFn = app.get('etag fn') + var generateETag = !this.get('ETag') && typeof etagFn === 'function' -function plural(ms, n, name) { - if (ms < n) { - return; + // populate Content-Length + var len + if (chunk !== undefined) { + if (Buffer.isBuffer(chunk)) { + // get length of Buffer + len = chunk.length + } else if (!generateETag && chunk.length < 1000) { + // just calculate length when no ETag + small chunk + len = Buffer.byteLength(chunk, encoding) + } else { + // convert chunk to Buffer and calculate + chunk = Buffer.from(chunk, encoding) + encoding = undefined; + len = chunk.length + } + + this.set('Content-Length', len); } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; + + // populate ETag + var etag; + if (generateETag && len !== undefined) { + if ((etag = etagFn(chunk, encoding))) { + this.set('ETag', etag); + } } - return Math.ceil(ms / n) + ' ' + name + 's'; -} + // freshness + if (req.fresh) this.statusCode = 304; -/***/ }), + // strip irrelevant headers + if (204 === this.statusCode || 304 === this.statusCode) { + this.removeHeader('Content-Type'); + this.removeHeader('Content-Length'); + this.removeHeader('Transfer-Encoding'); + chunk = ''; + } -/***/ 24826: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (req.method === 'HEAD') { + // skip body for HEAD + this.end(); + } else { + // respond + this.end(chunk, encoding); + } -"use strict"; + return this; +}; +/** + * Send JSON response. + * + * Examples: + * + * res.json(null); + * res.json({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ -const validator = __nccwpck_require__(74174) -const parse = __nccwpck_require__(96214) -const redactor = __nccwpck_require__(17333) -const restorer = __nccwpck_require__(98806) -const { groupRedact, nestedRedact } = __nccwpck_require__(54865) -const state = __nccwpck_require__(41012) -const rx = __nccwpck_require__(9158) -const validate = validator() -const noop = (o) => o -noop.restore = noop +res.json = function json(obj) { + var val = obj; -const DEFAULT_CENSOR = '[REDACTED]' -fastRedact.rx = rx -fastRedact.validator = validator + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.json(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.json(status, obj): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } -module.exports = fastRedact + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) -function fastRedact (opts = {}) { - const paths = Array.from(new Set(opts.paths || [])) - const serialize = 'serialize' in opts ? ( - opts.serialize === false ? opts.serialize - : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify) - ) : JSON.stringify - const remove = opts.remove - if (remove === true && serialize !== JSON.stringify) { - throw Error('fast-redact – remove option may only be set when serializer is JSON.stringify') + // content-type + if (!this.get('Content-Type')) { + this.set('Content-Type', 'application/json'); } - const censor = remove === true - ? undefined - : 'censor' in opts ? opts.censor : DEFAULT_CENSOR - const isCensorFct = typeof censor === 'function' - const censorFctTakesPath = isCensorFct && censor.length > 1 + return this.send(body); +}; - if (paths.length === 0) return serialize || noop +/** + * Send JSON response with JSONP callback support. + * + * Examples: + * + * res.jsonp(null); + * res.jsonp({ user: 'tj' }); + * + * @param {string|number|boolean|object} obj + * @public + */ - validate({ paths, serialize, censor }) +res.jsonp = function jsonp(obj) { + var val = obj; - const { wildcards, wcLen, secret } = parse({ paths, censor }) + // allow status / body + if (arguments.length === 2) { + // res.json(body, status) backwards compat + if (typeof arguments[1] === 'number') { + deprecate('res.jsonp(obj, status): Use res.status(status).json(obj) instead'); + this.statusCode = arguments[1]; + } else { + deprecate('res.jsonp(status, obj): Use res.status(status).jsonp(obj) instead'); + this.statusCode = arguments[0]; + val = arguments[1]; + } + } - const compileRestore = restorer({ secret, wcLen }) - const strict = 'strict' in opts ? opts.strict : true + // settings + var app = this.app; + var escape = app.get('json escape') + var replacer = app.get('json replacer'); + var spaces = app.get('json spaces'); + var body = stringify(val, replacer, spaces, escape) + var callback = this.req.query[app.get('jsonp callback name')]; - return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({ - secret, - censor, - compileRestore, - serialize, - groupRedact, - nestedRedact, - wildcards, - wcLen - })) -} + // content-type + if (!this.get('Content-Type')) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'application/json'); + } + // fixup callback + if (Array.isArray(callback)) { + callback = callback[0]; + } -/***/ }), + // jsonp + if (typeof callback === 'string' && callback.length !== 0) { + this.set('X-Content-Type-Options', 'nosniff'); + this.set('Content-Type', 'text/javascript'); -/***/ 54865: -/***/ ((module) => { + // restrict callback charset + callback = callback.replace(/[^\[\]\w$.]/g, ''); -"use strict"; + // replace chars not allowed in JavaScript that are in JSON + body = body + .replace(/\u2028/g, '\\u2028') + .replace(/\u2029/g, '\\u2029'); + // the /**/ is a specific security mitigation for "Rosetta Flash JSONP abuse" + // the typeof check is just to reduce client error noise + body = '/**/ typeof ' + callback + ' === \'function\' && ' + callback + '(' + body + ');'; + } -module.exports = { - groupRedact, - groupRestore, - nestedRedact, - nestedRestore -} + return this.send(body); +}; -function groupRestore ({ keys, values, target }) { - if (target == null) return - const length = keys.length - for (var i = 0; i < length; i++) { - const k = keys[i] - target[k] = values[i] - } -} +/** + * Send given HTTP status code. + * + * Sets the response status to `statusCode` and the body of the + * response to the standard description from node's http.STATUS_CODES + * or the statusCode number if no description. + * + * Examples: + * + * res.sendStatus(200); + * + * @param {number} statusCode + * @public + */ -function groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) { - const target = get(o, path) - if (target == null) return { keys: null, values: null, target: null, flat: true } - const keys = Object.keys(target) - const keysLength = keys.length - const pathLength = path.length - const pathWithKey = censorFctTakesPath ? [...path] : undefined - const values = new Array(keysLength) +res.sendStatus = function sendStatus(statusCode) { + var body = statuses[statusCode] || String(statusCode) - for (var i = 0; i < keysLength; i++) { - const key = keys[i] - values[i] = target[key] + this.statusCode = statusCode; + this.type('txt'); - if (censorFctTakesPath) { - pathWithKey[pathLength] = key - target[key] = censor(target[key], pathWithKey) - } else if (isCensorFct) { - target[key] = censor(target[key]) - } else { - target[key] = censor - } + return this.send(body); +}; + +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendFile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendFile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendFile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendFile = function sendFile(path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + if (!path) { + throw new TypeError('path argument is required to res.sendFile'); } - return { keys, values, target, flat: true } -} -function nestedRestore (arr) { - const length = arr.length - for (var i = 0; i < length; i++) { - const { key, target, value } = arr[i] - target[key] = value + if (typeof path !== 'string') { + throw new TypeError('path must be a string to res.sendFile') } -} -function nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) { - const target = get(o, path) - if (target == null) return - const keys = Object.keys(target) - const keysLength = keys.length - for (var i = 0; i < keysLength; i++) { - const key = keys[i] - const { value, parent, exists } = - specialSet(target, key, path, ns, censor, isCensorFct, censorFctTakesPath) + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } - if (exists === true && parent !== null) { - store.push({ key: ns[ns.length - 1], target: parent, value }) - } + if (!opts.root && !isAbsolute(path)) { + throw new TypeError('path must be absolute or specify root to res.sendFile'); } - return store -} -function has (obj, prop) { - return Object.prototype.hasOwnProperty.call(obj, prop) -} + // create file stream + var pathname = encodeURI(path); + var file = send(req, pathname, opts); -function specialSet (o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) { - const afterPathLen = afterPath.length - const lastPathIndex = afterPathLen - 1 - const originalKey = k - var i = -1 - var n - var nv - var ov - var oov = null - var exists = true - ov = n = o[k] - if (typeof n !== 'object') return { value: null, parent: null, exists } - while (n != null && ++i < afterPathLen) { - k = afterPath[i] - oov = ov - if (!(k in n)) { - exists = false - break + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); + + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); } - ov = n[k] - nv = (i !== lastPathIndex) - ? ov - : (isCensorFct - ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov)) - : censor) - n[k] = (has(n, k) && nv === ov) || (nv === undefined && censor !== undefined) ? n[k] : nv - n = n[k] - if (typeof n !== 'object') break - } - return { value: ov, parent: oov, exists } -} + }); +}; -function get (o, p) { - var i = -1 - var l = p.length - var n = o - while (n != null && ++i < l) { - n = n[p[i]] +/** + * Transfer the file at the given `path`. + * + * Automatically sets the _Content-Type_ response header field. + * The callback `callback(err)` is invoked when the transfer is complete + * or when an error occurs. Be sure to check `res.sentHeader` + * if you wish to attempt responding, as the header and some data + * may have already been transferred. + * + * Options: + * + * - `maxAge` defaulting to 0 (can be string converted by `ms`) + * - `root` root directory for relative filenames + * - `headers` object of headers to serve with file + * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them + * + * Other options are passed along to `send`. + * + * Examples: + * + * The following example illustrates how `res.sendfile()` may + * be used as an alternative for the `static()` middleware for + * dynamic situations. The code backing `res.sendfile()` is actually + * the same code, so HTTP cache support etc is identical. + * + * app.get('/user/:uid/photos/:file', function(req, res){ + * var uid = req.params.uid + * , file = req.params.file; + * + * req.user.mayViewFilesFrom(uid, function(yes){ + * if (yes) { + * res.sendfile('/uploads/' + uid + '/' + file); + * } else { + * res.send(403, 'Sorry! you cant see that.'); + * } + * }); + * }); + * + * @public + */ + +res.sendfile = function (path, options, callback) { + var done = callback; + var req = this.req; + var res = this; + var next = req.next; + var opts = options || {}; + + // support function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; } - return n -} + // create file stream + var file = send(req, path, opts); -/***/ }), + // transfer + sendfile(res, file, opts, function (err) { + if (done) return done(err); + if (err && err.code === 'EISDIR') return next(); -/***/ 96214: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // next() all but write errors + if (err && err.code !== 'ECONNABORTED' && err.syscall !== 'write') { + next(err); + } + }); +}; -"use strict"; +res.sendfile = deprecate.function(res.sendfile, + 'res.sendfile: Use res.sendFile instead'); +/** + * Transfer the file at the given `path` as an attachment. + * + * Optionally providing an alternate attachment `filename`, + * and optional callback `callback(err)`. The callback is invoked + * when the data transfer is complete, or when an error has + * ocurred. Be sure to check `res.headersSent` if you plan to respond. + * + * Optionally providing an `options` object to use with `res.sendFile()`. + * This function will set the `Content-Disposition` header, overriding + * any `Content-Disposition` header passed as header options in order + * to set the attachment and filename. + * + * This method uses `res.sendFile()`. + * + * @public + */ -const rx = __nccwpck_require__(9158) +res.download = function download (path, filename, options, callback) { + var done = callback; + var name = filename; + var opts = options || null -module.exports = parse + // support function as second or third arg + if (typeof filename === 'function') { + done = filename; + name = null; + opts = null + } else if (typeof options === 'function') { + done = options + opts = null + } -function parse ({ paths }) { - const wildcards = [] - var wcLen = 0 - const secret = paths.reduce(function (o, strPath, ix) { - var path = strPath.match(rx).map((p) => p.replace(/'|"|`/g, '')) - const leadingBracket = strPath[0] === '[' - path = path.map((p) => { - if (p[0] === '[') return p.substr(1, p.length - 2) - else return p - }) - const star = path.indexOf('*') - if (star > -1) { - const before = path.slice(0, star) - const beforeStr = before.join('.') - const after = path.slice(star + 1, path.length) - if (after.indexOf('*') > -1) throw Error('fast-redact – Only one wildcard per path is supported') - const nested = after.length > 0 - wcLen++ - wildcards.push({ - before, - beforeStr, - after, - nested - }) - } else { - o[strPath] = { - path: path, - val: undefined, - precensored: false, - circle: '', - escPath: JSON.stringify(strPath), - leadingBracket: leadingBracket + // set Content-Disposition when file is sent + var headers = { + 'Content-Disposition': contentDisposition(name || path) + }; + + // merge user-provided headers + if (opts && opts.headers) { + var keys = Object.keys(opts.headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + if (key.toLowerCase() !== 'content-disposition') { + headers[key] = opts.headers[key] } } - return o - }, {}) + } - return { wildcards, wcLen, secret } -} + // merge user-provided options + opts = Object.create(opts) + opts.headers = headers + // Resolve the full path for sendFile + var fullPath = resolve(path); -/***/ }), + // send file + return this.sendFile(fullPath, opts, done) +}; -/***/ 17333: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/** + * Set _Content-Type_ response header with `type` through `mime.lookup()` + * when it does not contain "/", or set the Content-Type to `type` otherwise. + * + * Examples: + * + * res.type('.html'); + * res.type('html'); + * res.type('json'); + * res.type('application/json'); + * res.type('png'); + * + * @param {String} type + * @return {ServerResponse} for chaining + * @public + */ -"use strict"; +res.contentType = +res.type = function contentType(type) { + var ct = type.indexOf('/') === -1 + ? mime.lookup(type) + : type; + return this.set('Content-Type', ct); +}; -const rx = __nccwpck_require__(9158) +/** + * Respond to the Acceptable formats using an `obj` + * of mime-type callbacks. + * + * This method uses `req.accepted`, an array of + * acceptable types ordered by their quality values. + * When "Accept" is not present the _first_ callback + * is invoked, otherwise the first match is used. When + * no match is performed the server responds with + * 406 "Not Acceptable". + * + * Content-Type is set for you, however if you choose + * you may alter this within the callback using `res.type()` + * or `res.set('Content-Type', ...)`. + * + * res.format({ + * 'text/plain': function(){ + * res.send('hey'); + * }, + * + * 'text/html': function(){ + * res.send('

hey

'); + * }, + * + * 'appliation/json': function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * In addition to canonicalized MIME types you may + * also use extnames mapped to these types: + * + * res.format({ + * text: function(){ + * res.send('hey'); + * }, + * + * html: function(){ + * res.send('

hey

'); + * }, + * + * json: function(){ + * res.send({ message: 'hey' }); + * } + * }); + * + * By default Express passes an `Error` + * with a `.status` of 406 to `next(err)` + * if a match is not made. If you provide + * a `.default` callback it will be invoked + * instead. + * + * @param {Object} obj + * @return {ServerResponse} for chaining + * @public + */ -module.exports = redactor +res.format = function(obj){ + var req = this.req; + var next = req.next; -function redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) { - /* eslint-disable-next-line */ - const redact = Function('o', ` - if (typeof o !== 'object' || o == null) { - ${strictImpl(strict, serialize)} - } - const { censor, secret } = this - ${redactTmpl(secret, isCensorFct, censorFctTakesPath)} - this.compileRestore() - ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)} - ${resultTmpl(serialize)} - `).bind(state) + var fn = obj.default; + if (fn) delete obj.default; + var keys = Object.keys(obj); - if (serialize === false) { - redact.restore = (o) => state.restore(o) + var key = keys.length > 0 + ? req.accepts(keys) + : false; + + this.vary("Accept"); + + if (key) { + this.set('Content-Type', normalizeType(key).value); + obj[key](req, this, next); + } else if (fn) { + fn(); + } else { + var err = new Error('Not Acceptable'); + err.status = err.statusCode = 406; + err.types = normalizeTypes(keys).map(function(o){ return o.value }); + next(err); } - return redact -} + return this; +}; -function redactTmpl (secret, isCensorFct, censorFctTakesPath) { - return Object.keys(secret).map((path) => { - const { escPath, leadingBracket, path: arrPath } = secret[path] - const skip = leadingBracket ? 1 : 0 - const delim = leadingBracket ? '' : '.' - const hops = [] - var match - while ((match = rx.exec(path)) !== null) { - const [ , ix ] = match - const { index, input } = match - if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1))) - } - var existence = hops.map((p) => `o${delim}${p}`).join(' && ') - if (existence.length === 0) existence += `o${delim}${path} != null` - else existence += ` && o${delim}${path} != null` +/** + * Set _Content-Disposition_ header to _attachment_ with optional `filename`. + * + * @param {String} filename + * @return {ServerResponse} + * @public + */ - const circularDetection = ` - switch (true) { - ${hops.reverse().map((p) => ` - case o${delim}${p} === censor: - secret[${escPath}].circle = ${JSON.stringify(p)} - break - `).join('\n')} - } - ` +res.attachment = function attachment(filename) { + if (filename) { + this.type(extname(filename)); + } - const censorArgs = censorFctTakesPath - ? `val, ${JSON.stringify(arrPath)}` - : `val` + this.set('Content-Disposition', contentDisposition(filename)); - return ` - if (${existence}) { - const val = o${delim}${path} - if (val === censor) { - secret[${escPath}].precensored = true - } else { - secret[${escPath}].val = val - o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'} - ${circularDetection} - } - } - ` - }).join('\n') -} + return this; +}; -function dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) { - return hasWildcards === true ? ` - { - const { wildcards, wcLen, groupRedact, nestedRedact } = this - for (var i = 0; i < wcLen; i++) { - const { before, beforeStr, after, nested } = wildcards[i] - if (nested === true) { - secret[beforeStr] = secret[beforeStr] || [] - nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath}) - } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath}) - } - } - ` : '' -} +/** + * Append additional header `field` with value `val`. + * + * Example: + * + * res.append('Link', ['', '']); + * res.append('Set-Cookie', 'foo=bar; Path=/; HttpOnly'); + * res.append('Warning', '199 Miscellaneous warning'); + * + * @param {String} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ -function resultTmpl (serialize) { - return serialize === false ? `return o` : ` - var s = this.serialize(o) - this.restore(o) - return s - ` -} +res.append = function append(field, val) { + var prev = this.get(field); + var value = val; -function strictImpl (strict, serialize) { - return strict === true - ? `throw Error('fast-redact: primitives cannot be redacted')` - : serialize === false ? `return o` : `return this.serialize(o)` -} + if (prev) { + // concat the new and prev vals + value = Array.isArray(prev) ? prev.concat(val) + : Array.isArray(val) ? [prev].concat(val) + : [prev, val]; + } + return this.set(field, value); +}; -/***/ }), +/** + * Set header `field` to `val`, or pass + * an object of header fields. + * + * Examples: + * + * res.set('Foo', ['bar', 'baz']); + * res.set('Accept', 'application/json'); + * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); + * + * Aliased as `res.header()`. + * + * @param {String|Object} field + * @param {String|Array} val + * @return {ServerResponse} for chaining + * @public + */ + +res.set = +res.header = function header(field, val) { + if (arguments.length === 2) { + var value = Array.isArray(val) + ? val.map(String) + : String(val); + + // add charset to content-type + if (field.toLowerCase() === 'content-type') { + if (Array.isArray(value)) { + throw new TypeError('Content-Type cannot be set to an Array'); + } + if (!charsetRegExp.test(value)) { + var charset = mime.charsets.lookup(value.split(';')[0]); + if (charset) value += '; charset=' + charset.toLowerCase(); + } + } -/***/ 98806: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + this.setHeader(field, value); + } else { + for (var key in field) { + this.set(key, field[key]); + } + } + return this; +}; -"use strict"; +/** + * Get value for header `field`. + * + * @param {String} field + * @return {String} + * @public + */ +res.get = function(field){ + return this.getHeader(field); +}; -const { groupRestore, nestedRestore } = __nccwpck_require__(54865) +/** + * Clear cookie `name`. + * + * @param {String} name + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public + */ -module.exports = restorer +res.clearCookie = function clearCookie(name, options) { + var opts = merge({ expires: new Date(1), path: '/' }, options); -function restorer ({ secret, wcLen }) { - return function compileRestore () { - if (this.restore) return - const paths = Object.keys(secret) - .filter((path) => secret[path].precensored === false) - const resetters = resetTmpl(secret, paths) - const hasWildcards = wcLen > 0 - const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret } - /* eslint-disable-next-line */ - this.restore = Function( - 'o', - restoreTmpl(resetters, paths, hasWildcards) - ).bind(state) - } -} + return this.cookie(name, '', opts); +}; /** - * Mutates the original object to be censored by restoring its original values - * prior to censoring. + * Set cookie `name` to `value`, with the given `options`. * - * @param {object} secret Compiled object describing which target fields should - * be censored and the field states. - * @param {string[]} paths The list of paths to censor as provided at - * initialization time. + * Options: * - * @returns {string} String of JavaScript to be used by `Function()`. The - * string compiles to the function that does the work in the description. + * - `maxAge` max-age in milliseconds, converted to `expires` + * - `signed` sign the cookie + * - `path` defaults to "/" + * + * Examples: + * + * // "Remember Me" for 15 minutes + * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); + * + * // same as above + * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) + * + * @param {String} name + * @param {String|Object} value + * @param {Object} [options] + * @return {ServerResponse} for chaining + * @public */ -function resetTmpl (secret, paths) { - return paths.map((path) => { - const { circle, escPath, leadingBracket } = secret[path] - const delim = leadingBracket ? '' : '.' - const reset = circle - ? `o.${circle} = secret[${escPath}].val` - : `o${delim}${path} = secret[${escPath}].val` - const clear = `secret[${escPath}].val = undefined` - return ` - if (secret[${escPath}].val !== undefined) { - try { ${reset} } catch (e) {} - ${clear} - } - ` - }).join('') -} -function restoreTmpl (resetters, paths, hasWildcards) { - const dynamicReset = hasWildcards === true ? ` - const keys = Object.keys(secret) - const len = keys.length - for (var i = ${paths.length}; i < len; i++) { - const k = keys[i] - const o = secret[k] - if (o.flat === true) this.groupRestore(o) - else this.nestedRestore(o) - secret[k] = null - } - ` : '' +res.cookie = function (name, value, options) { + var opts = merge({}, options); + var secret = this.req.secret; + var signed = opts.signed; - return ` - const secret = this.secret - ${resetters} - ${dynamicReset} - return o - ` -} + if (signed && !secret) { + throw new Error('cookieParser("secret") required for signed cookies'); + } + var val = typeof value === 'object' + ? 'j:' + JSON.stringify(value) + : String(value); -/***/ }), + if (signed) { + val = 's:' + sign(val, secret); + } -/***/ 9158: -/***/ ((module) => { + if ('maxAge' in opts) { + opts.expires = new Date(Date.now() + opts.maxAge); + opts.maxAge /= 1000; + } -"use strict"; + if (opts.path == null) { + opts.path = '/'; + } + this.append('Set-Cookie', cookie.serialize(name, String(val), opts)); -module.exports = /[^.[\]]+|\[((?:.)*?)\]/g + return this; +}; -/* -Regular expression explanation: +/** + * Set the location header to `url`. + * + * The given `url` can also be "back", which redirects + * to the _Referrer_ or _Referer_ headers or "/". + * + * Examples: + * + * res.location('/foo/bar').; + * res.location('http://example.com'); + * res.location('../login'); + * + * @param {String} url + * @return {ServerResponse} for chaining + * @public + */ -Alt 1: /[^.[\]]+/ - Match one or more characters that are *not* a dot (.) - opening square bracket ([) or closing square bracket (]) +res.location = function location(url) { + var loc = url; -Alt 2: /\[((?:.)*?)\]/ - If the char IS dot or square bracket, then create a capture - group (which will be capture group $1) that matches anything - within square brackets. Expansion is lazy so it will - stop matching as soon as the first closing bracket is met `]` - (rather than continuing to match until the final closing bracket). -*/ + // "back" is an alias for the referrer + if (url === 'back') { + loc = this.req.get('Referrer') || '/'; + } + // set location + return this.set('Location', encodeUrl(loc)); +}; -/***/ }), +/** + * Redirect to the given `url` with optional response `status` + * defaulting to 302. + * + * The resulting `url` is determined by `res.location()`, so + * it will play nicely with mounted apps, relative paths, + * `"back"` etc. + * + * Examples: + * + * res.redirect('/foo/bar'); + * res.redirect('http://example.com'); + * res.redirect(301, 'http://example.com'); + * res.redirect('../login'); // /blog/post/1 -> /blog/login + * + * @public + */ -/***/ 41012: -/***/ ((module) => { +res.redirect = function redirect(url) { + var address = url; + var body; + var status = 302; -"use strict"; + // allow status / url + if (arguments.length === 2) { + if (typeof arguments[0] === 'number') { + status = arguments[0]; + address = arguments[1]; + } else { + deprecate('res.redirect(url, status): Use res.redirect(status, url) instead'); + status = arguments[1]; + } + } + // Set location header + address = this.location(address).get('Location'); -module.exports = state + // Support text/{plain,html} by default + this.format({ + text: function(){ + body = statuses[status] + '. Redirecting to ' + address + }, -function state (o) { - const { - secret, - censor, - compileRestore, - serialize, - groupRedact, - nestedRedact, - wildcards, - wcLen - } = o - const builder = [{ secret, censor, compileRestore }] - if (serialize !== false) builder.push({ serialize }) - if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen }) - return Object.assign(...builder) -} + html: function(){ + var u = escapeHtml(address); + body = '

' + statuses[status] + '. Redirecting to ' + u + '

' + }, + default: function(){ + body = ''; + } + }); -/***/ }), + // Respond + this.statusCode = status; + this.set('Content-Length', Buffer.byteLength(body)); -/***/ 74174: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (this.req.method === 'HEAD') { + this.end(); + } else { + this.end(body); + } +}; -"use strict"; +/** + * Add `field` to Vary. If already present in the Vary set, then + * this call is simply ignored. + * + * @param {Array|String} field + * @return {ServerResponse} for chaining + * @public + */ +res.vary = function(field){ + // checks for back-compat + if (!field || (Array.isArray(field) && !field.length)) { + deprecate('res.vary(): Provide a field name'); + return this; + } -const { createContext, runInContext } = __nccwpck_require__(92184) + vary(this, field); -module.exports = validator + return this; +}; -function validator (opts = {}) { - const { - ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings', - ERR_INVALID_PATH = (s) => `fast-redact – Invalid path (${s})` - } = opts +/** + * Render `view` with the given `options` and optional callback `fn`. + * When a callback function is given a response will _not_ be made + * automatically, otherwise a response of _200_ and _text/html_ is given. + * + * Options: + * + * - `cache` boolean hinting to the engine it should cache + * - `filename` filename of the view being rendered + * + * @public + */ - return function validate ({ paths }) { - paths.forEach((s) => { - if (typeof s !== 'string') { - throw Error(ERR_PATHS_MUST_BE_STRINGS()) - } - try { - if (/〇/.test(s)) throw Error() - const proxy = new Proxy({}, { get: () => proxy, set: () => { throw Error() } }) - const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\*/, '〇').replace(/\.\*/g, '.〇').replace(/\[\*\]/g, '[〇]') - if (/\n|\r|;/.test(expr)) throw Error() - if (/\/\*/.test(expr)) throw Error() - runInContext(` - (function () { - 'use strict' - o${expr} - if ([o${expr}].length !== 1) throw Error() - })() - `, createContext({ o: proxy, 〇: null }), { - codeGeneration: { strings: false, wasm: false } - }) - } catch (e) { - throw Error(ERR_INVALID_PATH(s)) - } - }) - } -} +res.render = function render(view, options, callback) { + var app = this.req.app; + var done = callback; + var opts = options || {}; + var req = this.req; + var self = this; + // support callback function as second arg + if (typeof options === 'function') { + done = options; + opts = {}; + } -/***/ }), + // merge res.locals + opts._locals = self.locals; -/***/ 17676: -/***/ ((module) => { + // default callback to respond + done = done || function (err, str) { + if (err) return req.next(err); + self.send(str); + }; -module.exports = stringify -stringify.default = stringify -stringify.stable = deterministicStringify -stringify.stableStringify = deterministicStringify + // render + app.render(view, opts, done); +}; -var arr = [] -var replacerStack = [] +// pipe the send file stream +function sendfile(res, file, options, callback) { + var done = false; + var streaming; -// Regular stringify -function stringify (obj, replacer, spacer) { - decirc(obj, '', [], undefined) - var res - if (replacerStack.length === 0) { - res = JSON.stringify(obj, replacer, spacer) - } else { - res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) - } - while (arr.length !== 0) { - var part = arr.pop() - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]) - } else { - part[0][part[1]] = part[2] - } - } - return res -} -function decirc (val, k, stack, parent) { - var i - if (typeof val === 'object' && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) - if (propertyDescriptor.get !== undefined) { - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: '[Circular]' }) - arr.push([parent, k, val, propertyDescriptor]) - } else { - replacerStack.push([val, k]) - } - } else { - parent[k] = '[Circular]' - arr.push([parent, k, val]) - } - return - } - } - stack.push(val) - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - decirc(val[i], i, stack, val) - } - } else { - var keys = Object.keys(val) - for (i = 0; i < keys.length; i++) { - var key = keys[i] - decirc(val[key], key, stack, val) - } - } - stack.pop() - } -} + // request aborted + function onaborted() { + if (done) return; + done = true; -// Stable-stringify -function compareFunction (a, b) { - if (a < b) { - return -1 - } - if (a > b) { - return 1 + var err = new Error('Request aborted'); + err.code = 'ECONNABORTED'; + callback(err); } - return 0 -} -function deterministicStringify (obj, replacer, spacer) { - var tmp = deterministicDecirc(obj, '', [], undefined) || obj - var res - if (replacerStack.length === 0) { - res = JSON.stringify(tmp, replacer, spacer) - } else { - res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) - } - while (arr.length !== 0) { - var part = arr.pop() - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]) - } else { - part[0][part[1]] = part[2] - } - } - return res -} + // directory + function ondirectory() { + if (done) return; + done = true; -function deterministicDecirc (val, k, stack, parent) { - var i - if (typeof val === 'object' && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) - if (propertyDescriptor.get !== undefined) { - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: '[Circular]' }) - arr.push([parent, k, val, propertyDescriptor]) - } else { - replacerStack.push([val, k]) - } - } else { - parent[k] = '[Circular]' - arr.push([parent, k, val]) - } - return - } - } - if (typeof val.toJSON === 'function') { - return - } - stack.push(val) - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - deterministicDecirc(val[i], i, stack, val) - } - } else { - // Create a temporary object in the required way - var tmp = {} - var keys = Object.keys(val).sort(compareFunction) - for (i = 0; i < keys.length; i++) { - var key = keys[i] - deterministicDecirc(val[key], key, stack, val) - tmp[key] = val[key] - } - if (parent !== undefined) { - arr.push([parent, k, val]) - parent[k] = tmp - } else { - return tmp - } - } - stack.pop() + var err = new Error('EISDIR, read'); + err.code = 'EISDIR'; + callback(err); } -} -// wraps replacer function to handle values we couldn't replace -// and mark them as [Circular] -function replaceGetterValues (replacer) { - replacer = replacer !== undefined ? replacer : function (k, v) { return v } - return function (key, val) { - if (replacerStack.length > 0) { - for (var i = 0; i < replacerStack.length; i++) { - var part = replacerStack[i] - if (part[1] === key && part[0] === val) { - val = '[Circular]' - replacerStack.splice(i, 1) - break - } - } - } - return replacer.call(this, key, val) + // errors + function onerror(err) { + if (done) return; + done = true; + callback(err); } -} - - -/***/ }), - -/***/ 34578: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - -/* -Copyright (c) 2014 Petka Antonov -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: + // ended + function onend() { + if (done) return; + done = true; + callback(); + } -The above copyright notice and this permission notice shall be included in -all copies or substantial portions of the Software. + // file + function onfile() { + streaming = false; + } -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. -*/ -function Url() { - //For more efficient internal representation and laziness. - //The non-underscore versions of these properties are accessor functions - //defined on the prototype. - this._protocol = null; - this._href = ""; - this._port = -1; - this._query = null; + // finished + function onfinish(err) { + if (err && err.code === 'ECONNRESET') return onaborted(); + if (err) return onerror(err); + if (done) return; - this.auth = null; - this.slashes = null; - this.host = null; - this.hostname = null; - this.hash = null; - this.search = null; - this.pathname = null; + setImmediate(function () { + if (streaming !== false && !done) { + onaborted(); + return; + } - this._prependSlash = false; -} + if (done) return; + done = true; + callback(); + }); + } -var querystring = __nccwpck_require__(71191); + // streaming + function onstream() { + streaming = true; + } -Url.queryString = querystring; + file.on('directory', ondirectory); + file.on('end', onend); + file.on('error', onerror); + file.on('file', onfile); + file.on('stream', onstream); + onFinished(res, onfinish); -Url.prototype.parse = -function Url$parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) { - if (typeof str !== "string") { - throw new TypeError("Parameter 'url' must be a string, not " + - typeof str); - } - var start = 0; - var end = str.length - 1; + if (options.headers) { + // set headers on successful transfer + file.on('headers', function headers(res) { + var obj = options.headers; + var keys = Object.keys(obj); - //Trim leading and trailing ws - while (str.charCodeAt(start) <= 0x20 /*' '*/) start++; - while (str.charCodeAt(end) <= 0x20 /*' '*/) end--; + for (var i = 0; i < keys.length; i++) { + var k = keys[i]; + res.setHeader(k, obj[k]); + } + }); + } - start = this._parseProtocol(str, start, end); + // pipe + file.pipe(res); +} - //Javascript doesn't have host - if (this._protocol !== "javascript") { - start = this._parseHost(str, start, end, hostDenotesSlash); - var proto = this._protocol; - if (!this.hostname && - (this.slashes || (proto && !slashProtocols[proto]))) { - this.hostname = this.host = ""; - } - } +/** + * Stringify JSON, like JSON.stringify, but v8 optimized, with the + * ability to escape characters that can trigger HTML sniffing. + * + * @param {*} value + * @param {function} replaces + * @param {number} spaces + * @param {boolean} escape + * @returns {string} + * @private + */ - if (start <= end) { - var ch = str.charCodeAt(start); +function stringify (value, replacer, spaces, escape) { + // v8 checks arguments.length for optimizing simple call + // https://bugs.chromium.org/p/v8/issues/detail?id=4730 + var json = replacer || spaces + ? JSON.stringify(value, replacer, spaces) + : JSON.stringify(value); - if (ch === 0x2F /*'/'*/ || ch === 0x5C /*'\'*/) { - this._parsePath(str, start, end, disableAutoEscapeChars); - } - else if (ch === 0x3F /*'?'*/) { - this._parseQuery(str, start, end, disableAutoEscapeChars); - } - else if (ch === 0x23 /*'#'*/) { - this._parseHash(str, start, end, disableAutoEscapeChars); - } - else if (this._protocol !== "javascript") { - this._parsePath(str, start, end, disableAutoEscapeChars); - } - else { //For javascript the pathname is just the rest of it - this.pathname = str.slice(start, end + 1 ); - } + if (escape) { + json = json.replace(/[<>&]/g, function (c) { + switch (c.charCodeAt(0)) { + case 0x3c: + return '\\u003c' + case 0x3e: + return '\\u003e' + case 0x26: + return '\\u0026' + /* istanbul ignore next: unreachable default */ + default: + return c + } + }) + } - } + return json +} - if (!this.pathname && this.hostname && - this._slashProtocols[this._protocol]) { - this.pathname = "/"; - } - if (parseQueryString) { - var search = this.search; - if (search == null) { - search = this.search = ""; - } - if (search.charCodeAt(0) === 0x3F /*'?'*/) { - search = search.slice(1); - } - //This calls a setter function, there is no .query data property - this.query = Url.queryString.parse(search); - } -}; +/***/ }), -Url.prototype.resolve = function Url$resolve(relative) { - return this.resolveObject(Url.parse(relative, false, true)).format(); -}; +/***/ 24963: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -Url.prototype.format = function Url$format() { - var auth = this.auth || ""; +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - if (auth) { - auth = encodeURIComponent(auth); - auth = auth.replace(/%3A/i, ":"); - auth += "@"; - } - var protocol = this.protocol || ""; - var pathname = this.pathname || ""; - var hash = this.hash || ""; - var search = this.search || ""; - var query = ""; - var hostname = this.hostname || ""; - var port = this.port || ""; - var host = false; - var scheme = ""; - //Cache the result of the getter function - var q = this.query; - if (q && typeof q === "object") { - query = Url.queryString.stringify(q); - } +/** + * Module dependencies. + * @private + */ - if (!search) { - search = query ? "?" + query : ""; - } +var Route = __nccwpck_require__(23699); +var Layer = __nccwpck_require__(25624); +var methods = __nccwpck_require__(58752); +var mixin = __nccwpck_require__(44429); +var debug = __nccwpck_require__(52529)('express:router'); +var deprecate = __nccwpck_require__(18883)('express'); +var flatten = __nccwpck_require__(62003); +var parseUrl = __nccwpck_require__(89808); +var setPrototypeOf = __nccwpck_require__(40414) - if (protocol && protocol.charCodeAt(protocol.length - 1) !== 0x3A /*':'*/) - protocol += ":"; +/** + * Module variables. + * @private + */ - if (this.host) { - host = auth + this.host; - } - else if (hostname) { - var ip6 = hostname.indexOf(":") > -1; - if (ip6) hostname = "[" + hostname + "]"; - host = auth + hostname + (port ? ":" + port : ""); - } +var objectRegExp = /^\[object (\S+)\]$/; +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; - var slashes = this.slashes || - ((!protocol || - slashProtocols[protocol]) && host !== false); +/** + * Initialize a new `Router` with the given `options`. + * + * @param {Object} [options] + * @return {Router} which is an callable function + * @public + */ +var proto = module.exports = function(options) { + var opts = options || {}; - if (protocol) scheme = protocol + (slashes ? "//" : ""); - else if (slashes) scheme = "//"; + function router(req, res, next) { + router.handle(req, res, next); + } - if (slashes && pathname && pathname.charCodeAt(0) !== 0x2F /*'/'*/) { - pathname = "/" + pathname; - } - if (search && search.charCodeAt(0) !== 0x3F /*'?'*/) - search = "?" + search; - if (hash && hash.charCodeAt(0) !== 0x23 /*'#'*/) - hash = "#" + hash; + // mixin Router class functions + setPrototypeOf(router, proto) - pathname = escapePathName(pathname); - search = escapeSearch(search); + router.params = {}; + router._params = []; + router.caseSensitive = opts.caseSensitive; + router.mergeParams = opts.mergeParams; + router.strict = opts.strict; + router.stack = []; - return scheme + (host === false ? "" : host) + pathname + search + hash; + return router; }; -Url.prototype.resolveObject = function Url$resolveObject(relative) { - if (typeof relative === "string") - relative = Url.parse(relative, false, true); +/** + * Map the given param placeholder `name`(s) to the given callback. + * + * Parameter mapping is used to provide pre-conditions to routes + * which use normalized placeholders. For example a _:user_id_ parameter + * could automatically load a user's information from the database without + * any additional code, + * + * The callback uses the same signature as middleware, the only difference + * being that the value of the placeholder is passed, in this case the _id_ + * of the user. Once the `next()` function is invoked, just like middleware + * it will continue on to execute the route, or subsequent parameter functions. + * + * Just like in middleware, you must either respond to the request or call next + * to avoid stalling the request. + * + * app.param('user_id', function(req, res, next, id){ + * User.find(id, function(err, user){ + * if (err) { + * return next(err); + * } else if (!user) { + * return next(new Error('failed to load user')); + * } + * req.user = user; + * next(); + * }); + * }); + * + * @param {String} name + * @param {Function} fn + * @return {app} for chaining + * @public + */ - var result = this._clone(); +proto.param = function param(name, fn) { + // param logic + if (typeof name === 'function') { + deprecate('router.param(fn): Refactor to use path params'); + this._params.push(name); + return; + } - // hash is always overridden, no matter what. - // even href="" will remove it. - result.hash = relative.hash; + // apply param functions + var params = this._params; + var len = params.length; + var ret; - // if the relative url is empty, then there"s nothing left to do here. - if (!relative.href) { - result._href = ""; - return result; + if (name[0] === ':') { + deprecate('router.param(' + JSON.stringify(name) + ', fn): Use router.param(' + JSON.stringify(name.substr(1)) + ', fn) instead'); + name = name.substr(1); + } + + for (var i = 0; i < len; ++i) { + if (ret = params[i](name, fn)) { + fn = ret; } + } - // hrefs like //foo/bar always cut to the protocol. - if (relative.slashes && !relative._protocol) { - relative._copyPropsTo(result, true); + // ensure we end up with a + // middleware function + if ('function' !== typeof fn) { + throw new Error('invalid param() call for ' + name + ', got ' + fn); + } - if (slashProtocols[result._protocol] && - result.hostname && !result.pathname) { - result.pathname = "/"; - } - result._href = ""; - return result; - } + (this.params[name] = this.params[name] || []).push(fn); + return this; +}; - 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 (!slashProtocols[relative._protocol]) { - relative._copyPropsTo(result, false); - result._href = ""; - return result; - } +/** + * Dispatch a req, res into the router. + * @private + */ - result._protocol = relative._protocol; - if (!relative.host && relative._protocol !== "javascript") { - var 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; - } +proto.handle = function handle(req, res, out) { + var self = this; - result.search = relative.search; - result.host = relative.host || ""; - result.auth = relative.auth; - result.hostname = relative.hostname || relative.host; - result._port = relative._port; - result.slashes = result.slashes || relative.slashes; - result._href = ""; - return result; - } + debug('dispatching %s %s', req.method, req.url); - var isSourceAbs = - (result.pathname && result.pathname.charCodeAt(0) === 0x2F /*'/'*/); - var isRelAbs = ( - relative.host || - (relative.pathname && - relative.pathname.charCodeAt(0) === 0x2F /*'/'*/) - ); - var mustEndAbs = (isRelAbs || isSourceAbs || - (result.host && relative.pathname)); + var idx = 0; + var protohost = getProtohost(req.url) || '' + var removed = ''; + var slashAdded = false; + var paramcalled = {}; - var removeAllDots = mustEndAbs; + // store options for OPTIONS request + // only used if OPTIONS request + var options = []; - var srcPath = result.pathname && result.pathname.split("/") || []; - var relPath = relative.pathname && relative.pathname.split("/") || []; - var psychotic = result._protocol && !slashProtocols[result._protocol]; + // middleware and routes + var stack = self.stack; - // 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 = -1; - if (result.host) { - if (srcPath[0] === "") srcPath[0] = result.host; - else srcPath.unshift(result.host); - } - result.host = ""; - if (relative._protocol) { - relative.hostname = ""; - relative._port = -1; - if (relative.host) { - if (relPath[0] === "") relPath[0] = relative.host; - else relPath.unshift(relative.host); - } - relative.host = ""; - } - mustEndAbs = mustEndAbs && (relPath[0] === "" || srcPath[0] === ""); - } + // manage inter-router variables + var parentParams = req.params; + var parentUrl = req.baseUrl || ''; + var done = restore(out, req, 'baseUrl', 'next', 'params'); - if (isRelAbs) { - // it"s absolute. - result.host = relative.host ? - relative.host : result.host; - result.hostname = relative.hostname ? - relative.hostname : result.hostname; - result.search = relative.search; - 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; - } else if (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 especialy happens in cases like - //url.resolveObject("mailto:local1@domain1", "local2@domain2") - var 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._href = ""; - return result; - } + // setup next layer + req.next = next; - if (!srcPath.length) { - // no path at all. easy. - // we"ve already handled the other stuff above. - result.pathname = null; - result._href = ""; - return result; - } + // for options requests, respond with a default if nothing else responds + if (req.method === 'OPTIONS') { + done = wrap(done, function(old, err) { + if (err || options.length === 0) return old(err); + sendOptionsResponse(res, options, old); + }); + } - // 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) && (last === "." || last === "..") || - last === ""); + // setup basic req values + req.baseUrl = parentUrl; + req.originalUrl = req.originalUrl || req.url; - // 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--; - } - } + next(); - // if the path is allowed to go above the root, restore leading ..s - if (!mustEndAbs && !removeAllDots) { - for (; up--; up) { - srcPath.unshift(".."); - } - } + function next(err) { + var layerError = err === 'route' + ? null + : err; - if (mustEndAbs && srcPath[0] !== "" && - (!srcPath[0] || srcPath[0].charCodeAt(0) !== 0x2F /*'/'*/)) { - srcPath.unshift(""); + // remove added slash + if (slashAdded) { + req.url = req.url.substr(1); + slashAdded = false; } - if (hasTrailingSlash && (srcPath.join("/").substr(-1) !== "/")) { - srcPath.push(""); + // restore altered req.url + if (removed.length !== 0) { + req.baseUrl = parentUrl; + req.url = protohost + removed + req.url.substr(protohost.length); + removed = ''; } - var isAbsolute = srcPath[0] === "" || - (srcPath[0] && srcPath[0].charCodeAt(0) === 0x2F /*'/'*/); + // signal to exit router + if (layerError === 'router') { + setImmediate(done, null) + return + } - // 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 especialy happens in cases like - //url.resolveObject("mailto:local1@domain1", "local2@domain2") - var authInHost = result.host && result.host.indexOf("@") > 0 ? - result.host.split("@") : false; - if (authInHost) { - result.auth = authInHost.shift(); - result.host = result.hostname = authInHost.shift(); - } + // no more matching layers + if (idx >= stack.length) { + setImmediate(done, layerError); + return; } - mustEndAbs = mustEndAbs || (result.host && srcPath.length); + // get pathname of request + var path = getPathname(req); - if (mustEndAbs && !isAbsolute) { - srcPath.unshift(""); + if (path == null) { + return done(layerError); } - result.pathname = srcPath.length === 0 ? null : srcPath.join("/"); - result.auth = relative.auth || result.auth; - result.slashes = result.slashes || relative.slashes; - result._href = ""; - return result; -}; + // find next matching layer + var layer; + var match; + var route; -var punycode = __nccwpck_require__(94213); -Url.prototype._hostIdna = function Url$_hostIdna(hostname) { - // 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. - return punycode.toASCII(hostname); -}; + while (match !== true && idx < stack.length) { + layer = stack[idx++]; + match = matchLayer(layer, path); + route = layer.route; -var escapePathName = Url.prototype._escapePathName = -function Url$_escapePathName(pathname) { - if (!containsCharacter2(pathname, 0x23 /*'#'*/, 0x3F /*'?'*/)) { - return pathname; - } - //Avoid closure creation to keep this inlinable - return _escapePath(pathname); -}; + if (typeof match !== 'boolean') { + // hold on to layerError + layerError = layerError || match; + } -var escapeSearch = Url.prototype._escapeSearch = -function Url$_escapeSearch(search) { - if (!containsCharacter2(search, 0x23 /*'#'*/, -1)) return search; - //Avoid closure creation to keep this inlinable - return _escapeSearch(search); -}; + if (match !== true) { + continue; + } -Url.prototype._parseProtocol = function Url$_parseProtocol(str, start, end) { - var doLowerCase = false; - var protocolCharacters = this._protocolCharacters; + if (!route) { + // process non-route handlers normally + continue; + } - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); + if (layerError) { + // routes do not match with a pending error + match = false; + continue; + } - if (ch === 0x3A /*':'*/) { - var protocol = str.slice(start, i); - if (doLowerCase) protocol = protocol.toLowerCase(); - this._protocol = protocol; - return i + 1; - } - else if (protocolCharacters[ch] === 1) { - if (ch < 0x61 /*'a'*/) - doLowerCase = true; - } - else { - return start; - } + var method = req.method; + var has_method = route._handles_method(method); + + // build up automatic options response + if (!has_method && method === 'OPTIONS') { + appendMethods(options, route._options()); + } + // don't even bother matching route + if (!has_method && method !== 'HEAD') { + match = false; + continue; + } } - return start; -}; -Url.prototype._parseAuth = function Url$_parseAuth(str, start, end, decode) { - var auth = str.slice(start, end + 1); - if (decode) { - auth = decodeURIComponent(auth); + // no match + if (match !== true) { + return done(layerError); } - this.auth = auth; -}; -Url.prototype._parsePort = function Url$_parsePort(str, start, end) { - //Internal format is integer for more efficient parsing - //and for efficient trimming of leading zeros - var port = 0; - //Distinguish between :0 and : (no port number at all) - var hadChars = false; - var validPort = true; + // store route for dispatch on change + if (route) { + req.route = route; + } - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); + // Capture one-time layer values + req.params = self.mergeParams + ? mergeParams(layer.params, parentParams) + : layer.params; + var layerPath = layer.path; - if (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/) { - port = (10 * port) + (ch - 0x30 /*'0'*/); - hadChars = true; - } - else { - validPort = false; - if (ch === 0x5C/*'\'*/ || ch === 0x2F/*'/'*/) { - validPort = true; - } - break; - } + // this should be done for the layer + self.process_params(layer, paramcalled, req, res, function (err) { + if (err) { + return next(layerError || err); + } - } - if ((port === 0 && !hadChars) || !validPort) { - if (!validPort) { - this._port = -2; - } - return 0; - } + if (route) { + return layer.handle_request(req, res, next); + } - this._port = port; - return i - start; -}; + trim_prefix(layer, layerError, layerPath, path); + }); + } -Url.prototype._parseHost = -function Url$_parseHost(str, start, end, slashesDenoteHost) { - var hostEndingCharacters = this._hostEndingCharacters; - var first = str.charCodeAt(start); - var second = str.charCodeAt(start + 1); - if ((first === 0x2F /*'/'*/ || first === 0x5C /*'\'*/) && - (second === 0x2F /*'/'*/ || second === 0x5C /*'\'*/)) { - this.slashes = true; + function trim_prefix(layer, layerError, layerPath, path) { + if (layerPath.length !== 0) { + // Validate path breaks on a path separator + var c = path[layerPath.length] + if (c && c !== '/' && c !== '.') return next(layerError) - //The string starts with // - if (start === 0) { - //The string is just "//" - if (end < 2) return start; - //If slashes do not denote host and there is no auth, - //there is no host when the string starts with // - var hasAuth = - containsCharacter(str, 0x40 /*'@'*/, 2, hostEndingCharacters); - if (!hasAuth && !slashesDenoteHost) { - this.slashes = null; - return start; - } - } - //There is a host that starts after the // - start += 2; - } - //If there is no slashes, there is no hostname if - //1. there was no protocol at all - else if (!this._protocol || - //2. there was a protocol that requires slashes - //e.g. in 'http:asd' 'asd' is not a hostname - slashProtocols[this._protocol] - ) { - return start; - } + // Trim off the part of the url that matches the route + // middleware (.use stuff) needs to have the path stripped + debug('trim prefix (%s) from url %s', layerPath, req.url); + removed = layerPath; + req.url = protohost + req.url.substr(protohost.length + removed.length); - var doLowerCase = false; - var idna = false; - var hostNameStart = start; - var hostNameEnd = end; - var lastCh = -1; - var portLength = 0; - var charsAfterDot = 0; - var authNeedsDecoding = false; + // Ensure leading slash + if (!protohost && req.url[0] !== '/') { + req.url = '/' + req.url; + slashAdded = true; + } - var j = -1; + // Setup base URL (no trailing slash) + req.baseUrl = parentUrl + (removed[removed.length - 1] === '/' + ? removed.substring(0, removed.length - 1) + : removed); + } - //Find the last occurrence of an @-sign until hostending character is met - //also mark if decoding is needed for the auth portion - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); + debug('%s %s : %s', layer.name, layerPath, req.originalUrl); - if (ch === 0x40 /*'@'*/) { - j = i; - } - //This check is very, very cheap. Unneeded decodeURIComponent is very - //very expensive - else if (ch === 0x25 /*'%'*/) { - authNeedsDecoding = true; - } - else if (hostEndingCharacters[ch] === 1) { - break; - } + if (layerError) { + layer.handle_error(layerError, req, res, next); + } else { + layer.handle_request(req, res, next); } + } +}; - //@-sign was found at index j, everything to the left from it - //is auth part - if (j > -1) { - this._parseAuth(str, start, j - 1, authNeedsDecoding); - //hostname starts after the last @-sign - start = hostNameStart = j + 1; - } +/** + * Process any parameters for the layer. + * @private + */ - //Host name is starting with a [ - if (str.charCodeAt(start) === 0x5B /*'['*/) { - for (var i = start + 1; i <= end; ++i) { - var ch = str.charCodeAt(i); +proto.process_params = function process_params(layer, called, req, res, done) { + var params = this.params; - //Assume valid IP6 is between the brackets - if (ch === 0x5D /*']'*/) { - if (str.charCodeAt(i + 1) === 0x3A /*':'*/) { - portLength = this._parsePort(str, i + 2, end) + 1; - } - var hostname = str.slice(start + 1, i).toLowerCase(); - this.hostname = hostname; - this.host = this._port > 0 ? - "[" + hostname + "]:" + this._port : - "[" + hostname + "]"; - this.pathname = "/"; - return i + portLength + 1; - } - } - //Empty hostname, [ starts a path - return start; - } + // captured parameters from the layer, keys and values + var keys = layer.keys; - for (var i = start; i <= end; ++i) { - if (charsAfterDot > 62) { - this.hostname = this.host = str.slice(start, i); - return i; - } - var ch = str.charCodeAt(i); + // fast track + if (!keys || keys.length === 0) { + return done(); + } - if (ch === 0x3A /*':'*/) { - portLength = this._parsePort(str, i + 1, end) + 1; - hostNameEnd = i - 1; - break; - } - else if (ch < 0x61 /*'a'*/) { - if (ch === 0x2E /*'.'*/) { - //Node.js ignores this error - /* - if (lastCh === DOT || lastCh === -1) { - this.hostname = this.host = ""; - return start; - } - */ - charsAfterDot = -1; - } - else if (0x41 /*'A'*/ <= ch && ch <= 0x5A /*'Z'*/) { - doLowerCase = true; - } - //Valid characters other than ASCII letters -, _, +, 0-9 - else if (!(ch === 0x2D /*'-'*/ || - ch === 0x5F /*'_'*/ || - ch === 0x2B /*'+'*/ || - (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/)) - ) { - if (hostEndingCharacters[ch] === 0 && - this._noPrependSlashHostEnders[ch] === 0) { - this._prependSlash = true; - } - hostNameEnd = i - 1; - break; - } - } - else if (ch >= 0x7B /*'{'*/) { - if (ch <= 0x7E /*'~'*/) { - if (this._noPrependSlashHostEnders[ch] === 0) { - this._prependSlash = true; - } - hostNameEnd = i - 1; - break; - } - idna = true; - } - lastCh = ch; - charsAfterDot++; - } + var i = 0; + var name; + var paramIndex = 0; + var key; + var paramVal; + var paramCallbacks; + var paramCalled; - //Node.js ignores this error - /* - if (lastCh === DOT) { - hostNameEnd--; + // process params in order + // param callbacks can be async + function param(err) { + if (err) { + return done(err); } - */ - if (hostNameEnd + 1 !== start && - hostNameEnd - hostNameStart <= 256) { - var hostname = str.slice(hostNameStart, hostNameEnd + 1); - if (doLowerCase) hostname = hostname.toLowerCase(); - if (idna) hostname = this._hostIdna(hostname); - this.hostname = hostname; - this.host = this._port > 0 ? hostname + ":" + this._port : hostname; + if (i >= keys.length ) { + return done(); } - return hostNameEnd + 1 + portLength; - -}; + paramIndex = 0; + key = keys[i++]; + name = key.name; + paramVal = req.params[name]; + paramCallbacks = params[name]; + paramCalled = called[name]; -Url.prototype._copyPropsTo = function Url$_copyPropsTo(input, noProtocol) { - if (!noProtocol) { - input._protocol = this._protocol; + if (paramVal === undefined || !paramCallbacks) { + return param(); } - input._href = this._href; - input._port = this._port; - input._prependSlash = this._prependSlash; - input.auth = this.auth; - input.slashes = this.slashes; - input.host = this.host; - input.hostname = this.hostname; - input.hash = this.hash; - input.search = this.search; - input.pathname = this.pathname; -}; - -Url.prototype._clone = function Url$_clone() { - var ret = new Url(); - ret._protocol = this._protocol; - ret._href = this._href; - ret._port = this._port; - ret._prependSlash = this._prependSlash; - ret.auth = this.auth; - ret.slashes = this.slashes; - ret.host = this.host; - ret.hostname = this.hostname; - ret.hash = this.hash; - ret.search = this.search; - ret.pathname = this.pathname; - return ret; -}; -Url.prototype._getComponentEscaped = -function Url$_getComponentEscaped(str, start, end, isAfterQuery) { - var cur = start; - var i = start; - var ret = ""; - var autoEscapeMap = isAfterQuery ? - this._afterQueryAutoEscapeMap : this._autoEscapeMap; - for (; i <= end; ++i) { - var ch = str.charCodeAt(i); - var escaped = autoEscapeMap[ch]; + // param previously called with same value or error occurred + if (paramCalled && (paramCalled.match === paramVal + || (paramCalled.error && paramCalled.error !== 'route'))) { + // restore value + req.params[name] = paramCalled.value; - if (escaped !== "" && escaped !== undefined) { - if (cur < i) ret += str.slice(cur, i); - ret += escaped; - cur = i + 1; - } + // next param + return param(paramCalled.error); } - if (cur < i + 1) ret += str.slice(cur, i); - return ret; -}; -Url.prototype._parsePath = -function Url$_parsePath(str, start, end, disableAutoEscapeChars) { - var pathStart = start; - var pathEnd = end; - var escape = false; - var autoEscapeCharacters = this._autoEscapeCharacters; - var prePath = this._port === -2 ? "/:" : ""; + called[name] = paramCalled = { + error: null, + match: paramVal, + value: paramVal + }; - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); - if (ch === 0x23 /*'#'*/) { - this._parseHash(str, i, end, disableAutoEscapeChars); - pathEnd = i - 1; - break; - } - else if (ch === 0x3F /*'?'*/) { - this._parseQuery(str, i, end, disableAutoEscapeChars); - pathEnd = i - 1; - break; - } - else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { - escape = true; - } - } + paramCallback(); + } - if (pathStart > pathEnd) { - this.pathname = prePath === "" ? "/" : prePath; - return; - } + // single param callbacks + function paramCallback(err) { + var fn = paramCallbacks[paramIndex++]; - var path; - if (escape) { - path = this._getComponentEscaped(str, pathStart, pathEnd, false); + // store updated value + paramCalled.value = req.params[key.name]; + + if (err) { + // store error + paramCalled.error = err; + param(err); + return; } - else { - path = str.slice(pathStart, pathEnd + 1); + + if (!fn) return param(); + + try { + fn(req, res, paramCallback, paramVal, key.name); + } catch (e) { + paramCallback(e); } - this.pathname = prePath === "" - ? (this._prependSlash ? "/" + path : path) - : prePath + path; -}; + } -Url.prototype._parseQuery = function Url$_parseQuery(str, start, end, disableAutoEscapeChars) { - var queryStart = start; - var queryEnd = end; - var escape = false; - var autoEscapeCharacters = this._autoEscapeCharacters; + param(); +}; - for (var i = start; i <= end; ++i) { - var ch = str.charCodeAt(i); +/** + * Use the given middleware function, with optional path, defaulting to "/". + * + * Use (like `.all`) will run for any http METHOD, but it will not add + * handlers for those methods so OPTIONS requests will not consider `.use` + * functions even if they could respond. + * + * The other difference is that _route_ path is stripped and not visible + * to the handler function. The main effect of this feature is that mounted + * handlers can operate without any code changes regardless of the "prefix" + * pathname. + * + * @public + */ - if (ch === 0x23 /*'#'*/) { - this._parseHash(str, i, end, disableAutoEscapeChars); - queryEnd = i - 1; - break; - } - else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { - escape = true; - } - } +proto.use = function use(fn) { + var offset = 0; + var path = '/'; - if (queryStart > queryEnd) { - this.search = ""; - return; - } + // default path to '/' + // disambiguate router.use([fn]) + if (typeof fn !== 'function') { + var arg = fn; - var query; - if (escape) { - query = this._getComponentEscaped(str, queryStart, queryEnd, true); - } - else { - query = str.slice(queryStart, queryEnd + 1); + while (Array.isArray(arg) && arg.length !== 0) { + arg = arg[0]; } - this.search = query; -}; -Url.prototype._parseHash = function Url$_parseHash(str, start, end, disableAutoEscapeChars) { - if (start > end) { - this.hash = ""; - return; + // first arg is the path + if (typeof arg !== 'function') { + offset = 1; + path = fn; } + } - this.hash = disableAutoEscapeChars ? - str.slice(start, end + 1) : this._getComponentEscaped(str, start, end, true); -}; + var callbacks = flatten(slice.call(arguments, offset)); -Object.defineProperty(Url.prototype, "port", { - get: function() { - if (this._port >= 0) { - return ("" + this._port); - } - return null; - }, - set: function(v) { - if (v == null) { - this._port = -1; - } - else { - this._port = parseInt(v, 10); - } - } -}); + if (callbacks.length === 0) { + throw new TypeError('Router.use() requires a middleware function') + } -Object.defineProperty(Url.prototype, "query", { - get: function() { - var query = this._query; - if (query != null) { - return query; - } - var search = this.search; + for (var i = 0; i < callbacks.length; i++) { + var fn = callbacks[i]; - if (search) { - if (search.charCodeAt(0) === 0x3F /*'?'*/) { - search = search.slice(1); - } - if (search !== "") { - this._query = search; - return search; - } - } - return search; - }, - set: function(v) { - this._query = v; + if (typeof fn !== 'function') { + throw new TypeError('Router.use() requires a middleware function but got a ' + gettype(fn)) } -}); -Object.defineProperty(Url.prototype, "path", { - get: function() { - var p = this.pathname || ""; - var s = this.search || ""; - if (p || s) { - return p + s; - } - return (p == null && s) ? ("/" + s) : null; - }, - set: function() {} -}); + // add the middleware + debug('use %o %s', path, fn.name || '') -Object.defineProperty(Url.prototype, "protocol", { - get: function() { - var proto = this._protocol; - return proto ? proto + ":" : proto; - }, - set: function(v) { - if (typeof v === "string") { - var end = v.length - 1; - if (v.charCodeAt(end) === 0x3A /*':'*/) { - this._protocol = v.slice(0, end); - } - else { - this._protocol = v; - } - } - else if (v == null) { - this._protocol = null; - } - } -}); + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: false, + end: false + }, fn); -Object.defineProperty(Url.prototype, "href", { - get: function() { - var href = this._href; - if (!href) { - href = this._href = this.format(); - } - return href; - }, - set: function(v) { - this._href = v; - } -}); + layer.route = undefined; -Url.parse = function Url$Parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) { - if (str instanceof Url) return str; - var ret = new Url(); - ret.parse(str, !!parseQueryString, !!hostDenotesSlash, !!disableAutoEscapeChars); - return ret; -}; + this.stack.push(layer); + } -Url.format = function Url$Format(obj) { - if (typeof obj === "string") { - obj = Url.parse(obj); - } - if (!(obj instanceof Url)) { - return Url.prototype.format.call(obj); - } - return obj.format(); + return this; }; -Url.resolve = function Url$Resolve(source, relative) { - return Url.parse(source, false, true).resolve(relative); -}; +/** + * Create a new Route for the given path. + * + * Each route contains a separate middleware stack and VERB handlers. + * + * See the Route api documentation for details on adding handlers + * and middleware to routes. + * + * @param {String} path + * @return {Route} + * @public + */ -Url.resolveObject = function Url$ResolveObject(source, relative) { - if (!source) return relative; - return Url.parse(source, false, true).resolveObject(relative); +proto.route = function route(path) { + var route = new Route(path); + + var layer = new Layer(path, { + sensitive: this.caseSensitive, + strict: this.strict, + end: true + }, route.dispatch.bind(route)); + + layer.route = route; + + this.stack.push(layer); + return route; }; -function _escapePath(pathname) { - return pathname.replace(/[?#]/g, function(match) { - return encodeURIComponent(match); - }); +// create Router#VERB functions +methods.concat('all').forEach(function(method){ + proto[method] = function(path){ + var route = this.route(path) + route[method].apply(route, slice.call(arguments, 1)); + return this; + }; +}); + +// append methods to a list of methods +function appendMethods(list, addition) { + for (var i = 0; i < addition.length; i++) { + var method = addition[i]; + if (list.indexOf(method) === -1) { + list.push(method); + } + } } -function _escapeSearch(search) { - return search.replace(/#/g, function(match) { - return encodeURIComponent(match); - }); +// get pathname of request +function getPathname(req) { + try { + return parseUrl(req).pathname; + } catch (err) { + return undefined; + } } -//Search `char1` (integer code for a character) in `string` -//starting from `fromIndex` and ending at `string.length - 1` -//or when a stop character is found -function containsCharacter(string, char1, fromIndex, stopCharacterTable) { - var len = string.length; - for (var i = fromIndex; i < len; ++i) { - var ch = string.charCodeAt(i); +// Get get protocol + host for a URL +function getProtohost(url) { + if (typeof url !== 'string' || url.length === 0 || url[0] === '/') { + return undefined + } - if (ch === char1) { - return true; - } - else if (stopCharacterTable[ch] === 1) { - return false; - } - } - return false; -} + var searchIndex = url.indexOf('?') + var pathLength = searchIndex !== -1 + ? searchIndex + : url.length + var fqdnIndex = url.substr(0, pathLength).indexOf('://') -//See if `char1` or `char2` (integer codes for characters) -//is contained in `string` -function containsCharacter2(string, char1, char2) { - for (var i = 0, len = string.length; i < len; ++i) { - var ch = string.charCodeAt(i); - if (ch === char1 || ch === char2) return true; - } - return false; + return fqdnIndex !== -1 + ? url.substr(0, url.indexOf('/', 3 + fqdnIndex)) + : undefined } -//Makes an array of 128 uint8's which represent boolean values. -//Spec is an array of ascii code points or ascii code point ranges -//ranges are expressed as [start, end] +// get type for error message +function gettype(obj) { + var type = typeof obj; -//Create a table with the characters 0x30-0x39 (decimals '0' - '9') and -//0x7A (lowercaseletter 'z') as `true`: -// -//var a = makeAsciiTable([[0x30, 0x39], 0x7A]); -//a[0x30]; //1 -//a[0x15]; //0 -//a[0x35]; //1 -function makeAsciiTable(spec) { - var ret = new Uint8Array(128); - spec.forEach(function(item){ - if (typeof item === "number") { - ret[item] = 1; - } - else { - var start = item[0]; - var end = item[1]; - for (var j = start; j <= end; ++j) { - ret[j] = 1; - } - } - }); + if (type !== 'object') { + return type; + } - return ret; + // inspect [[Class]] for objects + return toString.call(obj) + .replace(objectRegExp, '$1'); } +/** + * Match path to a layer. + * + * @param {Layer} layer + * @param {string} path + * @private + */ -var autoEscape = ["<", ">", "\"", "`", " ", "\r", "\n", - "\t", "{", "}", "|", "\\", "^", "`", "'"]; +function matchLayer(layer, path) { + try { + return layer.match(path); + } catch (err) { + return err; + } +} -var autoEscapeMap = new Array(128); +// merge params with parent params +function mergeParams(params, parent) { + if (typeof parent !== 'object' || !parent) { + return params; + } + // make copy of parent for base + var obj = mixin({}, parent); + // simple non-numeric merging + if (!(0 in params) || !(0 in parent)) { + return mixin(obj, params); + } -for (var i = 0, len = autoEscapeMap.length; i < len; ++i) { - autoEscapeMap[i] = ""; -} + var i = 0; + var o = 0; -for (var i = 0, len = autoEscape.length; i < len; ++i) { - var c = autoEscape[i]; - var esc = encodeURIComponent(c); - if (esc === c) { - esc = escape(c); - } - autoEscapeMap[c.charCodeAt(0)] = esc; -} -var afterQueryAutoEscapeMap = autoEscapeMap.slice(); -autoEscapeMap[0x5C /*'\'*/] = "/"; + // determine numeric gaps + while (i in params) { + i++; + } -var slashProtocols = Url.prototype._slashProtocols = { - http: true, - https: true, - gopher: true, - file: true, - ftp: true, + while (o in parent) { + o++; + } - "http:": true, - "https:": true, - "gopher:": true, - "file:": true, - "ftp:": true -}; + // offset numeric indices in params before merge + for (i--; i >= 0; i--) { + params[i + o] = params[i]; -//Optimize back from normalized object caused by non-identifier keys -function f(){} -f.prototype = slashProtocols; + // create holes for the merge when necessary + if (i < o) { + delete params[i]; + } + } -Url.prototype._protocolCharacters = makeAsciiTable([ - [0x61 /*'a'*/, 0x7A /*'z'*/], - [0x41 /*'A'*/, 0x5A /*'Z'*/], - 0x2E /*'.'*/, 0x2B /*'+'*/, 0x2D /*'-'*/ -]); + return mixin(obj, params); +} -Url.prototype._hostEndingCharacters = makeAsciiTable([ - 0x23 /*'#'*/, 0x3F /*'?'*/, 0x2F /*'/'*/, 0x5C /*'\'*/ -]); +// restore obj props after function +function restore(fn, obj) { + var props = new Array(arguments.length - 2); + var vals = new Array(arguments.length - 2); -Url.prototype._autoEscapeCharacters = makeAsciiTable( - autoEscape.map(function(v) { - return v.charCodeAt(0); - }) -); + for (var i = 0; i < props.length; i++) { + props[i] = arguments[i + 2]; + vals[i] = obj[props[i]]; + } -//If these characters end a host name, the path will not be prepended a / -Url.prototype._noPrependSlashHostEnders = makeAsciiTable( - [ - "<", ">", "'", "`", " ", "\r", - "\n", "\t", "{", "}", "|", - "^", "`", "\"", "%", ";" - ].map(function(v) { - return v.charCodeAt(0); - }) -); + return function () { + // restore vals + for (var i = 0; i < props.length; i++) { + obj[props[i]] = vals[i]; + } -Url.prototype._autoEscapeMap = autoEscapeMap; -Url.prototype._afterQueryAutoEscapeMap = afterQueryAutoEscapeMap; + return fn.apply(this, arguments); + }; +} -module.exports = Url; +// send an OPTIONS response +function sendOptionsResponse(res, options, next) { + try { + var body = options.join(','); + res.set('Allow', body); + res.send(body); + } catch (err) { + next(err); + } +} -Url.replace = function Url$Replace() { - require.cache.url = { - exports: Url - }; -}; +// wrap a function +function wrap(old, fn) { + return function proxy() { + var args = new Array(arguments.length + 1); + + args[0] = old; + for (var i = 0, len = arguments.length; i < len; i++) { + args[i + 1] = arguments[i]; + } + + fn.apply(this, args); + }; +} /***/ }), -/***/ 30810: +/***/ 25624: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; /*! - * finalhandler - * Copyright(c) 2014-2017 Douglas Christopher Wilson + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson * MIT Licensed */ @@ -50488,43921 +53644,47725 @@ Url.replace = function Url$Replace() { * @private */ -var debug = __nccwpck_require__(65612)('finalhandler') -var encodeUrl = __nccwpck_require__(16592) -var escapeHtml = __nccwpck_require__(94070) -var onFinished = __nccwpck_require__(92098) -var parseUrl = __nccwpck_require__(89808) -var statuses = __nccwpck_require__(57415) -var unpipe = __nccwpck_require__(3124) - -/** - * Module variables. - * @private - */ - -var DOUBLE_SPACE_REGEXP = /\x20{2}/g -var NEWLINE_REGEXP = /\n/g - -/* istanbul ignore next */ -var defer = typeof setImmediate === 'function' - ? setImmediate - : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } -var isFinished = onFinished.isFinished +var pathRegexp = __nccwpck_require__(37819); +var debug = __nccwpck_require__(52529)('express:router:layer'); /** - * Create a minimal HTML document. - * - * @param {string} message + * Module variables. * @private */ -function createHtmlDocument (message) { - var body = escapeHtml(message) - .replace(NEWLINE_REGEXP, '
') - .replace(DOUBLE_SPACE_REGEXP, '  ') - - return '\n' + - '\n' + - '\n' + - '\n' + - 'Error\n' + - '\n' + - '\n' + - '
' + body + '
\n' + - '\n' + - '\n' -} +var hasOwnProperty = Object.prototype.hasOwnProperty; /** * Module exports. * @public */ -module.exports = finalhandler +module.exports = Layer; + +function Layer(path, options, fn) { + if (!(this instanceof Layer)) { + return new Layer(path, options, fn); + } + + debug('new %o', path) + var opts = options || {}; + + this.handle = fn; + this.name = fn.name || ''; + this.params = undefined; + this.path = undefined; + this.regexp = pathRegexp(path, this.keys = [], opts); + + // set fast path flags + this.regexp.fast_star = path === '*' + this.regexp.fast_slash = path === '/' && opts.end === false +} /** - * Create a function to handle the final response. + * Handle the error for the layer. * + * @param {Error} error * @param {Request} req * @param {Response} res - * @param {Object} [options] - * @return {Function} - * @public + * @param {function} next + * @api private */ -function finalhandler (req, res, options) { - var opts = options || {} +Layer.prototype.handle_error = function handle_error(error, req, res, next) { + var fn = this.handle; - // get environment - var env = opts.env || process.env.NODE_ENV || 'development' + if (fn.length !== 4) { + // not a standard error handler + return next(error); + } - // get error callback - var onerror = opts.onerror + try { + fn(error, req, res, next); + } catch (err) { + next(err); + } +}; - return function (err) { - var headers - var msg - var status +/** + * Handle the request for the layer. + * + * @param {Request} req + * @param {Response} res + * @param {function} next + * @api private + */ - // ignore 404 on in-flight response - if (!err && headersSent(res)) { - debug('cannot 404 after headers sent') - return - } +Layer.prototype.handle_request = function handle(req, res, next) { + var fn = this.handle; - // unhandled error - if (err) { - // respect status code from error - status = getErrorStatusCode(err) + if (fn.length > 3) { + // not a standard request handler + return next(); + } - if (status === undefined) { - // fallback to status code on response - status = getResponseStatusCode(res) - } else { - // respect headers from error - headers = getErrorHeaders(err) - } + try { + fn(req, res, next); + } catch (err) { + next(err); + } +}; - // get error message - msg = getErrorMessage(err, status, env) - } else { - // not found - status = 404 - msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) - } +/** + * Check if this route matches `path`, if so + * populate `.params`. + * + * @param {String} path + * @return {Boolean} + * @api private + */ - debug('default %s', status) +Layer.prototype.match = function match(path) { + var match - // schedule onerror callback - if (err && onerror) { - defer(onerror, err, req, res) + if (path != null) { + // fast path non-ending match for / (any path matches) + if (this.regexp.fast_slash) { + this.params = {} + this.path = '' + return true } - // cannot actually respond - if (headersSent(res)) { - debug('cannot %d after headers sent', status) - req.socket.destroy() - return + // fast path for * (everything matched in a param) + if (this.regexp.fast_star) { + this.params = {'0': decode_param(path)} + this.path = path + return true } - // send response - send(req, res, status, headers, msg) + // match the path + match = this.regexp.exec(path) } -} -/** - * Get headers from Error object. - * - * @param {Error} err - * @return {object} - * @private - */ - -function getErrorHeaders (err) { - if (!err.headers || typeof err.headers !== 'object') { - return undefined + if (!match) { + this.params = undefined; + this.path = undefined; + return false; } - var headers = Object.create(null) - var keys = Object.keys(err.headers) + // store values + this.params = {}; + this.path = match[0] - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - headers[key] = err.headers[key] + var keys = this.keys; + var params = this.params; + + for (var i = 1; i < match.length; i++) { + var key = keys[i - 1]; + var prop = key.name; + var val = decode_param(match[i]) + + if (val !== undefined || !(hasOwnProperty.call(params, prop))) { + params[prop] = val; + } } - return headers -} + return true; +}; /** - * Get message from Error object, fallback to status message. + * Decode param value. * - * @param {Error} err - * @param {number} status - * @param {string} env + * @param {string} val * @return {string} * @private */ -function getErrorMessage (err, status, env) { - var msg - - if (env !== 'production') { - // use err.stack, which typically includes err.message - msg = err.stack +function decode_param(val) { + if (typeof val !== 'string' || val.length === 0) { + return val; + } - // fallback to err.toString() when possible - if (!msg && typeof err.toString === 'function') { - msg = err.toString() + try { + return decodeURIComponent(val); + } catch (err) { + if (err instanceof URIError) { + err.message = 'Failed to decode param \'' + val + '\''; + err.status = err.statusCode = 400; } - } - return msg || statuses[status] + throw err; + } } -/** - * Get status code from Error object. - * - * @param {Error} err - * @return {number} - * @private - */ -function getErrorStatusCode (err) { - // check err.status - if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { - return err.status - } +/***/ }), + +/***/ 23699: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - // check err.statusCode - if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { - return err.statusCode - } - return undefined -} /** - * Get resource name for the request. - * - * This is typically just the original pathname of the request - * but will fallback to "resource" is that cannot be determined. - * - * @param {IncomingMessage} req - * @return {string} + * Module dependencies. * @private */ -function getResourceName (req) { - try { - return parseUrl.original(req).pathname - } catch (e) { - return 'resource' - } -} +var debug = __nccwpck_require__(52529)('express:router:route'); +var flatten = __nccwpck_require__(62003); +var Layer = __nccwpck_require__(25624); +var methods = __nccwpck_require__(58752); /** - * Get status code from response. - * - * @param {OutgoingMessage} res - * @return {number} + * Module variables. * @private */ -function getResponseStatusCode (res) { - var status = res.statusCode +var slice = Array.prototype.slice; +var toString = Object.prototype.toString; - // default status code to 500 if outside valid range - if (typeof status !== 'number' || status < 400 || status > 599) { - status = 500 - } +/** + * Module exports. + * @public + */ - return status -} +module.exports = Route; /** - * Determine if the response headers have been sent. + * Initialize `Route` with the given `path`, * - * @param {object} res - * @returns {boolean} - * @private + * @param {String} path + * @public */ -function headersSent (res) { - return typeof res.headersSent !== 'boolean' - ? Boolean(res._header) - : res.headersSent +function Route(path) { + this.path = path; + this.stack = []; + + debug('new %o', path) + + // route handlers for various http methods + this.methods = {}; } /** - * Send response. - * - * @param {IncomingMessage} req - * @param {OutgoingMessage} res - * @param {number} status - * @param {object} headers - * @param {string} message + * Determine if the route handles a given method. * @private */ -function send (req, res, status, headers, message) { - function write () { - // response body - var body = createHtmlDocument(message) +Route.prototype._handles_method = function _handles_method(method) { + if (this.methods._all) { + return true; + } - // response status - res.statusCode = status - res.statusMessage = statuses[status] + var name = method.toLowerCase(); - // response headers - setHeaders(res, headers) + if (name === 'head' && !this.methods['head']) { + name = 'get'; + } - // security headers - res.setHeader('Content-Security-Policy', "default-src 'none'") - res.setHeader('X-Content-Type-Options', 'nosniff') + return Boolean(this.methods[name]); +}; - // standard headers - res.setHeader('Content-Type', 'text/html; charset=utf-8') - res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) +/** + * @return {Array} supported HTTP methods + * @private + */ - if (req.method === 'HEAD') { - res.end() - return - } +Route.prototype._options = function _options() { + var methods = Object.keys(this.methods); - res.end(body, 'utf8') + // append automatic head + if (this.methods.get && !this.methods.head) { + methods.push('head'); } - if (isFinished(req)) { - write() - return + for (var i = 0; i < methods.length; i++) { + // make upper case + methods[i] = methods[i].toUpperCase(); } - // unpipe everything from the request - unpipe(req) - - // flush the request - onFinished(req, write) - req.resume() -} + return methods; +}; /** - * Set response headers from an object. - * - * @param {OutgoingMessage} res - * @param {object} headers + * dispatch req, res into this route * @private */ -function setHeaders (res, headers) { - if (!headers) { - return +Route.prototype.dispatch = function dispatch(req, res, done) { + var idx = 0; + var stack = this.stack; + if (stack.length === 0) { + return done(); } - var keys = Object.keys(headers) - for (var i = 0; i < keys.length; i++) { - var key = keys[i] - res.setHeader(key, headers[key]) + var method = req.method.toLowerCase(); + if (method === 'head' && !this.methods['head']) { + method = 'get'; } -} + req.route = this; -/***/ }), + next(); -/***/ 56401: -/***/ ((module, exports, __nccwpck_require__) => { + function next(err) { + // signal to exit route + if (err && err === 'route') { + return done(); + } -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + // signal to exit router + if (err && err === 'router') { + return done(err) + } -exports = module.exports = __nccwpck_require__(60545); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); + var layer = stack[idx++]; + if (!layer) { + return done(err); + } -/** - * Colors. - */ + if (layer.method && layer.method !== method) { + return next(err); + } -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; + if (err) { + layer.handle_error(err, req, res, next); + } else { + layer.handle_request(req, res, next); + } + } +}; /** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. + * Add a handler for all HTTP verbs to this route. * - * TODO: add a `localStorage` variable to explicitly enable/disable colors + * Behaves just like middleware and can respond or call `next` + * to continue processing. + * + * You can use multiple `.all` call to add multiple handlers. + * + * function check_something(req, res, next){ + * next(); + * }; + * + * function validate_user(req, res, next){ + * next(); + * }; + * + * route + * .all(validate_user) + * .all(check_something) + * .get(function(req, res, next){ + * res.send('hello world'); + * }); + * + * @param {function} handler + * @return {Route} for chaining + * @api public */ -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } +Route.prototype.all = function all() { + var handles = flatten(slice.call(arguments)); - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.all() requires a callback function but got a ' + type + throw new TypeError(msg); + } + + var layer = Layer('/', {}, handle); + layer.method = undefined; -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; + this.methods._all = true; + this.stack.push(layer); } -}; + return this; +}; -/** - * Colorize log arguments if enabled. - * - * @api public - */ +methods.forEach(function(method){ + Route.prototype[method] = function(){ + var handles = flatten(slice.call(arguments)); -function formatArgs(args) { - var useColors = this.useColors; + for (var i = 0; i < handles.length; i++) { + var handle = handles[i]; - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); + if (typeof handle !== 'function') { + var type = toString.call(handle); + var msg = 'Route.' + method + '() requires a callback function but got a ' + type + throw new Error(msg); + } - if (!useColors) return; + debug('%s %o', method, this.path) - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') + var layer = Layer('/', {}, handle); + layer.method = method; - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; + this.methods[method] = true; + this.stack.push(layer); } - }); - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ + return this; + }; +}); -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ +/***/ }), -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} -} +/***/ 53561: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed */ -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - return r; -} /** - * Enable namespaces listed in `localStorage.debug` initially. + * Module dependencies. + * @api private */ -exports.enable(load()); +var Buffer = __nccwpck_require__(41894).Buffer +var contentDisposition = __nccwpck_require__(53921); +var contentType = __nccwpck_require__(99915); +var deprecate = __nccwpck_require__(18883)('express'); +var flatten = __nccwpck_require__(62003); +var mime = __nccwpck_require__(95287).mime; +var etag = __nccwpck_require__(69972); +var proxyaddr = __nccwpck_require__(80140); +var qs = __nccwpck_require__(22760); +var querystring = __nccwpck_require__(71191); /** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. + * Return strong ETag for `body`. * - * @return {LocalStorage} + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} * @api private */ -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} - - -/***/ }), - -/***/ 60545: -/***/ ((module, exports, __nccwpck_require__) => { - +exports.etag = createETagGenerator({ weak: false }) /** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. + * Return weak ETag for `body`. * - * Expose `debug()` as the module. + * @param {String|Buffer} body + * @param {String} [encoding] + * @return {String} + * @api private */ -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = __nccwpck_require__(80761); +exports.wetag = createETagGenerator({ weak: true }) /** - * The currently active debug mode names, and names to skip. + * Check if `path` looks absolute. + * + * @param {String} path + * @return {Boolean} + * @api private */ -exports.names = []; -exports.skips = []; +exports.isAbsolute = function(path){ + if ('/' === path[0]) return true; + if (':' === path[1] && ('\\' === path[2] || '/' === path[2])) return true; // Windows device path + if ('\\\\' === path.substring(0, 2)) return true; // Microsoft Azure absolute path +}; /** - * Map of special "%n" handling functions, for the debug "format" argument. + * Flatten the given `arr`. * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + * @param {Array} arr + * @return {Array} + * @api private */ -exports.formatters = {}; +exports.flatten = deprecate.function(flatten, + 'utils.flatten: use array-flatten npm module instead'); /** - * Previous log timestamp. + * Normalize the given `type`, for example "html" becomes "text/html". + * + * @param {String} type + * @return {Object} + * @api private */ -var prevTime; +exports.normalizeType = function(type){ + return ~type.indexOf('/') + ? acceptParams(type) + : { value: mime.lookup(type), params: {} }; +}; /** - * Select a color. - * @param {String} namespace - * @return {Number} + * Normalize `types`, for example "html" becomes "text/html". + * + * @param {Array} types + * @return {Array} * @api private */ -function selectColor(namespace) { - var hash = 0, i; +exports.normalizeTypes = function(types){ + var ret = []; - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer + for (var i = 0; i < types.length; ++i) { + ret.push(exports.normalizeType(types[i])); } - return exports.colors[Math.abs(hash) % exports.colors.length]; -} + return ret; +}; /** - * Create a debugger with the given `namespace`. + * Generate Content-Disposition header appropriate for the filename. + * non-ascii filenames are urlencoded and a filename* parameter is added * - * @param {String} namespace - * @return {Function} - * @api public + * @param {String} filename + * @return {String} + * @api private */ -function createDebug(namespace) { - - function debug() { - // disabled? - if (!debug.enabled) return; - - var self = debug; - - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } - - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); - - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } - - return debug; -} +exports.contentDisposition = deprecate.function(contentDisposition, + 'utils.contentDisposition: use content-disposition npm module instead'); /** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. + * Parse accept params `str` returning an + * object with `.value`, `.quality` and `.params`. + * also includes `.originalIndex` for stable sorting * - * @param {String} namespaces - * @api public + * @param {String} str + * @return {Object} + * @api private */ -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; - - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; +function acceptParams(str, index) { + var parts = str.split(/ *; */); + var ret = { value: parts[0], quality: 1, params: {}, originalIndex: index }; - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + for (var i = 1; i < parts.length; ++i) { + var pms = parts[i].split(/ *= */); + if ('q' === pms[0]) { + ret.quality = parseFloat(pms[1]); } else { - exports.names.push(new RegExp('^' + namespaces + '$')); + ret.params[pms[0]] = pms[1]; } } -} - -/** - * Disable debug output. - * - * @api public - */ -function disable() { - exports.enable(''); + return ret; } /** - * Returns true if the given mode name is enabled, false otherwise. + * Compile "etag" value to function. * - * @param {String} name - * @return {Boolean} - * @api public + * @param {Boolean|String|Function} val + * @return {Function} + * @api private */ -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } +exports.compileETag = function(val) { + var fn; + + if (typeof val === 'function') { + return val; } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } + + switch (val) { + case true: + fn = exports.wetag; + break; + case false: + break; + case 'strong': + fn = exports.etag; + break; + case 'weak': + fn = exports.wetag; + break; + default: + throw new TypeError('unknown value for etag function: ' + val); } - return false; + + return fn; } /** - * Coerce `val`. + * Compile "query parser" value to function. * - * @param {Mixed} val - * @return {Mixed} + * @param {String|Function} val + * @return {Function} * @api private */ -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} - - -/***/ }), +exports.compileQueryParser = function compileQueryParser(val) { + var fn; -/***/ 65612: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (typeof val === 'function') { + return val; + } -/** - * Detect Electron renderer process, which is node, but we should - * treat as a browser. - */ + switch (val) { + case true: + fn = querystring.parse; + break; + case false: + fn = newObject; + break; + case 'extended': + fn = parseExtendedQueryString; + break; + case 'simple': + fn = querystring.parse; + break; + default: + throw new TypeError('unknown value for query parser function: ' + val); + } -if (typeof process !== 'undefined' && process.type === 'renderer') { - module.exports = __nccwpck_require__(56401); -} else { - module.exports = __nccwpck_require__(4706); + return fn; } - -/***/ }), - -/***/ 4706: -/***/ ((module, exports, __nccwpck_require__) => { - /** - * Module dependencies. + * Compile "proxy trust" value to function. + * + * @param {Boolean|String|Number|Array|Function} val + * @return {Function} + * @api private */ -var tty = __nccwpck_require__(33867); -var util = __nccwpck_require__(31669); +exports.compileTrust = function(val) { + if (typeof val === 'function') return val; -/** - * This is the Node.js implementation of `debug()`. - * - * Expose `debug()` as the module. - */ + if (val === true) { + // Support plain true/false + return function(){ return true }; + } -exports = module.exports = __nccwpck_require__(60545); -exports.init = init; -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; + if (typeof val === 'number') { + // Support trusting hop count + return function(a, i){ return i < val }; + } -/** - * Colors. - */ + if (typeof val === 'string') { + // Support comma-separated values + val = val.split(/ *, */); + } -exports.colors = [6, 2, 3, 4, 5, 1]; + return proxyaddr.compile(val || []); +} /** - * Build up the default `inspectOpts` object from the environment variables. + * Set the charset in a given Content-Type string. * - * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + * @param {String} type + * @param {String} charset + * @return {String} + * @api private */ -exports.inspectOpts = Object.keys(process.env).filter(function (key) { - return /^debug_/i.test(key); -}).reduce(function (obj, key) { - // camel-case - var prop = key - .substring(6) - .toLowerCase() - .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); +exports.setCharset = function setCharset(type, charset) { + if (!type || !charset) { + return type; + } - // coerce string value into JS value - var val = process.env[key]; - if (/^(yes|on|true|enabled)$/i.test(val)) val = true; - else if (/^(no|off|false|disabled)$/i.test(val)) val = false; - else if (val === 'null') val = null; - else val = Number(val); + // parse type + var parsed = contentType.parse(type); - obj[prop] = val; - return obj; -}, {}); + // set charset + parsed.parameters.charset = charset; + + // format type + return contentType.format(parsed); +}; /** - * The file descriptor to write the `debug()` calls to. - * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * Create an ETag generator function, generating ETags with + * the given options. * - * $ DEBUG_FD=3 node script.js 3>debug.log + * @param {object} options + * @return {function} + * @private */ -var fd = parseInt(process.env.DEBUG_FD, 10) || 2; +function createETagGenerator (options) { + return function generateETag (body, encoding) { + var buf = !Buffer.isBuffer(body) + ? Buffer.from(body, encoding) + : body -if (1 !== fd && 2 !== fd) { - util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() + return etag(buf, options) + } } -var stream = 1 === fd ? process.stdout : - 2 === fd ? process.stderr : - createWritableStdioStream(fd); - /** - * Is stdout a TTY? Colored output is enabled when `true`. + * Parse an extended query string with qs. + * + * @return {Object} + * @private */ -function useColors() { - return 'colors' in exports.inspectOpts - ? Boolean(exports.inspectOpts.colors) - : tty.isatty(fd); +function parseExtendedQueryString(str) { + return qs.parse(str, { + allowPrototypes: true + }); } /** - * Map %o to `util.inspect()`, all on a single line. + * Return new empty object. + * + * @return {Object} + * @api private */ -exports.formatters.o = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts) - .split('\n').map(function(str) { - return str.trim() - }).join(' '); -}; +function newObject() { + return {}; +} -/** - * Map %o to `util.inspect()`, allowing multiple lines if needed. - */ -exports.formatters.O = function(v) { - this.inspectOpts.colors = this.useColors; - return util.inspect(v, this.inspectOpts); -}; +/***/ }), -/** - * Adds ANSI color escape codes if enabled. - * - * @api public - */ +/***/ 99209: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function formatArgs(args) { - var name = this.namespace; - var useColors = this.useColors; +"use strict"; +/*! + * express + * Copyright(c) 2009-2013 TJ Holowaychuk + * Copyright(c) 2013 Roman Shtylman + * Copyright(c) 2014-2015 Douglas Christopher Wilson + * MIT Licensed + */ - if (useColors) { - var c = this.color; - var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; - args[0] = prefix + args[0].split('\n').join('\n' + prefix); - args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); - } else { - args[0] = new Date().toUTCString() - + ' ' + name + ' ' + args[0]; - } -} /** - * Invokes `util.format()` with the specified arguments and writes to `stream`. + * Module dependencies. + * @private */ -function log() { - return stream.write(util.format.apply(util, arguments) + '\n'); -} +var debug = __nccwpck_require__(52529)('express:view'); +var path = __nccwpck_require__(85622); +var fs = __nccwpck_require__(35747); /** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private + * Module variables. + * @private */ -function save(namespaces) { - if (null == namespaces) { - // If you set a process.env field to null or undefined, it gets cast to the - // string 'null' or 'undefined'. Just delete instead. - delete process.env.DEBUG; - } else { - process.env.DEBUG = namespaces; - } -} +var dirname = path.dirname; +var basename = path.basename; +var extname = path.extname; +var join = path.join; +var resolve = path.resolve; /** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private + * Module exports. + * @public */ -function load() { - return process.env.DEBUG; -} +module.exports = View; /** - * Copied from `node/src/node.js`. + * Initialize a new `View` with the given `name`. * - * XXX: It's lame that node doesn't expose this API out-of-the-box. It also - * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + * Options: + * + * - `defaultEngine` the default template engine name + * - `engines` template engine require() cache + * - `root` root path for view lookup + * + * @param {string} name + * @param {object} options + * @public */ -function createWritableStdioStream (fd) { - var stream; - var tty_wrap = process.binding('tty_wrap'); +function View(name, options) { + var opts = options || {}; - // Note stream._type is used for test-module-load-list.js + this.defaultEngine = opts.defaultEngine; + this.ext = extname(name); + this.name = name; + this.root = opts.root; - switch (tty_wrap.guessHandleType(fd)) { - case 'TTY': - stream = new tty.WriteStream(fd); - stream._type = 'tty'; + if (!this.ext && !this.defaultEngine) { + throw new Error('No default engine was specified and no extension was provided.'); + } - // Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; + var fileName = name; - case 'FILE': - var fs = __nccwpck_require__(35747); - stream = new fs.SyncWriteStream(fd, { autoClose: false }); - stream._type = 'fs'; - break; + if (!this.ext) { + // get extension from default engine name + this.ext = this.defaultEngine[0] !== '.' + ? '.' + this.defaultEngine + : this.defaultEngine; - case 'PIPE': - case 'TCP': - var net = __nccwpck_require__(11631); - stream = new net.Socket({ - fd: fd, - readable: false, - writable: true - }); + fileName += this.ext; + } - // FIXME Should probably have an option in net.Socket to create a - // stream from an existing fd which is writable only. But for now - // we'll just add this hack and set the `readable` member to false. - // Test: ./node test/fixtures/echo.js < /etc/passwd - stream.readable = false; - stream.read = null; - stream._type = 'pipe'; + if (!opts.engines[this.ext]) { + // load engine + var mod = this.ext.substr(1) + debug('require "%s"', mod) - // FIXME Hack to have stream not keep the event loop alive. - // See https://github.com/joyent/node/issues/1726 - if (stream._handle && stream._handle.unref) { - stream._handle.unref(); - } - break; + // default engine export + var fn = require(mod).__express - default: - // Probably an error on in uv_guess_handle() - throw new Error('Implement me. Unknown stream file type!'); - } + if (typeof fn !== 'function') { + throw new Error('Module "' + mod + '" does not provide a view engine.') + } - // For supporting legacy API we put the FD here. - stream.fd = fd; + opts.engines[this.ext] = fn + } - stream._isStdio = true; + // store loaded engine + this.engine = opts.engines[this.ext]; - return stream; + // lookup path + this.path = this.lookup(fileName); } /** - * Init logic for `debug` instances. + * Lookup view by the given `name` * - * Create a new `inspectOpts` object in case `useColors` is set - * differently for a particular `debug` instance. + * @param {string} name + * @private */ -function init (debug) { - debug.inspectOpts = {}; - - var keys = Object.keys(exports.inspectOpts); - for (var i = 0; i < keys.length; i++) { - debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; - } -} +View.prototype.lookup = function lookup(name) { + var path; + var roots = [].concat(this.root); -/** - * Enable namespaces listed in `process.env.DEBUG` initially. - */ + debug('lookup "%s"', name); -exports.enable(load()); + for (var i = 0; i < roots.length && !path; i++) { + var root = roots[i]; + // resolve the path + var loc = resolve(root, name); + var dir = dirname(loc); + var file = basename(loc); -/***/ }), + // resolve the file + path = this.resolve(dir, file); + } -/***/ 80761: -/***/ ((module) => { + return path; +}; /** - * Helpers. + * Render with the given options. + * + * @param {object} options + * @param {function} callback + * @private */ -var s = 1000; -var m = s * 60; -var h = m * 60; -var d = h * 24; -var y = d * 365.25; +View.prototype.render = function render(options, callback) { + debug('render "%s"', this.path); + this.engine(this.path, options, callback); +}; /** - * Parse or format the given `val`. - * - * Options: - * - * - `long` verbose formatting [false] + * Resolve the file within the given directory. * - * @param {String|Number} val - * @param {Object} [options] - * @throws {Error} throw an error if val is not a non-empty string or a number - * @return {String|Number} - * @api public + * @param {string} dir + * @param {string} file + * @private */ -module.exports = function(val, options) { - options = options || {}; - var type = typeof val; - if (type === 'string' && val.length > 0) { - return parse(val); - } else if (type === 'number' && isNaN(val) === false) { - return options.long ? fmtLong(val) : fmtShort(val); +View.prototype.resolve = function resolve(dir, file) { + var ext = this.ext; + + // . + var path = join(dir, file); + var stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; + } + + // /index. + path = join(dir, basename(file, ext), 'index' + ext); + stat = tryStat(path); + + if (stat && stat.isFile()) { + return path; } - throw new Error( - 'val is not a non-empty string or a valid number. val=' + - JSON.stringify(val) - ); }; /** - * Parse the given `str` and return milliseconds. + * Return a stat, maybe. * - * @param {String} str - * @return {Number} - * @api private + * @param {string} path + * @return {fs.Stats} + * @private */ -function parse(str) { - str = String(str); - if (str.length > 100) { - return; - } - var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( - str - ); - if (!match) { - return; - } - var n = parseFloat(match[1]); - var type = (match[2] || 'ms').toLowerCase(); - switch (type) { - case 'years': - case 'year': - case 'yrs': - case 'yr': - case 'y': - return n * y; - case 'days': - case 'day': - case 'd': - return n * d; - case 'hours': - case 'hour': - case 'hrs': - case 'hr': - case 'h': - return n * h; - case 'minutes': - case 'minute': - case 'mins': - case 'min': - case 'm': - return n * m; - case 'seconds': - case 'second': - case 'secs': - case 'sec': - case 's': - return n * s; - case 'milliseconds': - case 'millisecond': - case 'msecs': - case 'msec': - case 'ms': - return n; - default: - return undefined; +function tryStat(path) { + debug('stat "%s"', path); + + try { + return fs.statSync(path); + } catch (e) { + return undefined; } } + +/***/ }), + +/***/ 66515: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; +/*! + * cookie + * Copyright(c) 2012-2014 Roman Shtylman + * Copyright(c) 2015 Douglas Christopher Wilson + * MIT Licensed + */ + + + /** - * Short format for `ms`. - * - * @param {Number} ms - * @return {String} - * @api private + * Module exports. + * @public */ -function fmtShort(ms) { - if (ms >= d) { - return Math.round(ms / d) + 'd'; - } - if (ms >= h) { - return Math.round(ms / h) + 'h'; - } - if (ms >= m) { - return Math.round(ms / m) + 'm'; - } - if (ms >= s) { - return Math.round(ms / s) + 's'; - } - return ms + 'ms'; -} +exports.parse = parse; +exports.serialize = serialize; /** - * Long format for `ms`. + * Module variables. + * @private + */ + +var decode = decodeURIComponent; +var encode = encodeURIComponent; +var pairSplitRegExp = /; */; + +/** + * RegExp to match field-content in RFC 7230 sec 3.2 * - * @param {Number} ms - * @return {String} - * @api private + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + * obs-text = %x80-FF */ -function fmtLong(ms) { - return plural(ms, d, 'day') || - plural(ms, h, 'hour') || - plural(ms, m, 'minute') || - plural(ms, s, 'second') || - ms + ' ms'; -} +var fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/; /** - * Pluralization helper. + * Parse a cookie header. + * + * Parse the given cookie header string into an object + * The object has the various cookies as keys(names) => values + * + * @param {string} str + * @param {object} [options] + * @return {object} + * @public */ -function plural(ms, n, name) { - if (ms < n) { - return; - } - if (ms < n * 1.5) { - return Math.floor(ms / n) + ' ' + name; +function parse(str, options) { + if (typeof str !== 'string') { + throw new TypeError('argument str must be a string'); } - return Math.ceil(ms / n) + ' ' + name + 's'; -} + var obj = {} + var opt = options || {}; + var pairs = str.split(pairSplitRegExp); + var dec = opt.decode || decode; -/***/ }), + for (var i = 0; i < pairs.length; i++) { + var pair = pairs[i]; + var eq_idx = pair.indexOf('='); -/***/ 35298: -/***/ ((module) => { + // skip things that don't look like key=value + if (eq_idx < 0) { + continue; + } -"use strict"; + var key = pair.substr(0, eq_idx).trim() + var val = pair.substr(++eq_idx, pair.length).trim(); + // quoted values + if ('"' == val[0]) { + val = val.slice(1, -1); + } -// You may be tempted to copy and paste this, -// but take a look at the commit history first, -// this is a moving target so relying on the module -// is the best way to make sure the optimization -// method is kept up to date and compatible with -// every Node version. + // only assign once + if (undefined == obj[key]) { + obj[key] = tryDecode(val, dec); + } + } -function flatstr (s) { - s | 0 - return s + return obj; } -module.exports = flatstr +/** + * Serialize data into a cookie header. + * + * Serialize the a name value pair into a cookie string suitable for + * http headers. An optional options object specified cookie parameters. + * + * serialize('foo', 'bar', { httpOnly: true }) + * => "foo=bar; httpOnly" + * + * @param {string} name + * @param {string} val + * @param {object} [options] + * @return {string} + * @public + */ + +function serialize(name, val, options) { + var opt = options || {}; + var enc = opt.encode || encode; + + if (typeof enc !== 'function') { + throw new TypeError('option encode is invalid'); + } -/***/ }), + if (!fieldContentRegExp.test(name)) { + throw new TypeError('argument name is invalid'); + } -/***/ 68329: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var value = enc(val); -if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); + if (value && !fieldContentRegExp.test(value)) { + throw new TypeError('argument val is invalid'); + } -var util = __nccwpck_require__(31669), - fs = __nccwpck_require__(35747), - EventEmitter = __nccwpck_require__(28614).EventEmitter, - crypto = __nccwpck_require__(76417); + var str = name + '=' + value; -function File(properties) { - EventEmitter.call(this); + if (null != opt.maxAge) { + var maxAge = opt.maxAge - 0; + if (isNaN(maxAge)) throw new Error('maxAge should be a Number'); + str += '; Max-Age=' + Math.floor(maxAge); + } - this.size = 0; - this.path = null; - this.name = null; - this.type = null; - this.hash = null; - this.lastModifiedDate = null; + if (opt.domain) { + if (!fieldContentRegExp.test(opt.domain)) { + throw new TypeError('option domain is invalid'); + } - this._writeStream = null; - - for (var key in properties) { - this[key] = properties[key]; + str += '; Domain=' + opt.domain; } - if(typeof this.hash === 'string') { - this.hash = crypto.createHash(properties.hash); - } else { - this.hash = null; + if (opt.path) { + if (!fieldContentRegExp.test(opt.path)) { + throw new TypeError('option path is invalid'); + } + + str += '; Path=' + opt.path; } -} -module.exports = File; -util.inherits(File, EventEmitter); -File.prototype.open = function() { - this._writeStream = new fs.WriteStream(this.path); -}; + if (opt.expires) { + if (typeof opt.expires.toUTCString !== 'function') { + throw new TypeError('option expires is invalid'); + } -File.prototype.toJSON = function() { - var json = { - size: this.size, - path: this.path, - name: this.name, - type: this.type, - mtime: this.lastModifiedDate, - length: this.length, - filename: this.filename, - mime: this.mime - }; - if (this.hash && this.hash != "") { - json.hash = this.hash; + str += '; Expires=' + opt.expires.toUTCString(); } - return json; -}; -File.prototype.write = function(buffer, cb) { - var self = this; - if (self.hash) { - self.hash.update(buffer); + if (opt.httpOnly) { + str += '; HttpOnly'; } - if (this._writeStream.closed) { - return cb(); + if (opt.secure) { + str += '; Secure'; } - this._writeStream.write(buffer, function() { - self.lastModifiedDate = new Date(); - self.size += buffer.length; - self.emit('progress', self.size); - cb(); - }); -}; + if (opt.sameSite) { + var sameSite = typeof opt.sameSite === 'string' + ? opt.sameSite.toLowerCase() : opt.sameSite; -File.prototype.end = function(cb) { - var self = this; - if (self.hash) { - self.hash = self.hash.digest('hex'); + switch (sameSite) { + case true: + str += '; SameSite=Strict'; + break; + case 'lax': + str += '; SameSite=Lax'; + break; + case 'strict': + str += '; SameSite=Strict'; + break; + case 'none': + str += '; SameSite=None'; + break; + default: + throw new TypeError('option sameSite is invalid'); + } } - this._writeStream.end(function() { - self.emit('end'); - cb(); - }); -}; + return str; +} -/***/ }), - -/***/ 7973: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Try decoding a string using a decoding function. + * + * @param {string} str + * @param {function} decode + * @private + */ -if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); +function tryDecode(str, decode) { + try { + return decode(str); + } catch (e) { + return str; + } +} -var crypto = __nccwpck_require__(76417); -var fs = __nccwpck_require__(35747); -var util = __nccwpck_require__(31669), - path = __nccwpck_require__(85622), - File = __nccwpck_require__(68329), - MultipartParser = __nccwpck_require__(31323).MultipartParser, - QuerystringParser = __nccwpck_require__(80825)/* .QuerystringParser */ .l, - OctetParser = __nccwpck_require__(48680)/* .OctetParser */ .h, - JSONParser = __nccwpck_require__(715)/* .JSONParser */ .c, - StringDecoder = __nccwpck_require__(24304).StringDecoder, - EventEmitter = __nccwpck_require__(28614).EventEmitter, - Stream = __nccwpck_require__(92413).Stream, - os = __nccwpck_require__(12087); -function IncomingForm(opts) { - if (!(this instanceof IncomingForm)) return new IncomingForm(opts); - EventEmitter.call(this); +/***/ }), - opts=opts||{}; +/***/ 36654: +/***/ ((module, exports, __nccwpck_require__) => { - this.error = null; - this.ended = false; +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ - this.maxFields = opts.maxFields || 1000; - this.maxFieldsSize = opts.maxFieldsSize || 20 * 1024 * 1024; - this.maxFileSize = opts.maxFileSize || 200 * 1024 * 1024; - this.keepExtensions = opts.keepExtensions || false; - this.uploadDir = opts.uploadDir || (os.tmpdir && os.tmpdir()) || os.tmpDir(); - this.encoding = opts.encoding || 'utf-8'; - this.headers = null; - this.type = null; - this.hash = opts.hash || false; - this.multiples = opts.multiples || false; +exports = module.exports = __nccwpck_require__(86991); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); - this.bytesReceived = null; - this.bytesExpected = null; +/** + * Colors. + */ - this._parser = null; - this._flushing = 0; - this._fieldsSize = 0; - this._fileSize = 0; - this.openedFiles = []; +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; - return this; -} -util.inherits(IncomingForm, EventEmitter); -exports.c = IncomingForm; +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ -IncomingForm.prototype.parse = function(req, cb) { - this.pause = function() { - try { - req.pause(); - } catch (err) { - // the stream was destroyed - if (!this.ended) { - // before it was completed, crash & burn - this._error(err); - } - return false; - } +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { return true; - }; + } - this.resume = function() { - try { - req.resume(); - } catch (err) { - // the stream was destroyed - if (!this.ended) { - // before it was completed, crash & burn - this._error(err); - } - return false; - } + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); +} - return true; - }; +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ - // Setup callback first, so we don't miss anything from data events emitted - // immediately. - if (cb) { - var fields = {}, files = {}; - this - .on('field', function(name, value) { - fields[name] = value; - }) - .on('file', function(name, file) { - if (this.multiples) { - if (files[name]) { - if (!Array.isArray(files[name])) { - files[name] = [files[name]]; - } - files[name].push(file); - } else { - files[name] = file; - } - } else { - files[name] = file; - } - }) - .on('error', function(err) { - cb(err, fields, files); - }) - .on('end', function() { - cb(null, fields, files); - }); +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; } +}; - // Parse headers and setup the parser, ready to start listening for data. - this.writeHeaders(req.headers); - - // Start listening for data. - var self = this; - req - .on('error', function(err) { - self._error(err); - }) - .on('aborted', function() { - self.emit('aborted'); - self._error(new Error('Request aborted')); - }) - .on('data', function(buffer) { - self.write(buffer); - }) - .on('end', function() { - if (self.error) { - return; - } - var err = self._parser.end(); - if (err) { - self._error(err); - } - }); +/** + * Colorize log arguments if enabled. + * + * @api public + */ - return this; -}; +function formatArgs(args) { + var useColors = this.useColors; -IncomingForm.prototype.writeHeaders = function(headers) { - this.headers = headers; - this._parseContentLength(); - this._parseContentType(); -}; + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); -IncomingForm.prototype.write = function(buffer) { - if (this.error) { - return; - } - if (!this._parser) { - this._error(new Error('uninitialized parser')); - return; - } + if (!useColors) return; - this.bytesReceived += buffer.length; - this.emit('progress', this.bytesReceived, this.bytesExpected); + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') - var bytesParsed = this._parser.write(buffer); - if (bytesParsed !== buffer.length) { - this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed')); - } + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); - return bytesParsed; -}; + args.splice(lastC, 0, c); +} -IncomingForm.prototype.pause = function() { - // this does nothing, unless overwritten in IncomingForm.parse - return false; -}; +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ -IncomingForm.prototype.resume = function() { - // this does nothing, unless overwritten in IncomingForm.parse - return false; -}; +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); +} -IncomingForm.prototype.onPart = function(part) { - // this method can be overwritten by the user - this.handlePart(part); -}; +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ -IncomingForm.prototype.handlePart = function(part) { - var self = this; +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} +} - // This MUST check exactly for undefined. You can not change it to !part.filename. - if (part.filename === undefined) { - var value = '' - , decoder = new StringDecoder(this.encoding); +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ - part.on('data', function(buffer) { - self._fieldsSize += buffer.length; - if (self._fieldsSize > self.maxFieldsSize) { - self._error(new Error('maxFieldsSize exceeded, received '+self._fieldsSize+' bytes of field data')); - return; - } - value += decoder.write(buffer); - }); +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} - part.on('end', function() { - self.emit('field', part.name, value); - }); - return; + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; } - this._flushing++; - - var file = new File({ - path: this._uploadPath(part.filename), - name: part.filename, - type: part.mime, - hash: self.hash - }); - - this.emit('fileBegin', part.name, file); + return r; +} - file.open(); - this.openedFiles.push(file); +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ - part.on('data', function(buffer) { - self._fileSize += buffer.length; - if (self._fileSize > self.maxFileSize) { - self._error(new Error('maxFileSize exceeded, received '+self._fileSize+' bytes of file data')); - return; - } - if (buffer.length == 0) { - return; - } - self.pause(); - file.write(buffer, function() { - self.resume(); - }); - }); +exports.enable(load()); - part.on('end', function() { - file.end(function() { - self._flushing--; - self.emit('file', part.name, file); - self._maybeEnd(); - }); - }); -}; +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ -function dummyParser(self) { - return { - end: function () { - self.ended = true; - self._maybeEnd(); - return null; - } - }; +function localstorage() { + try { + return window.localStorage; + } catch (e) {} } -IncomingForm.prototype._parseContentType = function() { - if (this.bytesExpected === 0) { - this._parser = dummyParser(this); - return; - } - if (!this.headers['content-type']) { - this._error(new Error('bad content-type header, no content-type')); - return; - } +/***/ }), - if (this.headers['content-type'].match(/octet-stream/i)) { - this._initOctetStream(); - return; - } +/***/ 86991: +/***/ ((module, exports, __nccwpck_require__) => { - if (this.headers['content-type'].match(/urlencoded/i)) { - this._initUrlencoded(); - return; - } - if (this.headers['content-type'].match(/multipart/i)) { - var m = this.headers['content-type'].match(/boundary=(?:"([^"]+)"|([^;]+))/i); - if (m) { - this._initMultipart(m[1] || m[2]); - } else { - this._error(new Error('bad content-type header, no multipart boundary')); - } - return; - } +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ - if (this.headers['content-type'].match(/json/i)) { - this._initJSONencoded(); - return; - } +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __nccwpck_require__(27025); - this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type'])); -}; +/** + * The currently active debug mode names, and names to skip. + */ -IncomingForm.prototype._error = function(err) { - if (this.error || this.ended) { - return; - } +exports.names = []; +exports.skips = []; - this.error = err; - this.emit('error', err); +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ - if (Array.isArray(this.openedFiles)) { - this.openedFiles.forEach(function(file) { - file._writeStream.destroy(); - setTimeout(fs.unlink, 0, file.path, function(error) { }); - }); - } -}; +exports.formatters = {}; -IncomingForm.prototype._parseContentLength = function() { - this.bytesReceived = 0; - if (this.headers['content-length']) { - this.bytesExpected = parseInt(this.headers['content-length'], 10); - } else if (this.headers['transfer-encoding'] === undefined) { - this.bytesExpected = 0; - } +/** + * Previous log timestamp. + */ - if (this.bytesExpected !== null) { - this.emit('progress', this.bytesReceived, this.bytesExpected); - } -}; +var prevTime; -IncomingForm.prototype._newParser = function() { - return new MultipartParser(); -}; +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ -IncomingForm.prototype._initMultipart = function(boundary) { - this.type = 'multipart'; +function selectColor(namespace) { + var hash = 0, i; - var parser = new MultipartParser(), - self = this, - headerField, - headerValue, - part; + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } - parser.initWithBoundary(boundary); + return exports.colors[Math.abs(hash) % exports.colors.length]; +} - parser.onPartBegin = function() { - part = new Stream(); - part.readable = true; - part.headers = {}; - part.name = null; - part.filename = null; - part.mime = null; +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ - part.transferEncoding = 'binary'; - part.transferBuffer = ''; +function createDebug(namespace) { - headerField = ''; - headerValue = ''; - }; + function debug() { + // disabled? + if (!debug.enabled) return; - parser.onHeaderField = function(b, start, end) { - headerField += b.toString(self.encoding, start, end); - }; + var self = debug; - parser.onHeaderValue = function(b, start, end) { - headerValue += b.toString(self.encoding, start, end); - }; + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; - parser.onHeaderEnd = function() { - headerField = headerField.toLowerCase(); - part.headers[headerField] = headerValue; + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } - // matches either a quoted-string or a token (RFC 2616 section 19.5.1) - var m = headerValue.match(/\bname=("([^"]*)"|([^\(\)<>@,;:\\"\/\[\]\?=\{\}\s\t/]+))/i); - if (headerField == 'content-disposition') { - if (m) { - part.name = m[2] || m[3] || ''; - } + args[0] = exports.coerce(args[0]); - part.filename = self._fileName(headerValue); - } else if (headerField == 'content-type') { - part.mime = headerValue; - } else if (headerField == 'content-transfer-encoding') { - part.transferEncoding = headerValue.toLowerCase(); + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); } - headerField = ''; - headerValue = ''; - }; + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); - parser.onHeadersEnd = function() { - switch(part.transferEncoding){ - case 'binary': - case '7bit': - case '8bit': - parser.onPartData = function(b, start, end) { - part.emit('data', b.slice(start, end)); - }; + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); - parser.onPartEnd = function() { - part.emit('end'); - }; - break; + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); - case 'base64': - parser.onPartData = function(b, start, end) { - part.transferBuffer += b.slice(start, end).toString('ascii'); + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } - /* - four bytes (chars) in base64 converts to three bytes in binary - encoding. So we should always work with a number of bytes that - can be divided by 4, it will result in a number of buytes that - can be divided vy 3. - */ - var offset = parseInt(part.transferBuffer.length / 4, 10) * 4; - part.emit('data', new Buffer(part.transferBuffer.substring(0, offset), 'base64')); - part.transferBuffer = part.transferBuffer.substring(offset); - }; + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); - parser.onPartEnd = function() { - part.emit('data', new Buffer(part.transferBuffer, 'base64')); - part.emit('end'); - }; - break; + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } - default: - return self._error(new Error('unknown transfer-encoding')); - } + return debug; +} - self.onPart(part); - }; +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ +function enable(namespaces) { + exports.save(namespaces); - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; + exports.names = []; + exports.skips = []; - this._parser = parser; -}; + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; -IncomingForm.prototype._fileName = function(headerValue) { - // matches either a quoted-string or a token (RFC 2616 section 19.5.1) - var m = headerValue.match(/\bfilename=("(.*?)"|([^\(\)<>@,;:\\"\/\[\]\?=\{\}\s\t/]+))($|;\s)/i); - if (!m) return; + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} - var match = m[2] || m[3] || ''; - var filename = match.substr(match.lastIndexOf('\\') + 1); - filename = filename.replace(/%22/g, '"'); - filename = filename.replace(/&#([\d]{4});/g, function(m, code) { - return String.fromCharCode(code); - }); - return filename; -}; +/** + * Disable debug output. + * + * @api public + */ -IncomingForm.prototype._initUrlencoded = function() { - this.type = 'urlencoded'; +function disable() { + exports.enable(''); +} - var parser = new QuerystringParser(this.maxFields) - , self = this; +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ - parser.onField = function(key, val) { - self.emit('field', key, val); - }; +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } + } + return false; +} - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ - this._parser = parser; -}; +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; +} -IncomingForm.prototype._initOctetStream = function() { - this.type = 'octet-stream'; - var filename = this.headers['x-file-name']; - var mime = this.headers['content-type']; - var file = new File({ - path: this._uploadPath(filename), - name: filename, - type: mime - }); +/***/ }), - this.emit('fileBegin', filename, file); - file.open(); - this.openedFiles.push(file); - this._flushing++; +/***/ 52529: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var self = this; +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ - self._parser = new OctetParser(); +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __nccwpck_require__(36654); +} else { + module.exports = __nccwpck_require__(25696); +} - //Keep track of writes that haven't finished so we don't emit the file before it's done being written - var outstandingWrites = 0; - self._parser.on('data', function(buffer){ - self.pause(); - outstandingWrites++; +/***/ }), - file.write(buffer, function() { - outstandingWrites--; - self.resume(); +/***/ 25696: +/***/ ((module, exports, __nccwpck_require__) => { - if(self.ended){ - self._parser.emit('doneWritingFile'); - } - }); - }); +/** + * Module dependencies. + */ - self._parser.on('end', function(){ - self._flushing--; - self.ended = true; +var tty = __nccwpck_require__(33867); +var util = __nccwpck_require__(31669); - var done = function(){ - file.end(function() { - self.emit('file', 'file', file); - self._maybeEnd(); - }); - }; +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ - if(outstandingWrites === 0){ - done(); - } else { - self._parser.once('doneWritingFile', done); - } - }); -}; +exports = module.exports = __nccwpck_require__(86991); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; -IncomingForm.prototype._initJSONencoded = function() { - this.type = 'json'; +/** + * Colors. + */ - var parser = new JSONParser(this) - , self = this; +exports.colors = [6, 2, 3, 4, 5, 1]; - parser.onField = function(key, val) { - self.emit('field', key, val); - }; +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - parser.onEnd = function() { - self.ended = true; - self._maybeEnd(); - }; +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); - this._parser = parser; -}; + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); -IncomingForm.prototype._uploadPath = function(filename) { - var buf = crypto.randomBytes(16); - var name = 'upload_' + buf.toString('hex'); + obj[prop] = val; + return obj; +}, {}); - if (this.keepExtensions) { - var ext = path.extname(filename); - ext = ext.replace(/(\.[a-z0-9]+).*/i, '$1'); +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ - name += ext; - } +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; - return path.join(this.uploadDir, name); -}; +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} -IncomingForm.prototype._maybeEnd = function() { - if (!this.ended || this._flushing || this.error) { - return; - } +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); - this.emit('end'); -}; +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} -/***/ }), +/** + * Map %o to `util.inspect()`, all on a single line. + */ -/***/ 95265: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; -var IncomingForm = __nccwpck_require__(7973)/* .IncomingForm */ .c; -IncomingForm.IncomingForm = IncomingForm; -module.exports = IncomingForm; +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ -/***/ }), +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; -/***/ 715: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; -if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} -var Buffer = __nccwpck_require__(64293).Buffer; +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ -function JSONParser(parent) { - this.parent = parent; - this.chunks = []; - this.bytesWritten = 0; +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); } -exports.c = JSONParser; -JSONParser.prototype.write = function(buffer) { - this.bytesWritten += buffer.length; - this.chunks.push(buffer); - return buffer.length; -}; +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ -JSONParser.prototype.end = function() { - try { - var fields = JSON.parse(Buffer.concat(this.chunks)); - for (var field in fields) { - this.onField(field, fields[field]); - } - } catch (e) { - this.parent.emit('error', e); +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; } - this.data = null; +} - this.onEnd(); -}; +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + return process.env.DEBUG; +} -/***/ }), +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ -/***/ 31323: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); -var Buffer = __nccwpck_require__(64293).Buffer, - s = 0, - S = - { PARSER_UNINITIALIZED: s++, - START: s++, - START_BOUNDARY: s++, - HEADER_FIELD_START: s++, - HEADER_FIELD: s++, - HEADER_VALUE_START: s++, - HEADER_VALUE: s++, - HEADER_VALUE_ALMOST_DONE: s++, - HEADERS_ALMOST_DONE: s++, - PART_DATA_START: s++, - PART_DATA: s++, - PART_END: s++, - END: s++ - }, + // Note stream._type is used for test-module-load-list.js - f = 1, - F = - { PART_BOUNDARY: f, - LAST_BOUNDARY: f *= 2 - }, + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; - LF = 10, - CR = 13, - SPACE = 32, - HYPHEN = 45, - COLON = 58, - A = 97, - Z = 122, + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; - lower = function(c) { - return c | 0x20; - }; + case 'FILE': + var fs = __nccwpck_require__(35747); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; -for (s in S) { - exports[s] = S[s]; -} + case 'PIPE': + case 'TCP': + var net = __nccwpck_require__(11631); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); -function MultipartParser() { - this.boundary = null; - this.boundaryChars = null; - this.lookbehind = null; - this.state = S.PARSER_UNINITIALIZED; + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; - this.index = null; - this.flags = 0; -} -exports.MultipartParser = MultipartParser; + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; -MultipartParser.stateToString = function(stateNumber) { - for (var state in S) { - var number = S[state]; - if (number === stateNumber) return state; + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); } -}; - -MultipartParser.prototype.initWithBoundary = function(str) { - this.boundary = new Buffer(str.length+4); - this.boundary.write('\r\n--', 0); - this.boundary.write(str, 4); - this.lookbehind = new Buffer(this.boundary.length+8); - this.state = S.START; - this.boundaryChars = {}; - for (var i = 0; i < this.boundary.length; i++) { - this.boundaryChars[this.boundary[i]] = true; - } -}; + // For supporting legacy API we put the FD here. + stream.fd = fd; -MultipartParser.prototype.write = function(buffer) { - var self = this, - i = 0, - len = buffer.length, - prevIndex = this.index, - index = this.index, - state = this.state, - flags = this.flags, - lookbehind = this.lookbehind, - boundary = this.boundary, - boundaryChars = this.boundaryChars, - boundaryLength = this.boundary.length, - boundaryEnd = boundaryLength - 1, - bufferLength = buffer.length, - c, - cl, + stream._isStdio = true; - mark = function(name) { - self[name+'Mark'] = i; - }, - clear = function(name) { - delete self[name+'Mark']; - }, - callback = function(name, buffer, start, end) { - if (start !== undefined && start === end) { - return; - } + return stream; +} - var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); - if (callbackSymbol in self) { - self[callbackSymbol](buffer, start, end); - } - }, - dataCallback = function(name, clear) { - var markSymbol = name+'Mark'; - if (!(markSymbol in self)) { - return; - } +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ - if (!clear) { - callback(name, buffer, self[markSymbol], buffer.length); - self[markSymbol] = 0; - } else { - callback(name, buffer, self[markSymbol], i); - delete self[markSymbol]; - } - }; +function init (debug) { + debug.inspectOpts = {}; - for (i = 0; i < len; i++) { - c = buffer[i]; - switch (state) { - case S.PARSER_UNINITIALIZED: - return i; - case S.START: - index = 0; - state = S.START_BOUNDARY; - case S.START_BOUNDARY: - if (index == boundary.length - 2) { - if (c == HYPHEN) { - flags |= F.LAST_BOUNDARY; - } else if (c != CR) { - return i; - } - index++; - break; - } else if (index - 1 == boundary.length - 2) { - if (flags & F.LAST_BOUNDARY && c == HYPHEN){ - callback('end'); - state = S.END; - flags = 0; - } else if (!(flags & F.LAST_BOUNDARY) && c == LF) { - index = 0; - callback('partBegin'); - state = S.HEADER_FIELD_START; - } else { - return i; - } - break; - } + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} - if (c != boundary[index+2]) { - index = -2; - } - if (c == boundary[index+2]) { - index++; - } - break; - case S.HEADER_FIELD_START: - state = S.HEADER_FIELD; - mark('headerField'); - index = 0; - case S.HEADER_FIELD: - if (c == CR) { - clear('headerField'); - state = S.HEADERS_ALMOST_DONE; - break; - } +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ - index++; - if (c == HYPHEN) { - break; - } +exports.enable(load()); - if (c == COLON) { - if (index == 1) { - // empty header field - return i; - } - dataCallback('headerField', true); - state = S.HEADER_VALUE_START; - break; - } - cl = lower(c); - if (cl < A || cl > Z) { - return i; - } - break; - case S.HEADER_VALUE_START: - if (c == SPACE) { - break; - } +/***/ }), - mark('headerValue'); - state = S.HEADER_VALUE; - case S.HEADER_VALUE: - if (c == CR) { - dataCallback('headerValue', true); - callback('headerEnd'); - state = S.HEADER_VALUE_ALMOST_DONE; - } - break; - case S.HEADER_VALUE_ALMOST_DONE: - if (c != LF) { - return i; - } - state = S.HEADER_FIELD_START; - break; - case S.HEADERS_ALMOST_DONE: - if (c != LF) { - return i; - } +/***/ 27025: +/***/ ((module) => { - callback('headersEnd'); - state = S.PART_DATA_START; - break; - case S.PART_DATA_START: - state = S.PART_DATA; - mark('partData'); - case S.PART_DATA: - prevIndex = index; +/** + * Helpers. + */ - if (index === 0) { - // boyer-moore derrived algorithm to safely skip non-boundary data - i += boundaryEnd; - while (i < bufferLength && !(buffer[i] in boundaryChars)) { - i += boundaryLength; - } - i -= boundaryEnd; - c = buffer[i]; - } +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; - if (index < boundary.length) { - if (boundary[index] == c) { - if (index === 0) { - dataCallback('partData', true); - } - index++; - } else { - index = 0; - } - } else if (index == boundary.length) { - index++; - if (c == CR) { - // CR = part boundary - flags |= F.PART_BOUNDARY; - } else if (c == HYPHEN) { - // HYPHEN = end boundary - flags |= F.LAST_BOUNDARY; - } else { - index = 0; - } - } else if (index - 1 == boundary.length) { - if (flags & F.PART_BOUNDARY) { - index = 0; - if (c == LF) { - // unset the PART_BOUNDARY flag - flags &= ~F.PART_BOUNDARY; - callback('partEnd'); - callback('partBegin'); - state = S.HEADER_FIELD_START; - break; - } - } else if (flags & F.LAST_BOUNDARY) { - if (c == HYPHEN) { - callback('partEnd'); - callback('end'); - state = S.END; - flags = 0; - } else { - index = 0; - } - } else { - index = 0; - } - } +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ - if (index > 0) { - // when matching a possible boundary, keep a lookbehind reference - // in case it turns out to be a false lead - lookbehind[index-1] = c; - } else if (prevIndex > 0) { - // if our boundary turned out to be rubbish, the captured lookbehind - // belongs to partData - callback('partData', lookbehind, 0, prevIndex); - prevIndex = 0; - mark('partData'); +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; - // reconsider the current character even so it interrupted the sequence - // it could be the beginning of a new sequence - i--; - } +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - break; - case S.END: - break; - default: - return i; - } +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; } +} - dataCallback('headerField'); - dataCallback('headerValue'); - dataCallback('partData'); - - this.index = index; - this.state = state; - this.flags = flags; - - return len; -}; +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ -MultipartParser.prototype.end = function() { - var callback = function(self, name) { - var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); - if (callbackSymbol in self) { - self[callbackSymbol](); - } - }; - if ((this.state == S.HEADER_FIELD_START && this.index === 0) || - (this.state == S.PART_DATA && this.index == this.boundary.length)) { - callback(this, 'partEnd'); - callback(this, 'end'); - } else if (this.state != S.END) { - return new Error('MultipartParser.end(): stream ended unexpectedly: ' + this.explain()); +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; } -}; - -MultipartParser.prototype.explain = function() { - return 'state = ' + MultipartParser.stateToString(this.state); -}; - - -/***/ }), - -/***/ 48680: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -var EventEmitter = __nccwpck_require__(28614).EventEmitter - , util = __nccwpck_require__(31669); - -function OctetParser(options){ - if(!(this instanceof OctetParser)) return new OctetParser(options); - EventEmitter.call(this); + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; } -util.inherits(OctetParser, EventEmitter); +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ -exports.h = OctetParser; +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} -OctetParser.prototype.write = function(buffer) { - this.emit('data', buffer); - return buffer.length; -}; +/** + * Pluralization helper. + */ -OctetParser.prototype.end = function() { - this.emit('end'); -}; +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} /***/ }), -/***/ 80825: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 41894: +/***/ ((module, exports, __nccwpck_require__) => { -if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); +/* eslint-disable node/no-deprecated-api */ +var buffer = __nccwpck_require__(64293) +var Buffer = buffer.Buffer -// This is a buffering parser, not quite as nice as the multipart one. -// If I find time I'll rewrite this to be fully streaming as well -var querystring = __nccwpck_require__(71191); +// alternative to using Object.keys for old browsers +function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key] + } +} +if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer +} else { + // Copy properties from require('buffer') + copyProps(buffer, exports) + exports.Buffer = SafeBuffer +} -function QuerystringParser(maxKeys) { - this.maxKeys = maxKeys; - this.buffer = ''; +function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) } -exports.l = QuerystringParser; -QuerystringParser.prototype.write = function(buffer) { - this.buffer += buffer.toString('ascii'); - return buffer.length; -}; +// Copy static methods from Buffer +copyProps(Buffer, SafeBuffer) -QuerystringParser.prototype.end = function() { - var fields = querystring.parse(this.buffer, '&', '=', { maxKeys: this.maxKeys }); - for (var field in fields) { - this.onField(field, fields[field]); +SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') } - this.buffer = ''; + return Buffer(arg, encodingOrOffset, length) +} - this.onEnd(); -}; +SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size) + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding) + } else { + buf.fill(fill) + } + } else { + buf.fill(0) + } + return buf +} + +SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) +} +SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) +} /***/ }), -/***/ 46868: -/***/ ((module) => { +/***/ 24826: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/*! - * forwarded - * Copyright(c) 2014-2017 Douglas Christopher Wilson - * MIT Licensed - */ +const validator = __nccwpck_require__(74174) +const parse = __nccwpck_require__(96214) +const redactor = __nccwpck_require__(17333) +const restorer = __nccwpck_require__(98806) +const { groupRedact, nestedRedact } = __nccwpck_require__(54865) +const state = __nccwpck_require__(41012) +const rx = __nccwpck_require__(9158) +const validate = validator() +const noop = (o) => o +noop.restore = noop -/** - * Module exports. - * @public - */ - -module.exports = forwarded +const DEFAULT_CENSOR = '[REDACTED]' +fastRedact.rx = rx +fastRedact.validator = validator -/** - * Get all addresses in the request, using the `X-Forwarded-For` header. - * - * @param {object} req - * @return {array} - * @public - */ +module.exports = fastRedact -function forwarded (req) { - if (!req) { - throw new TypeError('argument req is required') +function fastRedact (opts = {}) { + const paths = Array.from(new Set(opts.paths || [])) + const serialize = 'serialize' in opts ? ( + opts.serialize === false ? opts.serialize + : (typeof opts.serialize === 'function' ? opts.serialize : JSON.stringify) + ) : JSON.stringify + const remove = opts.remove + if (remove === true && serialize !== JSON.stringify) { + throw Error('fast-redact – remove option may only be set when serializer is JSON.stringify') } + const censor = remove === true + ? undefined + : 'censor' in opts ? opts.censor : DEFAULT_CENSOR - // simple header parsing - var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') - var socketAddr = req.connection.remoteAddress - var addrs = [socketAddr].concat(proxyAddrs) - - // return all addresses - return addrs -} + const isCensorFct = typeof censor === 'function' + const censorFctTakesPath = isCensorFct && censor.length > 1 -/** - * Parse the X-Forwarded-For header. - * - * @param {string} header - * @private - */ + if (paths.length === 0) return serialize || noop -function parse (header) { - var end = header.length - var list = [] - var start = header.length + validate({ paths, serialize, censor }) - // gather addresses, backwards - for (var i = header.length - 1; i >= 0; i--) { - switch (header.charCodeAt(i)) { - case 0x20: /* */ - if (start === end) { - start = end = i - } - break - case 0x2c: /* , */ - if (start !== end) { - list.push(header.substring(start, end)) - } - start = end = i - break - default: - start = i - break - } - } + const { wildcards, wcLen, secret } = parse({ paths, censor }) - // final address - if (start !== end) { - list.push(header.substring(start, end)) - } + const compileRestore = restorer({ secret, wcLen }) + const strict = 'strict' in opts ? opts.strict : true - return list + return redactor({ secret, wcLen, serialize, strict, isCensorFct, censorFctTakesPath }, state({ + secret, + censor, + compileRestore, + serialize, + groupRedact, + nestedRedact, + wildcards, + wcLen + })) } /***/ }), -/***/ 83136: +/***/ 54865: /***/ ((module) => { "use strict"; -/*! - * fresh - * Copyright(c) 2012 TJ Holowaychuk - * Copyright(c) 2016-2017 Douglas Christopher Wilson - * MIT Licensed - */ - - -/** - * RegExp to check for no-cache token in Cache-Control. - * @private - */ -var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ - -/** - * Module exports. - * @public - */ +module.exports = { + groupRedact, + groupRestore, + nestedRedact, + nestedRestore +} -module.exports = fresh +function groupRestore ({ keys, values, target }) { + if (target == null) return + const length = keys.length + for (var i = 0; i < length; i++) { + const k = keys[i] + target[k] = values[i] + } +} -/** - * Check freshness of the response using request and response headers. - * - * @param {Object} reqHeaders - * @param {Object} resHeaders - * @return {Boolean} - * @public - */ +function groupRedact (o, path, censor, isCensorFct, censorFctTakesPath) { + const target = get(o, path) + if (target == null) return { keys: null, values: null, target: null, flat: true } + const keys = Object.keys(target) + const keysLength = keys.length + const pathLength = path.length + const pathWithKey = censorFctTakesPath ? [...path] : undefined + const values = new Array(keysLength) -function fresh (reqHeaders, resHeaders) { - // fields - var modifiedSince = reqHeaders['if-modified-since'] - var noneMatch = reqHeaders['if-none-match'] + for (var i = 0; i < keysLength; i++) { + const key = keys[i] + values[i] = target[key] - // unconditional request - if (!modifiedSince && !noneMatch) { - return false + if (censorFctTakesPath) { + pathWithKey[pathLength] = key + target[key] = censor(target[key], pathWithKey) + } else if (isCensorFct) { + target[key] = censor(target[key]) + } else { + target[key] = censor + } } + return { keys, values, target, flat: true } +} - // Always return stale when Cache-Control: no-cache - // to support end-to-end reload requests - // https://tools.ietf.org/html/rfc2616#section-14.9.4 - var cacheControl = reqHeaders['cache-control'] - if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { - return false +function nestedRestore (arr) { + const length = arr.length + for (var i = 0; i < length; i++) { + const { key, target, value } = arr[i] + target[key] = value } +} - // if-none-match - if (noneMatch && noneMatch !== '*') { - var etag = resHeaders['etag'] - - if (!etag) { - return false - } - - var etagStale = true - var matches = parseTokenList(noneMatch) - for (var i = 0; i < matches.length; i++) { - var match = matches[i] - if (match === etag || match === 'W/' + etag || 'W/' + match === etag) { - etagStale = false - break - } - } +function nestedRedact (store, o, path, ns, censor, isCensorFct, censorFctTakesPath) { + const target = get(o, path) + if (target == null) return + const keys = Object.keys(target) + const keysLength = keys.length + for (var i = 0; i < keysLength; i++) { + const key = keys[i] + const { value, parent, exists } = + specialSet(target, key, path, ns, censor, isCensorFct, censorFctTakesPath) - if (etagStale) { - return false + if (exists === true && parent !== null) { + store.push({ key: ns[ns.length - 1], target: parent, value }) } } + return store +} - // if-modified-since - if (modifiedSince) { - var lastModified = resHeaders['last-modified'] - var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) +function has (obj, prop) { + return Object.prototype.hasOwnProperty.call(obj, prop) +} - if (modifiedStale) { - return false +function specialSet (o, k, path, afterPath, censor, isCensorFct, censorFctTakesPath) { + const afterPathLen = afterPath.length + const lastPathIndex = afterPathLen - 1 + const originalKey = k + var i = -1 + var n + var nv + var ov + var oov = null + var exists = true + ov = n = o[k] + if (typeof n !== 'object') return { value: null, parent: null, exists } + while (n != null && ++i < afterPathLen) { + k = afterPath[i] + oov = ov + if (!(k in n)) { + exists = false + break } + ov = n[k] + nv = (i !== lastPathIndex) + ? ov + : (isCensorFct + ? (censorFctTakesPath ? censor(ov, [...path, originalKey, ...afterPath]) : censor(ov)) + : censor) + n[k] = (has(n, k) && nv === ov) || (nv === undefined && censor !== undefined) ? n[k] : nv + n = n[k] + if (typeof n !== 'object') break } + return { value: ov, parent: oov, exists } +} - return true +function get (o, p) { + var i = -1 + var l = p.length + var n = o + while (n != null && ++i < l) { + n = n[p[i]] + } + return n } -/** - * Parse an HTTP Date into a number. - * - * @param {string} date - * @private - */ -function parseHttpDate (date) { - var timestamp = date && Date.parse(date) +/***/ }), - // istanbul ignore next: guard against date.js Date.parse patching - return typeof timestamp === 'number' - ? timestamp - : NaN -} +/***/ 96214: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Parse a HTTP token list. - * - * @param {string} str - * @private - */ +"use strict"; -function parseTokenList (str) { - var end = 0 - var list = [] - var start = 0 - // gather tokens - for (var i = 0, len = str.length; i < len; i++) { - switch (str.charCodeAt(i)) { - case 0x20: /* */ - if (start === end) { - start = end = i + 1 - } - break - case 0x2c: /* , */ - list.push(str.substring(start, end)) - start = end = i + 1 - break - default: - end = i + 1 - break +const rx = __nccwpck_require__(9158) + +module.exports = parse + +function parse ({ paths }) { + const wildcards = [] + var wcLen = 0 + const secret = paths.reduce(function (o, strPath, ix) { + var path = strPath.match(rx).map((p) => p.replace(/'|"|`/g, '')) + const leadingBracket = strPath[0] === '[' + path = path.map((p) => { + if (p[0] === '[') return p.substr(1, p.length - 2) + else return p + }) + const star = path.indexOf('*') + if (star > -1) { + const before = path.slice(0, star) + const beforeStr = before.join('.') + const after = path.slice(star + 1, path.length) + if (after.indexOf('*') > -1) throw Error('fast-redact – Only one wildcard per path is supported') + const nested = after.length > 0 + wcLen++ + wildcards.push({ + before, + beforeStr, + after, + nested + }) + } else { + o[strPath] = { + path: path, + val: undefined, + precensored: false, + circle: '', + escPath: JSON.stringify(strPath), + leadingBracket: leadingBracket + } } - } - - // final token - list.push(str.substring(start, end)) + return o + }, {}) - return list + return { wildcards, wcLen, secret } } /***/ }), -/***/ 19320: -/***/ ((module) => { +/***/ 17333: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/* eslint no-invalid-this: 1 */ +const rx = __nccwpck_require__(9158) -var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; -var slice = Array.prototype.slice; -var toStr = Object.prototype.toString; -var funcType = '[object Function]'; +module.exports = redactor -module.exports = function bind(that) { - var target = this; - if (typeof target !== 'function' || toStr.call(target) !== funcType) { - throw new TypeError(ERROR_MESSAGE + target); +function redactor ({ secret, serialize, wcLen, strict, isCensorFct, censorFctTakesPath }, state) { + /* eslint-disable-next-line */ + const redact = Function('o', ` + if (typeof o !== 'object' || o == null) { + ${strictImpl(strict, serialize)} } - var args = slice.call(arguments, 1); + const { censor, secret } = this + ${redactTmpl(secret, isCensorFct, censorFctTakesPath)} + this.compileRestore() + ${dynamicRedactTmpl(wcLen > 0, isCensorFct, censorFctTakesPath)} + ${resultTmpl(serialize)} + `).bind(state) - var bound; - var binder = function () { - if (this instanceof bound) { - var result = target.apply( - this, - args.concat(slice.call(arguments)) - ); - if (Object(result) === result) { - return result; - } - return this; - } else { - return target.apply( - that, - args.concat(slice.call(arguments)) - ); - } - }; + if (serialize === false) { + redact.restore = (o) => state.restore(o) + } - var boundLength = Math.max(0, target.length - args.length); - var boundArgs = []; - for (var i = 0; i < boundLength; i++) { - boundArgs.push('$' + i); + return redact +} + +function redactTmpl (secret, isCensorFct, censorFctTakesPath) { + return Object.keys(secret).map((path) => { + const { escPath, leadingBracket, path: arrPath } = secret[path] + const skip = leadingBracket ? 1 : 0 + const delim = leadingBracket ? '' : '.' + const hops = [] + var match + while ((match = rx.exec(path)) !== null) { + const [ , ix ] = match + const { index, input } = match + if (index > skip) hops.push(input.substring(0, index - (ix ? 0 : 1))) } + var existence = hops.map((p) => `o${delim}${p}`).join(' && ') + if (existence.length === 0) existence += `o${delim}${path} != null` + else existence += ` && o${delim}${path} != null` - bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); + const circularDetection = ` + switch (true) { + ${hops.reverse().map((p) => ` + case o${delim}${p} === censor: + secret[${escPath}].circle = ${JSON.stringify(p)} + break + `).join('\n')} + } + ` - if (target.prototype) { - var Empty = function Empty() {}; - Empty.prototype = target.prototype; - bound.prototype = new Empty(); - Empty.prototype = null; + const censorArgs = censorFctTakesPath + ? `val, ${JSON.stringify(arrPath)}` + : `val` + + return ` + if (${existence}) { + const val = o${delim}${path} + if (val === censor) { + secret[${escPath}].precensored = true + } else { + secret[${escPath}].val = val + o${delim}${path} = ${isCensorFct ? `censor(${censorArgs})` : 'censor'} + ${circularDetection} + } + } + ` + }).join('\n') +} + +function dynamicRedactTmpl (hasWildcards, isCensorFct, censorFctTakesPath) { + return hasWildcards === true ? ` + { + const { wildcards, wcLen, groupRedact, nestedRedact } = this + for (var i = 0; i < wcLen; i++) { + const { before, beforeStr, after, nested } = wildcards[i] + if (nested === true) { + secret[beforeStr] = secret[beforeStr] || [] + nestedRedact(secret[beforeStr], o, before, after, censor, ${isCensorFct}, ${censorFctTakesPath}) + } else secret[beforeStr] = groupRedact(o, before, censor, ${isCensorFct}, ${censorFctTakesPath}) + } } + ` : '' +} - return bound; -}; +function resultTmpl (serialize) { + return serialize === false ? `return o` : ` + var s = this.serialize(o) + this.restore(o) + return s + ` +} + +function strictImpl (strict, serialize) { + return strict === true + ? `throw Error('fast-redact: primitives cannot be redacted')` + : serialize === false ? `return o` : `return this.serialize(o)` +} /***/ }), -/***/ 88334: +/***/ 98806: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var implementation = __nccwpck_require__(19320); +const { groupRestore, nestedRestore } = __nccwpck_require__(54865) -module.exports = Function.prototype.bind || implementation; +module.exports = restorer + +function restorer ({ secret, wcLen }) { + return function compileRestore () { + if (this.restore) return + const paths = Object.keys(secret) + .filter((path) => secret[path].precensored === false) + const resetters = resetTmpl(secret, paths) + const hasWildcards = wcLen > 0 + const state = hasWildcards ? { secret, groupRestore, nestedRestore } : { secret } + /* eslint-disable-next-line */ + this.restore = Function( + 'o', + restoreTmpl(resetters, paths, hasWildcards) + ).bind(state) + } +} + +/** + * Mutates the original object to be censored by restoring its original values + * prior to censoring. + * + * @param {object} secret Compiled object describing which target fields should + * be censored and the field states. + * @param {string[]} paths The list of paths to censor as provided at + * initialization time. + * + * @returns {string} String of JavaScript to be used by `Function()`. The + * string compiles to the function that does the work in the description. + */ +function resetTmpl (secret, paths) { + return paths.map((path) => { + const { circle, escPath, leadingBracket } = secret[path] + const delim = leadingBracket ? '' : '.' + const reset = circle + ? `o.${circle} = secret[${escPath}].val` + : `o${delim}${path} = secret[${escPath}].val` + const clear = `secret[${escPath}].val = undefined` + return ` + if (secret[${escPath}].val !== undefined) { + try { ${reset} } catch (e) {} + ${clear} + } + ` + }).join('') +} + +/** + * Creates the body of the restore function + * + * Restoration of the redacted object happens + * backwards, in reverse order of redactions, + * so that repeated redactions on the same object + * property can be eventually rolled back to the + * original value. + * + * This way dynamic redactions are restored first, + * starting from the last one working backwards and + * followed by the static ones. + * + * @returns {string} the body of the restore function + */ +function restoreTmpl (resetters, paths, hasWildcards) { + const dynamicReset = hasWildcards === true ? ` + const keys = Object.keys(secret) + const len = keys.length + for (var i = len - 1; i >= ${paths.length}; i--) { + const k = keys[i] + const o = secret[k] + if (o.flat === true) this.groupRestore(o) + else this.nestedRestore(o) + secret[k] = null + } + ` : '' + + return ` + const secret = this.secret + ${dynamicReset} + ${resetters} + return o + ` +} /***/ }), -/***/ 31621: +/***/ 9158: /***/ ((module) => { "use strict"; -module.exports = (flag, argv = process.argv) => { - const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); - const position = argv.indexOf(prefix + flag); - const terminatorPosition = argv.indexOf('--'); - return position !== -1 && (terminatorPosition === -1 || position < terminatorPosition); -}; +module.exports = /[^.[\]]+|\[((?:.)*?)\]/g + +/* +Regular expression explanation: + +Alt 1: /[^.[\]]+/ - Match one or more characters that are *not* a dot (.) + opening square bracket ([) or closing square bracket (]) + +Alt 2: /\[((?:.)*?)\]/ - If the char IS dot or square bracket, then create a capture + group (which will be capture group $1) that matches anything + within square brackets. Expansion is lazy so it will + stop matching as soon as the first closing bracket is met `]` + (rather than continuing to match until the final closing bracket). +*/ /***/ }), -/***/ 76339: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 41012: +/***/ ((module) => { "use strict"; -var bind = __nccwpck_require__(88334); +module.exports = state -module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); +function state (o) { + const { + secret, + censor, + compileRestore, + serialize, + groupRedact, + nestedRedact, + wildcards, + wcLen + } = o + const builder = [{ secret, censor, compileRestore }] + if (serialize !== false) builder.push({ serialize }) + if (wcLen > 0) builder.push({ groupRedact, nestedRedact, wildcards, wcLen }) + return Object.assign(...builder) +} /***/ }), -/***/ 95193: +/***/ 74174: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -/*! - * http-errors - * Copyright(c) 2014 Jonathan Ong - * Copyright(c) 2016 Douglas Christopher Wilson - * MIT Licensed - */ +const { createContext, runInContext } = __nccwpck_require__(92184) -/** - * Module dependencies. - * @private - */ +module.exports = validator -var deprecate = __nccwpck_require__(18883)('http-errors') -var setPrototypeOf = __nccwpck_require__(40414) -var statuses = __nccwpck_require__(57415) -var inherits = __nccwpck_require__(44124) -var toIdentifier = __nccwpck_require__(46399) +function validator (opts = {}) { + const { + ERR_PATHS_MUST_BE_STRINGS = () => 'fast-redact - Paths must be (non-empty) strings', + ERR_INVALID_PATH = (s) => `fast-redact – Invalid path (${s})` + } = opts -/** - * Module exports. - * @public - */ + return function validate ({ paths }) { + paths.forEach((s) => { + if (typeof s !== 'string') { + throw Error(ERR_PATHS_MUST_BE_STRINGS()) + } + try { + if (/〇/.test(s)) throw Error() + const proxy = new Proxy({}, { get: () => proxy, set: () => { throw Error() } }) + const expr = (s[0] === '[' ? '' : '.') + s.replace(/^\*/, '〇').replace(/\.\*/g, '.〇').replace(/\[\*\]/g, '[〇]') + if (/\n|\r|;/.test(expr)) throw Error() + if (/\/\*/.test(expr)) throw Error() + runInContext(` + (function () { + 'use strict' + o${expr} + if ([o${expr}].length !== 1) throw Error() + })() + `, createContext({ o: proxy, 〇: null }), { + codeGeneration: { strings: false, wasm: false } + }) + } catch (e) { + throw Error(ERR_INVALID_PATH(s)) + } + }) + } +} -module.exports = createError -module.exports.HttpError = createHttpErrorConstructor() -// Populate exports for all constructors -populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) +/***/ }), -/** - * Get the code class of a status code. - * @private - */ +/***/ 17676: +/***/ ((module) => { -function codeClass (status) { - return Number(String(status).charAt(0) + '00') +module.exports = stringify +stringify.default = stringify +stringify.stable = deterministicStringify +stringify.stableStringify = deterministicStringify + +var arr = [] +var replacerStack = [] + +// Regular stringify +function stringify (obj, replacer, spacer) { + decirc(obj, '', [], undefined) + var res + try { + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer) + } else { + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer) + } + } catch (_) { + return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') + } finally { + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } + } + } + return res +} +function decirc (val, k, stack, parent) { + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: '[Circular]' }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k]) + } + } else { + parent[k] = '[Circular]' + arr.push([parent, k, val]) + } + return + } + } + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + decirc(val[i], i, stack, val) + } + } else { + var keys = Object.keys(val) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + decirc(val[key], key, stack, val) + } + } + stack.pop() + } } -/** - * Create a new HTTP Error. - * - * @returns {Error} - * @public - */ +// Stable-stringify +function compareFunction (a, b) { + if (a < b) { + return -1 + } + if (a > b) { + return 1 + } + return 0 +} -function createError () { - // so much arity going on ~_~ - var err - var msg - var status = 500 - var props = {} - for (var i = 0; i < arguments.length; i++) { - var arg = arguments[i] - if (arg instanceof Error) { - err = arg - status = err.status || err.statusCode || status - continue +function deterministicStringify (obj, replacer, spacer) { + var tmp = deterministicDecirc(obj, '', [], undefined) || obj + var res + try { + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer) + } else { + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer) } - switch (typeof arg) { - case 'string': - msg = arg - break - case 'number': - status = arg - if (i !== 0) { - deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)') + } catch (_) { + return JSON.stringify('[unable to serialize, circular reference is too complex to analyze]') + } finally { + // Ensure that we restore the object as it was. + while (arr.length !== 0) { + var part = arr.pop() + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]) + } else { + part[0][part[1]] = part[2] + } + } + } + return res +} + +function deterministicDecirc (val, k, stack, parent) { + var i + if (typeof val === 'object' && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k) + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: '[Circular]' }) + arr.push([parent, k, val, propertyDescriptor]) + } else { + replacerStack.push([val, k]) + } + } else { + parent[k] = '[Circular]' + arr.push([parent, k, val]) } - break - case 'object': - props = arg - break + return + } + } + try { + if (typeof val.toJSON === 'function') { + return + } + } catch (_) { + return + } + stack.push(val) + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + deterministicDecirc(val[i], i, stack, val) + } + } else { + // Create a temporary object in the required way + var tmp = {} + var keys = Object.keys(val).sort(compareFunction) + for (i = 0; i < keys.length; i++) { + var key = keys[i] + deterministicDecirc(val[key], key, stack, val) + tmp[key] = val[key] + } + if (parent !== undefined) { + arr.push([parent, k, val]) + parent[k] = tmp + } else { + return tmp + } } + stack.pop() } +} - if (typeof status === 'number' && (status < 400 || status >= 600)) { - deprecate('non-error status code; use only 4xx or 5xx status codes') +// wraps replacer function to handle values we couldn't replace +// and mark them as [Circular] +function replaceGetterValues (replacer) { + replacer = replacer !== undefined ? replacer : function (k, v) { return v } + return function (key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i] + if (part[1] === key && part[0] === val) { + val = '[Circular]' + replacerStack.splice(i, 1) + break + } + } + } + return replacer.call(this, key, val) } +} - if (typeof status !== 'number' || - (!statuses[status] && (status < 400 || status >= 600))) { - status = 500 - } - // constructor - var HttpError = createError[status] || createError[codeClass(status)] +/***/ }), - if (!err) { - // create error - err = HttpError - ? new HttpError(msg) - : new Error(msg || statuses[status]) - Error.captureStackTrace(err, createError) - } +/***/ 34578: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - if (!HttpError || !(err instanceof HttpError) || err.status !== status) { - // add properties to generic error - err.expose = status < 500 - err.status = err.statusCode = status - } +"use strict"; - for (var key in props) { - if (key !== 'status' && key !== 'statusCode') { - err[key] = props[key] - } - } +/* +Copyright (c) 2014 Petka Antonov - return err -} +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: -/** - * Create HTTP error abstract base class. - * @private - */ +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. -function createHttpErrorConstructor () { - function HttpError () { - throw new TypeError('cannot construct abstract class') - } +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. +*/ +function Url() { + //For more efficient internal representation and laziness. + //The non-underscore versions of these properties are accessor functions + //defined on the prototype. + this._protocol = null; + this._href = ""; + this._port = -1; + this._query = null; - inherits(HttpError, Error) + this.auth = null; + this.slashes = null; + this.host = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.pathname = null; - return HttpError + this._prependSlash = false; } -/** - * Create a constructor for a client error. - * @private - */ +var querystring = __nccwpck_require__(71191); -function createClientErrorConstructor (HttpError, name, code) { - var className = name.match(/Error$/) ? name : name + 'Error' +Url.queryString = querystring; - function ClientError (message) { - // create the error object - var msg = message != null ? message : statuses[code] - var err = new Error(msg) +Url.prototype.parse = +function Url$parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) { + if (typeof str !== "string") { + throw new TypeError("Parameter 'url' must be a string, not " + + typeof str); + } + var start = 0; + var end = str.length - 1; - // capture a stack trace to the construction point - Error.captureStackTrace(err, ClientError) + //Trim leading and trailing ws + while (str.charCodeAt(start) <= 0x20 /*' '*/) start++; + while (str.charCodeAt(end) <= 0x20 /*' '*/) end--; - // adjust the [[Prototype]] - setPrototypeOf(err, ClientError.prototype) + start = this._parseProtocol(str, start, end); - // redefine the error message - Object.defineProperty(err, 'message', { - enumerable: true, - configurable: true, - value: msg, - writable: true - }) + //Javascript doesn't have host + if (this._protocol !== "javascript") { + start = this._parseHost(str, start, end, hostDenotesSlash); + var proto = this._protocol; + if (!this.hostname && + (this.slashes || (proto && !slashProtocols[proto]))) { + this.hostname = this.host = ""; + } + } - // redefine the error name - Object.defineProperty(err, 'name', { - enumerable: false, - configurable: true, - value: className, - writable: true - }) + if (start <= end) { + var ch = str.charCodeAt(start); - return err - } + if (ch === 0x2F /*'/'*/ || ch === 0x5C /*'\'*/) { + this._parsePath(str, start, end, disableAutoEscapeChars); + } + else if (ch === 0x3F /*'?'*/) { + this._parseQuery(str, start, end, disableAutoEscapeChars); + } + else if (ch === 0x23 /*'#'*/) { + this._parseHash(str, start, end, disableAutoEscapeChars); + } + else if (this._protocol !== "javascript") { + this._parsePath(str, start, end, disableAutoEscapeChars); + } + else { //For javascript the pathname is just the rest of it + this.pathname = str.slice(start, end + 1 ); + } - inherits(ClientError, HttpError) - nameFunc(ClientError, className) + } - ClientError.prototype.status = code - ClientError.prototype.statusCode = code - ClientError.prototype.expose = true + if (!this.pathname && this.hostname && + this._slashProtocols[this._protocol]) { + this.pathname = "/"; + } - return ClientError -} + if (parseQueryString) { + var search = this.search; + if (search == null) { + search = this.search = ""; + } + if (search.charCodeAt(0) === 0x3F /*'?'*/) { + search = search.slice(1); + } + //This calls a setter function, there is no .query data property + this.query = Url.queryString.parse(search); + } +}; -/** - * Create a constructor for a server error. - * @private - */ +Url.prototype.resolve = function Url$resolve(relative) { + return this.resolveObject(Url.parse(relative, false, true)).format(); +}; -function createServerErrorConstructor (HttpError, name, code) { - var className = name.match(/Error$/) ? name : name + 'Error' +Url.prototype.format = function Url$format() { + var auth = this.auth || ""; - function ServerError (message) { - // create the error object - var msg = message != null ? message : statuses[code] - var err = new Error(msg) + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ":"); + auth += "@"; + } - // capture a stack trace to the construction point - Error.captureStackTrace(err, ServerError) + var protocol = this.protocol || ""; + var pathname = this.pathname || ""; + var hash = this.hash || ""; + var search = this.search || ""; + var query = ""; + var hostname = this.hostname || ""; + var port = this.port || ""; + var host = false; + var scheme = ""; - // adjust the [[Prototype]] - setPrototypeOf(err, ServerError.prototype) + //Cache the result of the getter function + var q = this.query; + if (q && typeof q === "object") { + query = Url.queryString.stringify(q); + } - // redefine the error message - Object.defineProperty(err, 'message', { - enumerable: true, - configurable: true, - value: msg, - writable: true - }) + if (!search) { + search = query ? "?" + query : ""; + } - // redefine the error name - Object.defineProperty(err, 'name', { - enumerable: false, - configurable: true, - value: className, - writable: true - }) + if (protocol && protocol.charCodeAt(protocol.length - 1) !== 0x3A /*':'*/) + protocol += ":"; - return err - } + if (this.host) { + host = auth + this.host; + } + else if (hostname) { + var ip6 = hostname.indexOf(":") > -1; + if (ip6) hostname = "[" + hostname + "]"; + host = auth + hostname + (port ? ":" + port : ""); + } - inherits(ServerError, HttpError) - nameFunc(ServerError, className) + var slashes = this.slashes || + ((!protocol || + slashProtocols[protocol]) && host !== false); - ServerError.prototype.status = code - ServerError.prototype.statusCode = code - ServerError.prototype.expose = false - return ServerError -} + if (protocol) scheme = protocol + (slashes ? "//" : ""); + else if (slashes) scheme = "//"; -/** - * Set the name of a function, if possible. - * @private - */ + if (slashes && pathname && pathname.charCodeAt(0) !== 0x2F /*'/'*/) { + pathname = "/" + pathname; + } + if (search && search.charCodeAt(0) !== 0x3F /*'?'*/) + search = "?" + search; + if (hash && hash.charCodeAt(0) !== 0x23 /*'#'*/) + hash = "#" + hash; -function nameFunc (func, name) { - var desc = Object.getOwnPropertyDescriptor(func, 'name') + pathname = escapePathName(pathname); + search = escapeSearch(search); - if (desc && desc.configurable) { - desc.value = name - Object.defineProperty(func, 'name', desc) - } -} + return scheme + (host === false ? "" : host) + pathname + search + hash; +}; -/** - * Populate the exports object with constructors for every error class. - * @private - */ +Url.prototype.resolveObject = function Url$resolveObject(relative) { + if (typeof relative === "string") + relative = Url.parse(relative, false, true); -function populateConstructorExports (exports, codes, HttpError) { - codes.forEach(function forEachCode (code) { - var CodeError - var name = toIdentifier(statuses[code]) + var result = this._clone(); - switch (codeClass(code)) { - case 400: - CodeError = createClientErrorConstructor(HttpError, name, code) - break - case 500: - CodeError = createServerErrorConstructor(HttpError, name, code) - break + // 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 = ""; + return result; } - if (CodeError) { - // export the constructor - exports[code] = CodeError - exports[name] = CodeError + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative._protocol) { + relative._copyPropsTo(result, true); + + if (slashProtocols[result._protocol] && + result.hostname && !result.pathname) { + result.pathname = "/"; + } + result._href = ""; + return result; } - }) - // backwards-compatibility - exports["I'mateapot"] = deprecate.function(exports.ImATeapot, - '"I\'mateapot"; use "ImATeapot" instead') -} + 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 (!slashProtocols[relative._protocol]) { + relative._copyPropsTo(result, false); + result._href = ""; + return result; + } + result._protocol = relative._protocol; + if (!relative.host && relative._protocol !== "javascript") { + var 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.host = relative.host || ""; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result._port = relative._port; + result.slashes = result.slashes || relative.slashes; + result._href = ""; + return result; + } -/***/ 15098: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + var isSourceAbs = + (result.pathname && result.pathname.charCodeAt(0) === 0x2F /*'/'*/); + var isRelAbs = ( + relative.host || + (relative.pathname && + relative.pathname.charCodeAt(0) === 0x2F /*'/'*/) + ); + var mustEndAbs = (isRelAbs || isSourceAbs || + (result.host && relative.pathname)); -"use strict"; + var removeAllDots = mustEndAbs; -var __awaiter = (this && this.__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()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const net_1 = __importDefault(__nccwpck_require__(11631)); -const tls_1 = __importDefault(__nccwpck_require__(4016)); -const url_1 = __importDefault(__nccwpck_require__(78835)); -const assert_1 = __importDefault(__nccwpck_require__(42357)); -const debug_1 = __importDefault(__nccwpck_require__(38237)); -const agent_base_1 = __nccwpck_require__(49690); -const parse_proxy_response_1 = __importDefault(__nccwpck_require__(595)); -const debug = debug_1.default('https-proxy-agent:agent'); -/** - * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to - * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. - * - * Outgoing HTTP requests are first tunneled through the proxy server using the - * `CONNECT` HTTP request method to establish a connection to the proxy server, - * and then the proxy server connects to the destination target and issues the - * HTTP request from the proxy server. - * - * `https:` requests have their socket connection upgraded to TLS once - * the connection to the proxy server has been established. - * - * @api public - */ -class HttpsProxyAgent extends agent_base_1.Agent { - constructor(_opts) { - let opts; - if (typeof _opts === 'string') { - opts = url_1.default.parse(_opts); - } - else { - opts = _opts; - } - if (!opts) { - throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); + var srcPath = result.pathname && result.pathname.split("/") || []; + var relPath = relative.pathname && relative.pathname.split("/") || []; + var psychotic = result._protocol && !slashProtocols[result._protocol]; + + // 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 = -1; + if (result.host) { + if (srcPath[0] === "") srcPath[0] = result.host; + else srcPath.unshift(result.host); } - debug('creating new HttpsProxyAgent instance: %o', opts); - super(opts); - const proxy = Object.assign({}, opts); - // If `true`, then connect to the proxy server over TLS. - // Defaults to `false`. - this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); - // Prefer `hostname` over `host`, and set the `port` if needed. - proxy.host = proxy.hostname || proxy.host; - if (typeof proxy.port === 'string') { - proxy.port = parseInt(proxy.port, 10); + result.host = ""; + if (relative._protocol) { + relative.hostname = ""; + relative._port = -1; + if (relative.host) { + if (relPath[0] === "") relPath[0] = relative.host; + else relPath.unshift(relative.host); + } + relative.host = ""; } - if (!proxy.port && proxy.host) { - proxy.port = this.secureProxy ? 443 : 80; + mustEndAbs = mustEndAbs && (relPath[0] === "" || srcPath[0] === ""); + } + + if (isRelAbs) { + // it"s absolute. + result.host = relative.host ? + relative.host : result.host; + result.hostname = relative.hostname ? + relative.hostname : result.hostname; + result.search = relative.search; + 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; + } else if (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 especialy happens in cases like + //url.resolveObject("mailto:local1@domain1", "local2@domain2") + var authInHost = result.host && result.host.indexOf("@") > 0 ? + result.host.split("@") : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); + } } - // ALPN is supported by Node.js >= v5. - // attempt to negotiate http/1.1 for proxy servers that support http/2 - if (this.secureProxy && !('ALPNProtocols' in proxy)) { - proxy.ALPNProtocols = ['http 1.1']; + result.search = relative.search; + result._href = ""; + return result; + } + + if (!srcPath.length) { + // no path at all. easy. + // we"ve already handled the other stuff above. + result.pathname = null; + result._href = ""; + 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) && (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 (proxy.host && proxy.path) { - // If both a `host` and `path` are specified then it's most likely - // the result of a `url.parse()` call... we need to remove the - // `path` portion so that `net.connect()` doesn't attempt to open - // that as a Unix socket file. - delete proxy.path; - delete proxy.pathname; + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift(".."); } - this.proxy = proxy; } - /** - * Called when the node-core HTTP client library is creating a - * new HTTP request. - * - * @api protected - */ - callback(req, opts) { - return __awaiter(this, void 0, void 0, function* () { - const { proxy, secureProxy } = this; - // Create a socket connection to the proxy server. - let socket; - if (secureProxy) { - debug('Creating `tls.Socket`: %o', proxy); - socket = tls_1.default.connect(proxy); - } - else { - debug('Creating `net.Socket`: %o', proxy); - socket = net_1.default.connect(proxy); - } - const headers = Object.assign({}, proxy.headers); - const hostname = `${opts.host}:${opts.port}`; - let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; - // Inject the `Proxy-Authorization` header if necessary. - if (proxy.auth) { - headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; - } - // The `Host` header should only include the port - // number when it is not the default port. - let { host, port, secureEndpoint } = opts; - if (!isDefaultPort(port, secureEndpoint)) { - host += `:${port}`; - } - headers.Host = host; - headers.Connection = 'close'; - for (const name of Object.keys(headers)) { - payload += `${name}: ${headers[name]}\r\n`; - } - const proxyResponsePromise = parse_proxy_response_1.default(socket); - socket.write(`${payload}\r\n`); - const { statusCode, buffered } = yield proxyResponsePromise; - if (statusCode === 200) { - req.once('socket', resume); - if (opts.secureEndpoint) { - const servername = opts.servername || opts.host; - if (!servername) { - throw new Error('Could not determine "servername"'); - } - // The proxy is connecting to a TLS server, so upgrade - // this socket connection to a TLS connection. - debug('Upgrading socket connection to TLS'); - return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, - servername })); - } - return socket; - } - // Some other status code that's not 200... need to re-play the HTTP - // header "data" events onto the socket once the HTTP machinery is - // attached so that the node core `http` can parse and handle the - // error status code. - // Close the original socket, and a new "fake" socket is returned - // instead, so that the proxy doesn't get the HTTP request - // written to it (which may contain `Authorization` headers or other - // sensitive data). - // - // See: https://hackerone.com/reports/541502 - socket.destroy(); - const fakeSocket = new net_1.default.Socket(); - fakeSocket.readable = true; - // Need to wait for the "socket" event to re-play the "data" events. - req.once('socket', (s) => { - debug('replaying proxy buffer for failed request'); - assert_1.default(s.listenerCount('data') > 0); - // Replay the "buffered" Buffer onto the fake `socket`, since at - // this point the HTTP module machinery has been hooked up for - // the user. - s.push(buffered); - s.push(null); - }); - return fakeSocket; - }); + + if (mustEndAbs && srcPath[0] !== "" && + (!srcPath[0] || srcPath[0].charCodeAt(0) !== 0x2F /*'/'*/)) { + srcPath.unshift(""); } -} -exports.default = HttpsProxyAgent; -function resume(socket) { - socket.resume(); -} -function isDefaultPort(port, secure) { - return Boolean((!secure && port === 80) || (secure && port === 443)); -} -function isHTTPS(protocol) { - return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; -} -function omit(obj, ...keys) { - const ret = {}; - let key; - for (key in obj) { - if (!keys.includes(key)) { - ret[key] = obj[key]; + + if (hasTrailingSlash && (srcPath.join("/").substr(-1) !== "/")) { + srcPath.push(""); + } + + var isAbsolute = srcPath[0] === "" || + (srcPath[0] && srcPath[0].charCodeAt(0) === 0x2F /*'/'*/); + + // 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 especialy happens in cases like + //url.resolveObject("mailto:local1@domain1", "local2@domain2") + var authInHost = result.host && result.host.indexOf("@") > 0 ? + result.host.split("@") : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.host = result.hostname = authInHost.shift(); } } - return ret; -} -//# sourceMappingURL=agent.js.map -/***/ }), + mustEndAbs = mustEndAbs || (result.host && srcPath.length); -/***/ 77219: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(""); + } -"use strict"; + result.pathname = srcPath.length === 0 ? null : srcPath.join("/"); + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result._href = ""; + return result; +}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; +var punycode = __nccwpck_require__(94213); +Url.prototype._hostIdna = function Url$_hostIdna(hostname) { + // 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. + return punycode.toASCII(hostname); }; -const agent_1 = __importDefault(__nccwpck_require__(15098)); -function createHttpsProxyAgent(opts) { - return new agent_1.default(opts); -} -(function (createHttpsProxyAgent) { - createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; - createHttpsProxyAgent.prototype = agent_1.default.prototype; -})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); -module.exports = createHttpsProxyAgent; -//# sourceMappingURL=index.js.map -/***/ }), +var escapePathName = Url.prototype._escapePathName = +function Url$_escapePathName(pathname) { + if (!containsCharacter2(pathname, 0x23 /*'#'*/, 0x3F /*'?'*/)) { + return pathname; + } + //Avoid closure creation to keep this inlinable + return _escapePath(pathname); +}; -/***/ 595: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { +var escapeSearch = Url.prototype._escapeSearch = +function Url$_escapeSearch(search) { + if (!containsCharacter2(search, 0x23 /*'#'*/, -1)) return search; + //Avoid closure creation to keep this inlinable + return _escapeSearch(search); +}; -"use strict"; +Url.prototype._parseProtocol = function Url$_parseProtocol(str, start, end) { + var doLowerCase = false; + var protocolCharacters = this._protocolCharacters; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const debug_1 = __importDefault(__nccwpck_require__(38237)); -const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); -function parseProxyResponse(socket) { - return new Promise((resolve, reject) => { - // we need to buffer any HTTP traffic that happens with the proxy before we get - // the CONNECT response, so that if the response is anything other than an "200" - // response code, then we can re-play the "data" events on the socket once the - // HTTP parser is hooked up... - let buffersLength = 0; - const buffers = []; - function read() { - const b = socket.read(); - if (b) - ondata(b); - else - socket.once('readable', read); - } - function cleanup() { - socket.removeListener('end', onend); - socket.removeListener('error', onerror); - socket.removeListener('close', onclose); - socket.removeListener('readable', read); - } - function onclose(err) { - debug('onclose had error %o', err); - } - function onend() { - debug('onend'); + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); + + if (ch === 0x3A /*':'*/) { + var protocol = str.slice(start, i); + if (doLowerCase) protocol = protocol.toLowerCase(); + this._protocol = protocol; + return i + 1; } - function onerror(err) { - cleanup(); - debug('onerror %o', err); - reject(err); + else if (protocolCharacters[ch] === 1) { + if (ch < 0x61 /*'a'*/) + doLowerCase = true; } - function ondata(b) { - buffers.push(b); - buffersLength += b.length; - const buffered = Buffer.concat(buffers, buffersLength); - const endOfHeaders = buffered.indexOf('\r\n\r\n'); - if (endOfHeaders === -1) { - // keep buffering - debug('have not received end of HTTP headers yet...'); - read(); - return; - } - const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); - const statusCode = +firstLine.split(' ')[1]; - debug('got proxy server response: %o', firstLine); - resolve({ - statusCode, - buffered - }); + else { + return start; } - socket.on('error', onerror); - socket.on('close', onclose); - socket.on('end', onend); - read(); - }); -} -exports.default = parseProxyResponse; -//# sourceMappingURL=parse-proxy-response.js.map - -/***/ }), - -/***/ 39695: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; + } + return start; +}; -var Buffer = __nccwpck_require__(15118).Buffer; +Url.prototype._parseAuth = function Url$_parseAuth(str, start, end, decode) { + var auth = str.slice(start, end + 1); + if (decode) { + auth = decodeURIComponent(auth); + } + this.auth = auth; +}; -// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. -// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. -// To save memory and loading time, we read table files only when requested. +Url.prototype._parsePort = function Url$_parsePort(str, start, end) { + //Internal format is integer for more efficient parsing + //and for efficient trimming of leading zeros + var port = 0; + //Distinguish between :0 and : (no port number at all) + var hadChars = false; + var validPort = true; -exports._dbcs = DBCSCodec; + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); -var UNASSIGNED = -1, - GB18030_CODE = -2, - SEQ_START = -10, - NODE_START = -1000, - UNASSIGNED_NODE = new Array(0x100), - DEF_CHAR = -1; + if (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/) { + port = (10 * port) + (ch - 0x30 /*'0'*/); + hadChars = true; + } + else { + validPort = false; + if (ch === 0x5C/*'\'*/ || ch === 0x2F/*'/'*/) { + validPort = true; + } + break; + } -for (var i = 0; i < 0x100; i++) - UNASSIGNED_NODE[i] = UNASSIGNED; + } + if ((port === 0 && !hadChars) || !validPort) { + if (!validPort) { + this._port = -2; + } + return 0; + } + this._port = port; + return i - start; +}; -// Class DBCSCodec reads and initializes mapping tables. -function DBCSCodec(codecOptions, iconv) { - this.encodingName = codecOptions.encodingName; - if (!codecOptions) - throw new Error("DBCS codec is called without the data.") - if (!codecOptions.table) - throw new Error("Encoding '" + this.encodingName + "' has no data."); +Url.prototype._parseHost = +function Url$_parseHost(str, start, end, slashesDenoteHost) { + var hostEndingCharacters = this._hostEndingCharacters; + var first = str.charCodeAt(start); + var second = str.charCodeAt(start + 1); + if ((first === 0x2F /*'/'*/ || first === 0x5C /*'\'*/) && + (second === 0x2F /*'/'*/ || second === 0x5C /*'\'*/)) { + this.slashes = true; - // Load tables. - var mappingTable = codecOptions.table(); + //The string starts with // + if (start === 0) { + //The string is just "//" + if (end < 2) return start; + //If slashes do not denote host and there is no auth, + //there is no host when the string starts with // + var hasAuth = + containsCharacter(str, 0x40 /*'@'*/, 2, hostEndingCharacters); + if (!hasAuth && !slashesDenoteHost) { + this.slashes = null; + return start; + } + } + //There is a host that starts after the // + start += 2; + } + //If there is no slashes, there is no hostname if + //1. there was no protocol at all + else if (!this._protocol || + //2. there was a protocol that requires slashes + //e.g. in 'http:asd' 'asd' is not a hostname + slashProtocols[this._protocol] + ) { + return start; + } + var doLowerCase = false; + var idna = false; + var hostNameStart = start; + var hostNameEnd = end; + var lastCh = -1; + var portLength = 0; + var charsAfterDot = 0; + var authNeedsDecoding = false; - // Decode tables: MBCS -> Unicode. + var j = -1; - // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. - // Trie root is decodeTables[0]. - // Values: >= 0 -> unicode character code. can be > 0xFFFF - // == UNASSIGNED -> unknown/unassigned sequence. - // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. - // <= NODE_START -> index of the next node in our trie to process next byte. - // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. - this.decodeTables = []; - this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. + //Find the last occurrence of an @-sign until hostending character is met + //also mark if decoding is needed for the auth portion + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); - // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. - this.decodeTableSeq = []; + if (ch === 0x40 /*'@'*/) { + j = i; + } + //This check is very, very cheap. Unneeded decodeURIComponent is very + //very expensive + else if (ch === 0x25 /*'%'*/) { + authNeedsDecoding = true; + } + else if (hostEndingCharacters[ch] === 1) { + break; + } + } - // Actual mapping tables consist of chunks. Use them to fill up decode tables. - for (var i = 0; i < mappingTable.length; i++) - this._addDecodeChunk(mappingTable[i]); + //@-sign was found at index j, everything to the left from it + //is auth part + if (j > -1) { + this._parseAuth(str, start, j - 1, authNeedsDecoding); + //hostname starts after the last @-sign + start = hostNameStart = j + 1; + } - this.defaultCharUnicode = iconv.defaultCharUnicode; + //Host name is starting with a [ + if (str.charCodeAt(start) === 0x5B /*'['*/) { + for (var i = start + 1; i <= end; ++i) { + var ch = str.charCodeAt(i); - - // Encode tables: Unicode -> DBCS. + //Assume valid IP6 is between the brackets + if (ch === 0x5D /*']'*/) { + if (str.charCodeAt(i + 1) === 0x3A /*':'*/) { + portLength = this._parsePort(str, i + 2, end) + 1; + } + var hostname = str.slice(start + 1, i).toLowerCase(); + this.hostname = hostname; + this.host = this._port > 0 ? + "[" + hostname + "]:" + this._port : + "[" + hostname + "]"; + this.pathname = "/"; + return i + portLength + 1; + } + } + //Empty hostname, [ starts a path + return start; + } - // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. - // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. - // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). - // == UNASSIGNED -> no conversion found. Output a default char. - // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. - this.encodeTable = []; - - // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of - // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key - // means end of sequence (needed when one sequence is a strict subsequence of another). - // Objects are kept separately from encodeTable to increase performance. - this.encodeTableSeq = []; + for (var i = start; i <= end; ++i) { + if (charsAfterDot > 62) { + this.hostname = this.host = str.slice(start, i); + return i; + } + var ch = str.charCodeAt(i); - // Some chars can be decoded, but need not be encoded. - var skipEncodeChars = {}; - if (codecOptions.encodeSkipVals) - for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { - var val = codecOptions.encodeSkipVals[i]; - if (typeof val === 'number') - skipEncodeChars[val] = true; - else - for (var j = val.from; j <= val.to; j++) - skipEncodeChars[j] = true; + if (ch === 0x3A /*':'*/) { + portLength = this._parsePort(str, i + 1, end) + 1; + hostNameEnd = i - 1; + break; + } + else if (ch < 0x61 /*'a'*/) { + if (ch === 0x2E /*'.'*/) { + //Node.js ignores this error + /* + if (lastCh === DOT || lastCh === -1) { + this.hostname = this.host = ""; + return start; + } + */ + charsAfterDot = -1; + } + else if (0x41 /*'A'*/ <= ch && ch <= 0x5A /*'Z'*/) { + doLowerCase = true; + } + //Valid characters other than ASCII letters -, _, +, 0-9 + else if (!(ch === 0x2D /*'-'*/ || + ch === 0x5F /*'_'*/ || + ch === 0x2B /*'+'*/ || + (0x30 /*'0'*/ <= ch && ch <= 0x39 /*'9'*/)) + ) { + if (hostEndingCharacters[ch] === 0 && + this._noPrependSlashHostEnders[ch] === 0) { + this._prependSlash = true; + } + hostNameEnd = i - 1; + break; + } + } + else if (ch >= 0x7B /*'{'*/) { + if (ch <= 0x7E /*'~'*/) { + if (this._noPrependSlashHostEnders[ch] === 0) { + this._prependSlash = true; + } + hostNameEnd = i - 1; + break; + } + idna = true; } - - // Use decode trie to recursively fill out encode tables. - this._fillEncodeTable(0, 0, skipEncodeChars); - - // Add more encoding pairs when needed. - if (codecOptions.encodeAdd) { - for (var uChar in codecOptions.encodeAdd) - if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) - this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); + lastCh = ch; + charsAfterDot++; } - this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; - if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; - if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); + //Node.js ignores this error + /* + if (lastCh === DOT) { + hostNameEnd--; + } + */ + if (hostNameEnd + 1 !== start && + hostNameEnd - hostNameStart <= 256) { + var hostname = str.slice(hostNameStart, hostNameEnd + 1); + if (doLowerCase) hostname = hostname.toLowerCase(); + if (idna) hostname = this._hostIdna(hostname); + this.hostname = hostname; + this.host = this._port > 0 ? hostname + ":" + this._port : hostname; + } - // Load & create GB18030 tables when needed. - if (typeof codecOptions.gb18030 === 'function') { - this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. + return hostNameEnd + 1 + portLength; - // Add GB18030 decode tables. - var thirdByteNodeIdx = this.decodeTables.length; - var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); +}; - var fourthByteNodeIdx = this.decodeTables.length; - var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); +Url.prototype._copyPropsTo = function Url$_copyPropsTo(input, noProtocol) { + if (!noProtocol) { + input._protocol = this._protocol; + } + input._href = this._href; + input._port = this._port; + input._prependSlash = this._prependSlash; + input.auth = this.auth; + input.slashes = this.slashes; + input.host = this.host; + input.hostname = this.hostname; + input.hash = this.hash; + input.search = this.search; + input.pathname = this.pathname; +}; - for (var i = 0x81; i <= 0xFE; i++) { - var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; - var secondByteNode = this.decodeTables[secondByteNodeIdx]; - for (var j = 0x30; j <= 0x39; j++) - secondByteNode[j] = NODE_START - thirdByteNodeIdx; - } - for (var i = 0x81; i <= 0xFE; i++) - thirdByteNode[i] = NODE_START - fourthByteNodeIdx; - for (var i = 0x30; i <= 0x39; i++) - fourthByteNode[i] = GB18030_CODE - } -} +Url.prototype._clone = function Url$_clone() { + var ret = new Url(); + ret._protocol = this._protocol; + ret._href = this._href; + ret._port = this._port; + ret._prependSlash = this._prependSlash; + ret.auth = this.auth; + ret.slashes = this.slashes; + ret.host = this.host; + ret.hostname = this.hostname; + ret.hash = this.hash; + ret.search = this.search; + ret.pathname = this.pathname; + return ret; +}; -DBCSCodec.prototype.encoder = DBCSEncoder; -DBCSCodec.prototype.decoder = DBCSDecoder; +Url.prototype._getComponentEscaped = +function Url$_getComponentEscaped(str, start, end, isAfterQuery) { + var cur = start; + var i = start; + var ret = ""; + var autoEscapeMap = isAfterQuery ? + this._afterQueryAutoEscapeMap : this._autoEscapeMap; + for (; i <= end; ++i) { + var ch = str.charCodeAt(i); + var escaped = autoEscapeMap[ch]; -// Decoder helpers -DBCSCodec.prototype._getDecodeTrieNode = function(addr) { - var bytes = []; - for (; addr > 0; addr >>= 8) - bytes.push(addr & 0xFF); - if (bytes.length == 0) - bytes.push(0); + if (escaped !== "" && escaped !== undefined) { + if (cur < i) ret += str.slice(cur, i); + ret += escaped; + cur = i + 1; + } + } + if (cur < i + 1) ret += str.slice(cur, i); + return ret; +}; - var node = this.decodeTables[0]; - for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. - var val = node[bytes[i]]; +Url.prototype._parsePath = +function Url$_parsePath(str, start, end, disableAutoEscapeChars) { + var pathStart = start; + var pathEnd = end; + var escape = false; + var autoEscapeCharacters = this._autoEscapeCharacters; + var prePath = this._port === -2 ? "/:" : ""; - if (val == UNASSIGNED) { // Create new node. - node[bytes[i]] = NODE_START - this.decodeTables.length; - this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); + if (ch === 0x23 /*'#'*/) { + this._parseHash(str, i, end, disableAutoEscapeChars); + pathEnd = i - 1; + break; } - else if (val <= NODE_START) { // Existing node. - node = this.decodeTables[NODE_START - val]; + else if (ch === 0x3F /*'?'*/) { + this._parseQuery(str, i, end, disableAutoEscapeChars); + pathEnd = i - 1; + break; + } + else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { + escape = true; } - else - throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); } - return node; -} + if (pathStart > pathEnd) { + this.pathname = prePath === "" ? "/" : prePath; + return; + } -DBCSCodec.prototype._addDecodeChunk = function(chunk) { - // First element of chunk is the hex mbcs code where we start. - var curAddr = parseInt(chunk[0], 16); + var path; + if (escape) { + path = this._getComponentEscaped(str, pathStart, pathEnd, false); + } + else { + path = str.slice(pathStart, pathEnd + 1); + } + this.pathname = prePath === "" + ? (this._prependSlash ? "/" + path : path) + : prePath + path; +}; - // Choose the decoding node where we'll write our chars. - var writeTable = this._getDecodeTrieNode(curAddr); - curAddr = curAddr & 0xFF; +Url.prototype._parseQuery = function Url$_parseQuery(str, start, end, disableAutoEscapeChars) { + var queryStart = start; + var queryEnd = end; + var escape = false; + var autoEscapeCharacters = this._autoEscapeCharacters; - // Write all other elements of the chunk to the table. - for (var k = 1; k < chunk.length; k++) { - var part = chunk[k]; - if (typeof part === "string") { // String, write as-is. - for (var l = 0; l < part.length;) { - var code = part.charCodeAt(l++); - if (0xD800 <= code && code < 0xDC00) { // Decode surrogate - var codeTrail = part.charCodeAt(l++); - if (0xDC00 <= codeTrail && codeTrail < 0xE000) - writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); - else - throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); - } - else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) - var len = 0xFFF - code + 2; - var seq = []; - for (var m = 0; m < len; m++) - seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. + for (var i = start; i <= end; ++i) { + var ch = str.charCodeAt(i); - writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; - this.decodeTableSeq.push(seq); - } - else - writeTable[curAddr++] = code; // Basic char - } - } - else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. - var charCode = writeTable[curAddr - 1] + 1; - for (var l = 0; l < part; l++) - writeTable[curAddr++] = charCode++; + if (ch === 0x23 /*'#'*/) { + this._parseHash(str, i, end, disableAutoEscapeChars); + queryEnd = i - 1; + break; + } + else if (!disableAutoEscapeChars && !escape && autoEscapeCharacters[ch] === 1) { + escape = true; } - else - throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); } - if (curAddr > 0xFF) - throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); -} - -// Encoder helpers -DBCSCodec.prototype._getEncodeBucket = function(uCode) { - var high = uCode >> 8; // This could be > 0xFF because of astral characters. - if (this.encodeTable[high] === undefined) - this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. - return this.encodeTable[high]; -} - -DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; - if (bucket[low] <= SEQ_START) - this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. - else if (bucket[low] == UNASSIGNED) - bucket[low] = dbcsCode; -} -DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { - - // Get the root of character tree according to first character of the sequence. - var uCode = seq[0]; - var bucket = this._getEncodeBucket(uCode); - var low = uCode & 0xFF; + if (queryStart > queryEnd) { + this.search = ""; + return; + } - var node; - if (bucket[low] <= SEQ_START) { - // There's already a sequence with - use it. - node = this.encodeTableSeq[SEQ_START-bucket[low]]; + var query; + if (escape) { + query = this._getComponentEscaped(str, queryStart, queryEnd, true); } else { - // There was no sequence object - allocate a new one. - node = {}; - if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. - bucket[low] = SEQ_START - this.encodeTableSeq.length; - this.encodeTableSeq.push(node); + query = str.slice(queryStart, queryEnd + 1); + } + this.search = query; +}; + +Url.prototype._parseHash = function Url$_parseHash(str, start, end, disableAutoEscapeChars) { + if (start > end) { + this.hash = ""; + return; } - // Traverse the character tree, allocating new nodes as needed. - for (var j = 1; j < seq.length-1; j++) { - var oldVal = node[uCode]; - if (typeof oldVal === 'object') - node = oldVal; + this.hash = disableAutoEscapeChars ? + str.slice(start, end + 1) : this._getComponentEscaped(str, start, end, true); +}; + +Object.defineProperty(Url.prototype, "port", { + get: function() { + if (this._port >= 0) { + return ("" + this._port); + } + return null; + }, + set: function(v) { + if (v == null) { + this._port = -1; + } else { - node = node[uCode] = {} - if (oldVal !== undefined) - node[DEF_CHAR] = oldVal + this._port = parseInt(v, 10); } } +}); - // Set the leaf to given dbcsCode. - uCode = seq[seq.length-1]; - node[uCode] = dbcsCode; -} - -DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { - var node = this.decodeTables[nodeIdx]; - for (var i = 0; i < 0x100; i++) { - var uCode = node[i]; - var mbCode = prefix + i; - if (skipEncodeChars[mbCode]) - continue; +Object.defineProperty(Url.prototype, "query", { + get: function() { + var query = this._query; + if (query != null) { + return query; + } + var search = this.search; - if (uCode >= 0) - this._setEncodeChar(uCode, mbCode); - else if (uCode <= NODE_START) - this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); - else if (uCode <= SEQ_START) - this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + if (search) { + if (search.charCodeAt(0) === 0x3F /*'?'*/) { + search = search.slice(1); + } + if (search !== "") { + this._query = search; + return search; + } + } + return search; + }, + set: function(v) { + this._query = v; } -} - - - -// == Encoder ================================================================== - -function DBCSEncoder(options, codec) { - // Encoder state - this.leadSurrogate = -1; - this.seqObj = undefined; - - // Static data - this.encodeTable = codec.encodeTable; - this.encodeTableSeq = codec.encodeTableSeq; - this.defaultCharSingleByte = codec.defCharSB; - this.gb18030 = codec.gb18030; -} - -DBCSEncoder.prototype.write = function(str) { - var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), - leadSurrogate = this.leadSurrogate, - seqObj = this.seqObj, nextChar = -1, - i = 0, j = 0; +}); - while (true) { - // 0. Get next character. - if (nextChar === -1) { - if (i == str.length) break; - var uCode = str.charCodeAt(i++); - } - else { - var uCode = nextChar; - nextChar = -1; +Object.defineProperty(Url.prototype, "path", { + get: function() { + var p = this.pathname || ""; + var s = this.search || ""; + if (p || s) { + return p + s; } + return (p == null && s) ? ("/" + s) : null; + }, + set: function() {} +}); - // 1. Handle surrogates. - if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. - if (uCode < 0xDC00) { // We've got lead surrogate. - if (leadSurrogate === -1) { - leadSurrogate = uCode; - continue; - } else { - leadSurrogate = uCode; - // Double lead surrogate found. - uCode = UNASSIGNED; - } - } else { // We've got trail surrogate. - if (leadSurrogate !== -1) { - uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); - leadSurrogate = -1; - } else { - // Incomplete surrogate pair - only trail surrogate found. - uCode = UNASSIGNED; - } - +Object.defineProperty(Url.prototype, "protocol", { + get: function() { + var proto = this._protocol; + return proto ? proto + ":" : proto; + }, + set: function(v) { + if (typeof v === "string") { + var end = v.length - 1; + if (v.charCodeAt(end) === 0x3A /*':'*/) { + this._protocol = v.slice(0, end); + } + else { + this._protocol = v; } } - else if (leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. - leadSurrogate = -1; + else if (v == null) { + this._protocol = null; } + } +}); - // 2. Convert uCode character. - var dbcsCode = UNASSIGNED; - if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence - var resCode = seqObj[uCode]; - if (typeof resCode === 'object') { // Sequence continues. - seqObj = resCode; - continue; +Object.defineProperty(Url.prototype, "href", { + get: function() { + var href = this._href; + if (!href) { + href = this._href = this.format(); + } + return href; + }, + set: function(v) { + this._href = v; + } +}); - } else if (typeof resCode == 'number') { // Sequence finished. Write it. - dbcsCode = resCode; +Url.parse = function Url$Parse(str, parseQueryString, hostDenotesSlash, disableAutoEscapeChars) { + if (str instanceof Url) return str; + var ret = new Url(); + ret.parse(str, !!parseQueryString, !!hostDenotesSlash, !!disableAutoEscapeChars); + return ret; +}; - } else if (resCode == undefined) { // Current character is not part of the sequence. +Url.format = function Url$Format(obj) { + if (typeof obj === "string") { + obj = Url.parse(obj); + } + if (!(obj instanceof Url)) { + return Url.prototype.format.call(obj); + } + return obj.format(); +}; - // Try default character for this sequence - resCode = seqObj[DEF_CHAR]; - if (resCode !== undefined) { - dbcsCode = resCode; // Found. Write it. - nextChar = uCode; // Current character will be written too in the next iteration. +Url.resolve = function Url$Resolve(source, relative) { + return Url.parse(source, false, true).resolve(relative); +}; - } else { - // TODO: What if we have no default? (resCode == undefined) - // Then, we should write first char of the sequence as-is and try the rest recursively. - // Didn't do it for now because no encoding has this situation yet. - // Currently, just skip the sequence and write current char. - } - } - seqObj = undefined; - } - else if (uCode >= 0) { // Regular character - var subtable = this.encodeTable[uCode >> 8]; - if (subtable !== undefined) - dbcsCode = subtable[uCode & 0xFF]; - - if (dbcsCode <= SEQ_START) { // Sequence start - seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; - continue; - } +Url.resolveObject = function Url$ResolveObject(source, relative) { + if (!source) return relative; + return Url.parse(source, false, true).resolveObject(relative); +}; - if (dbcsCode == UNASSIGNED && this.gb18030) { - // Use GB18030 algorithm to find character(s) to write. - var idx = findIdx(this.gb18030.uChars, uCode); - if (idx != -1) { - var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; - newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; - newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; - newBuf[j++] = 0x30 + dbcsCode; - continue; - } - } +function _escapePath(pathname) { + return pathname.replace(/[?#]/g, function(match) { + return encodeURIComponent(match); + }); +} + +function _escapeSearch(search) { + return search.replace(/#/g, function(match) { + return encodeURIComponent(match); + }); +} + +//Search `char1` (integer code for a character) in `string` +//starting from `fromIndex` and ending at `string.length - 1` +//or when a stop character is found +function containsCharacter(string, char1, fromIndex, stopCharacterTable) { + var len = string.length; + for (var i = fromIndex; i < len; ++i) { + var ch = string.charCodeAt(i); + + if (ch === char1) { + return true; + } + else if (stopCharacterTable[ch] === 1) { + return false; } + } + return false; +} - // 3. Write dbcsCode character. - if (dbcsCode === UNASSIGNED) - dbcsCode = this.defaultCharSingleByte; - - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else if (dbcsCode < 0x10000) { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte +//See if `char1` or `char2` (integer codes for characters) +//is contained in `string` +function containsCharacter2(string, char1, char2) { + for (var i = 0, len = string.length; i < len; ++i) { + var ch = string.charCodeAt(i); + if (ch === char1 || ch === char2) return true; + } + return false; +} + +//Makes an array of 128 uint8's which represent boolean values. +//Spec is an array of ascii code points or ascii code point ranges +//ranges are expressed as [start, end] + +//Create a table with the characters 0x30-0x39 (decimals '0' - '9') and +//0x7A (lowercaseletter 'z') as `true`: +// +//var a = makeAsciiTable([[0x30, 0x39], 0x7A]); +//a[0x30]; //1 +//a[0x15]; //0 +//a[0x35]; //1 +function makeAsciiTable(spec) { + var ret = new Uint8Array(128); + spec.forEach(function(item){ + if (typeof item === "number") { + ret[item] = 1; } else { - newBuf[j++] = dbcsCode >> 16; - newBuf[j++] = (dbcsCode >> 8) & 0xFF; - newBuf[j++] = dbcsCode & 0xFF; + var start = item[0]; + var end = item[1]; + for (var j = start; j <= end; ++j) { + ret[j] = 1; + } } - } + }); - this.seqObj = seqObj; - this.leadSurrogate = leadSurrogate; - return newBuf.slice(0, j); + return ret; } -DBCSEncoder.prototype.end = function() { - if (this.leadSurrogate === -1 && this.seqObj === undefined) - return; // All clean. Most often case. - var newBuf = Buffer.alloc(10), j = 0; +var autoEscape = ["<", ">", "\"", "`", " ", "\r", "\n", + "\t", "{", "}", "|", "\\", "^", "`", "'"]; - if (this.seqObj) { // We're in the sequence. - var dbcsCode = this.seqObj[DEF_CHAR]; - if (dbcsCode !== undefined) { // Write beginning of the sequence. - if (dbcsCode < 0x100) { - newBuf[j++] = dbcsCode; - } - else { - newBuf[j++] = dbcsCode >> 8; // high byte - newBuf[j++] = dbcsCode & 0xFF; // low byte - } - } else { - // See todo above. - } - this.seqObj = undefined; - } +var autoEscapeMap = new Array(128); - if (this.leadSurrogate !== -1) { - // Incomplete surrogate pair - only lead surrogate found. - newBuf[j++] = this.defaultCharSingleByte; - this.leadSurrogate = -1; + + +for (var i = 0, len = autoEscapeMap.length; i < len; ++i) { + autoEscapeMap[i] = ""; +} + +for (var i = 0, len = autoEscape.length; i < len; ++i) { + var c = autoEscape[i]; + var esc = encodeURIComponent(c); + if (esc === c) { + esc = escape(c); } - - return newBuf.slice(0, j); + autoEscapeMap[c.charCodeAt(0)] = esc; } +var afterQueryAutoEscapeMap = autoEscapeMap.slice(); +autoEscapeMap[0x5C /*'\'*/] = "/"; -// Export for testing -DBCSEncoder.prototype.findIdx = findIdx; +var slashProtocols = Url.prototype._slashProtocols = { + http: true, + https: true, + gopher: true, + file: true, + ftp: true, + "http:": true, + "https:": true, + "gopher:": true, + "file:": true, + "ftp:": true +}; -// == Decoder ================================================================== +//Optimize back from normalized object caused by non-identifier keys +function f(){} +f.prototype = slashProtocols; -function DBCSDecoder(options, codec) { - // Decoder state - this.nodeIdx = 0; - this.prevBuf = Buffer.alloc(0); +Url.prototype._protocolCharacters = makeAsciiTable([ + [0x61 /*'a'*/, 0x7A /*'z'*/], + [0x41 /*'A'*/, 0x5A /*'Z'*/], + 0x2E /*'.'*/, 0x2B /*'+'*/, 0x2D /*'-'*/ +]); - // Static data - this.decodeTables = codec.decodeTables; - this.decodeTableSeq = codec.decodeTableSeq; - this.defaultCharUnicode = codec.defaultCharUnicode; - this.gb18030 = codec.gb18030; -} +Url.prototype._hostEndingCharacters = makeAsciiTable([ + 0x23 /*'#'*/, 0x3F /*'?'*/, 0x2F /*'/'*/, 0x5C /*'\'*/ +]); -DBCSDecoder.prototype.write = function(buf) { - var newBuf = Buffer.alloc(buf.length*2), - nodeIdx = this.nodeIdx, - prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, - seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. - uCode; +Url.prototype._autoEscapeCharacters = makeAsciiTable( + autoEscape.map(function(v) { + return v.charCodeAt(0); + }) +); - if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. - prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); - - for (var i = 0, j = 0; i < buf.length; i++) { - var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; +//If these characters end a host name, the path will not be prepended a / +Url.prototype._noPrependSlashHostEnders = makeAsciiTable( + [ + "<", ">", "'", "`", " ", "\r", + "\n", "\t", "{", "}", "|", + "^", "`", "\"", "%", ";" + ].map(function(v) { + return v.charCodeAt(0); + }) +); - // Lookup in current trie node. - var uCode = this.decodeTables[nodeIdx][curByte]; +Url.prototype._autoEscapeMap = autoEscapeMap; +Url.prototype._afterQueryAutoEscapeMap = afterQueryAutoEscapeMap; - if (uCode >= 0) { - // Normal character, just use it. - } - else if (uCode === UNASSIGNED) { // Unknown char. - // TODO: Callback with seq. - //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); - i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). - uCode = this.defaultCharUnicode.charCodeAt(0); - } - else if (uCode === GB18030_CODE) { - var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); - var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); - var idx = findIdx(this.gb18030.gbChars, ptr); - uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; - } - else if (uCode <= NODE_START) { // Go to next trie node. - nodeIdx = NODE_START - uCode; - continue; - } - else if (uCode <= SEQ_START) { // Output a sequence of chars. - var seq = this.decodeTableSeq[SEQ_START - uCode]; - for (var k = 0; k < seq.length - 1; k++) { - uCode = seq[k]; - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - } - uCode = seq[seq.length-1]; - } - else - throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); +module.exports = Url; - // Write the character to buffer, handling higher planes using surrogate pair. - if (uCode > 0xFFFF) { - uCode -= 0x10000; - var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); - newBuf[j++] = uCodeLead & 0xFF; - newBuf[j++] = uCodeLead >> 8; +Url.replace = function Url$Replace() { + require.cache.url = { + exports: Url + }; +}; - uCode = 0xDC00 + uCode % 0x400; - } - newBuf[j++] = uCode & 0xFF; - newBuf[j++] = uCode >> 8; - // Reset trie node. - nodeIdx = 0; seqStart = i+1; - } +/***/ }), - this.nodeIdx = nodeIdx; - this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); - return newBuf.slice(0, j).toString('ucs2'); -} +/***/ 44972: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -DBCSDecoder.prototype.end = function() { - var ret = ''; +"use strict"; - // Try to parse all remaining chars. - while (this.prevBuf.length > 0) { - // Skip 1 character in the buffer. - ret += this.defaultCharUnicode; - var buf = this.prevBuf.slice(1); - // Parse remaining as usual. - this.prevBuf = Buffer.alloc(0); - this.nodeIdx = 0; - if (buf.length > 0) - ret += this.write(buf); - } +const { format } = __nccwpck_require__(31669) - this.nodeIdx = 0; - return ret; -} +function build () { + const codes = {} + const emitted = new Map() -// Binary search for GB18030. Returns largest i such that table[i] <= val. -function findIdx(table, val) { - if (table[0] > val) - return -1; + function create (name, code, message) { + if (!name) throw new Error('Fastify warning name must not be empty') + if (!code) throw new Error('Fastify warning code must not be empty') + if (!message) throw new Error('Fastify warning message must not be empty') - var l = 0, r = table.length; - while (l < r-1) { // always table[l] <= val < table[r] - var mid = l + Math.floor((r-l+1)/2); - if (table[mid] <= val) - l = mid; - else - r = mid; + code = code.toUpperCase() + + if (codes[code] !== undefined) { + throw new Error(`The code '${code}' already exist`) } - return l; -} + function buildWarnOpts (a, b, c) { + // more performant than spread (...) operator + let formatted + if (a && b && c) { + formatted = format(message, a, b, c) + } else if (a && b) { + formatted = format(message, a, b) + } else if (a) { + formatted = format(message, a) + } else { + formatted = message + } + return { + code, + name, + message: formatted + } + } -/***/ }), + emitted.set(code, false) + codes[code] = buildWarnOpts -/***/ 91386: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return codes[code] + } -"use strict"; + function emit (code, a, b, c) { + if (codes[code] === undefined) throw new Error(`The code '${code}' does not exist`) + if (emitted.get(code) === true) return + emitted.set(code, true) + const warning = codes[code](a, b, c) + process.emitWarning(warning.message, warning.name, warning.code) + } -// Description of supported double byte encodings and aliases. -// Tables are not require()-d until they are needed to speed up library load. -// require()-s are direct to support Browserify. + return { + create, + emit, + emitted + } +} -module.exports = { - - // == Japanese/ShiftJIS ==================================================== - // All japanese encodings are based on JIS X set of standards: - // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. - // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. - // Has several variations in 1978, 1983, 1990 and 1997. - // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. - // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. - // 2 planes, first is superset of 0208, second - revised 0212. - // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) +module.exports = build - // Byte encodings are: - // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte - // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. - // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. - // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. - // 0x00-0x7F - lower part of 0201 - // 0x8E, 0xA1-0xDF - upper part of 0201 - // (0xA1-0xFE)x2 - 0208 plane (94x94). - // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). - // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. - // Used as-is in ISO2022 family. - // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, - // 0201-1976 Roman, 0208-1978, 0208-1983. - // * ISO2022-JP-1: Adds esc seq for 0212-1990. - // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. - // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. - // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. - // - // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. - // - // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html - 'shiftjis': { - type: '_dbcs', - table: function() { return __nccwpck_require__(64108) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - encodeSkipVals: [{from: 0xED40, to: 0xF940}], - }, - 'csshiftjis': 'shiftjis', - 'mskanji': 'shiftjis', - 'sjis': 'shiftjis', - 'windows31j': 'shiftjis', - 'ms31j': 'shiftjis', - 'xsjis': 'shiftjis', - 'windows932': 'shiftjis', - 'ms932': 'shiftjis', - '932': 'shiftjis', - 'cp932': 'shiftjis', +/***/ }), - 'eucjp': { - type: '_dbcs', - table: function() { return __nccwpck_require__(72417) }, - encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, - }, +/***/ 30810: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // TODO: KDDI extension to Shift_JIS - // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. - // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. +"use strict"; +/*! + * finalhandler + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ - // == Chinese/GBK ========================================================== - // http://en.wikipedia.org/wiki/GBK - // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder - // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 - 'gb2312': 'cp936', - 'gb231280': 'cp936', - 'gb23121980': 'cp936', - 'csgb2312': 'cp936', - 'csiso58gb231280': 'cp936', - 'euccn': 'cp936', +/** + * Module dependencies. + * @private + */ - // Microsoft's CP936 is a subset and approximation of GBK. - 'windows936': 'cp936', - 'ms936': 'cp936', - '936': 'cp936', - 'cp936': { - type: '_dbcs', - table: function() { return __nccwpck_require__(97803) }, - }, +var debug = __nccwpck_require__(65612)('finalhandler') +var encodeUrl = __nccwpck_require__(16592) +var escapeHtml = __nccwpck_require__(94070) +var onFinished = __nccwpck_require__(92098) +var parseUrl = __nccwpck_require__(89808) +var statuses = __nccwpck_require__(57415) +var unpipe = __nccwpck_require__(3124) - // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. - 'gbk': { - type: '_dbcs', - table: function() { return __nccwpck_require__(97803).concat(__nccwpck_require__(37419)) }, - }, - 'xgbk': 'gbk', - 'isoir58': 'gbk', +/** + * Module variables. + * @private + */ - // GB18030 is an algorithmic extension of GBK. - // Main source: https://www.w3.org/TR/encoding/#gbk-encoder - // http://icu-project.org/docs/papers/gb18030.html - // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml - // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 - 'gb18030': { - type: '_dbcs', - table: function() { return __nccwpck_require__(97803).concat(__nccwpck_require__(37419)) }, - gb18030: function() { return __nccwpck_require__(86351) }, - encodeSkipVals: [0x80], - encodeAdd: {'€': 0xA2E3}, - }, +var DOUBLE_SPACE_REGEXP = /\x20{2}/g +var NEWLINE_REGEXP = /\n/g - 'chinese': 'gb18030', +/* istanbul ignore next */ +var defer = typeof setImmediate === 'function' + ? setImmediate + : function (fn) { process.nextTick(fn.bind.apply(fn, arguments)) } +var isFinished = onFinished.isFinished +/** + * Create a minimal HTML document. + * + * @param {string} message + * @private + */ - // == Korean =============================================================== - // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. - 'windows949': 'cp949', - 'ms949': 'cp949', - '949': 'cp949', - 'cp949': { - type: '_dbcs', - table: function() { return __nccwpck_require__(87013) }, - }, +function createHtmlDocument (message) { + var body = escapeHtml(message) + .replace(NEWLINE_REGEXP, '
') + .replace(DOUBLE_SPACE_REGEXP, '  ') - 'cseuckr': 'cp949', - 'csksc56011987': 'cp949', - 'euckr': 'cp949', - 'isoir149': 'cp949', - 'korean': 'cp949', - 'ksc56011987': 'cp949', - 'ksc56011989': 'cp949', - 'ksc5601': 'cp949', + return '\n' + + '\n' + + '\n' + + '\n' + + 'Error\n' + + '\n' + + '\n' + + '
' + body + '
\n' + + '\n' + + '\n' +} +/** + * Module exports. + * @public + */ - // == Big5/Taiwan/Hong Kong ================================================ - // There are lots of tables for Big5 and cp950. Please see the following links for history: - // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html - // Variations, in roughly number of defined chars: - // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT - // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ - // * Big5-2003 (Taiwan standard) almost superset of cp950. - // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. - // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. - // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. - // Plus, it has 4 combining sequences. - // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 - // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. - // Implementations are not consistent within browsers; sometimes labeled as just big5. - // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. - // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 - // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. - // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt - // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt - // - // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder - // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. +module.exports = finalhandler - 'windows950': 'cp950', - 'ms950': 'cp950', - '950': 'cp950', - 'cp950': { - type: '_dbcs', - table: function() { return __nccwpck_require__(33104) }, - }, +/** + * Create a function to handle the final response. + * + * @param {Request} req + * @param {Response} res + * @param {Object} [options] + * @return {Function} + * @public + */ - // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. - 'big5': 'big5hkscs', - 'big5hkscs': { - type: '_dbcs', - table: function() { return __nccwpck_require__(33104).concat(__nccwpck_require__(43612)) }, - encodeSkipVals: [0xa2cc], - }, +function finalhandler (req, res, options) { + var opts = options || {} - 'cnbig5': 'big5hkscs', - 'csbig5': 'big5hkscs', - 'xxbig5': 'big5hkscs', -}; + // get environment + var env = opts.env || process.env.NODE_ENV || 'development' + + // get error callback + var onerror = opts.onerror + return function (err) { + var headers + var msg + var status -/***/ }), + // ignore 404 on in-flight response + if (!err && headersSent(res)) { + debug('cannot 404 after headers sent') + return + } + + // unhandled error + if (err) { + // respect status code from error + status = getErrorStatusCode(err) + + if (status === undefined) { + // fallback to status code on response + status = getResponseStatusCode(res) + } else { + // respect headers from error + headers = getErrorHeaders(err) + } -/***/ 82733: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // get error message + msg = getErrorMessage(err, status, env) + } else { + // not found + status = 404 + msg = 'Cannot ' + req.method + ' ' + encodeUrl(getResourceName(req)) + } -"use strict"; + debug('default %s', status) + // schedule onerror callback + if (err && onerror) { + defer(onerror, err, req, res) + } -// Update this array if you add/rename/remove files in this directory. -// We support Browserify by skipping automatic module discovery and requiring modules directly. -var modules = [ - __nccwpck_require__(12376), - __nccwpck_require__(11155), - __nccwpck_require__(51644), - __nccwpck_require__(26657), - __nccwpck_require__(41080), - __nccwpck_require__(21012), - __nccwpck_require__(39695), - __nccwpck_require__(91386), -]; + // cannot actually respond + if (headersSent(res)) { + debug('cannot %d after headers sent', status) + req.socket.destroy() + return + } -// Put all encoding/alias/codec definitions to single object and export it. -for (var i = 0; i < modules.length; i++) { - var module = modules[i]; - for (var enc in module) - if (Object.prototype.hasOwnProperty.call(module, enc)) - exports[enc] = module[enc]; + // send response + send(req, res, status, headers, msg) + } } +/** + * Get headers from Error object. + * + * @param {Error} err + * @return {object} + * @private + */ -/***/ }), +function getErrorHeaders (err) { + if (!err.headers || typeof err.headers !== 'object') { + return undefined + } -/***/ 12376: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + var headers = Object.create(null) + var keys = Object.keys(err.headers) -"use strict"; + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + headers[key] = err.headers[key] + } -var Buffer = __nccwpck_require__(15118).Buffer; + return headers +} -// Export Node.js internal encodings. +/** + * Get message from Error object, fallback to status message. + * + * @param {Error} err + * @param {number} status + * @param {string} env + * @return {string} + * @private + */ -module.exports = { - // Encodings - utf8: { type: "_internal", bomAware: true}, - cesu8: { type: "_internal", bomAware: true}, - unicode11utf8: "utf8", +function getErrorMessage (err, status, env) { + var msg - ucs2: { type: "_internal", bomAware: true}, - utf16le: "ucs2", + if (env !== 'production') { + // use err.stack, which typically includes err.message + msg = err.stack - binary: { type: "_internal" }, - base64: { type: "_internal" }, - hex: { type: "_internal" }, + // fallback to err.toString() when possible + if (!msg && typeof err.toString === 'function') { + msg = err.toString() + } + } - // Codec. - _internal: InternalCodec, -}; + return msg || statuses[status] +} -//------------------------------------------------------------------------------ +/** + * Get status code from Error object. + * + * @param {Error} err + * @return {number} + * @private + */ -function InternalCodec(codecOptions, iconv) { - this.enc = codecOptions.encodingName; - this.bomAware = codecOptions.bomAware; +function getErrorStatusCode (err) { + // check err.status + if (typeof err.status === 'number' && err.status >= 400 && err.status < 600) { + return err.status + } - if (this.enc === "base64") - this.encoder = InternalEncoderBase64; - else if (this.enc === "cesu8") { - this.enc = "utf8"; // Use utf8 for decoding. - this.encoder = InternalEncoderCesu8; + // check err.statusCode + if (typeof err.statusCode === 'number' && err.statusCode >= 400 && err.statusCode < 600) { + return err.statusCode + } - // Add decoder for versions of Node not supporting CESU-8 - if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { - this.decoder = InternalDecoderCesu8; - this.defaultCharUnicode = iconv.defaultCharUnicode; - } - } + return undefined } -InternalCodec.prototype.encoder = InternalEncoder; -InternalCodec.prototype.decoder = InternalDecoder; +/** + * Get resource name for the request. + * + * This is typically just the original pathname of the request + * but will fallback to "resource" is that cannot be determined. + * + * @param {IncomingMessage} req + * @return {string} + * @private + */ -//------------------------------------------------------------------------------ +function getResourceName (req) { + try { + return parseUrl.original(req).pathname + } catch (e) { + return 'resource' + } +} -// We use node.js internal decoder. Its signature is the same as ours. -var StringDecoder = __nccwpck_require__(24304).StringDecoder; +/** + * Get status code from response. + * + * @param {OutgoingMessage} res + * @return {number} + * @private + */ -if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. - StringDecoder.prototype.end = function() {}; +function getResponseStatusCode (res) { + var status = res.statusCode + // default status code to 500 if outside valid range + if (typeof status !== 'number' || status < 400 || status > 599) { + status = 500 + } -function InternalDecoder(options, codec) { - StringDecoder.call(this, codec.enc); + return status } -InternalDecoder.prototype = StringDecoder.prototype; +/** + * Determine if the response headers have been sent. + * + * @param {object} res + * @returns {boolean} + * @private + */ +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +} -//------------------------------------------------------------------------------ -// Encoder is mostly trivial +/** + * Send response. + * + * @param {IncomingMessage} req + * @param {OutgoingMessage} res + * @param {number} status + * @param {object} headers + * @param {string} message + * @private + */ -function InternalEncoder(options, codec) { - this.enc = codec.enc; -} +function send (req, res, status, headers, message) { + function write () { + // response body + var body = createHtmlDocument(message) -InternalEncoder.prototype.write = function(str) { - return Buffer.from(str, this.enc); -} + // response status + res.statusCode = status + res.statusMessage = statuses[status] -InternalEncoder.prototype.end = function() { -} + // response headers + setHeaders(res, headers) + // security headers + res.setHeader('Content-Security-Policy', "default-src 'none'") + res.setHeader('X-Content-Type-Options', 'nosniff') -//------------------------------------------------------------------------------ -// Except base64 encoder, which must keep its state. + // standard headers + res.setHeader('Content-Type', 'text/html; charset=utf-8') + res.setHeader('Content-Length', Buffer.byteLength(body, 'utf8')) -function InternalEncoderBase64(options, codec) { - this.prevStr = ''; -} + if (req.method === 'HEAD') { + res.end() + return + } -InternalEncoderBase64.prototype.write = function(str) { - str = this.prevStr + str; - var completeQuads = str.length - (str.length % 4); - this.prevStr = str.slice(completeQuads); - str = str.slice(0, completeQuads); + res.end(body, 'utf8') + } - return Buffer.from(str, "base64"); -} + if (isFinished(req)) { + write() + return + } -InternalEncoderBase64.prototype.end = function() { - return Buffer.from(this.prevStr, "base64"); + // unpipe everything from the request + unpipe(req) + + // flush the request + onFinished(req, write) + req.resume() } +/** + * Set response headers from an object. + * + * @param {OutgoingMessage} res + * @param {object} headers + * @private + */ -//------------------------------------------------------------------------------ -// CESU-8 encoder is also special. +function setHeaders (res, headers) { + if (!headers) { + return + } -function InternalEncoderCesu8(options, codec) { + var keys = Object.keys(headers) + for (var i = 0; i < keys.length; i++) { + var key = keys[i] + res.setHeader(key, headers[key]) + } } -InternalEncoderCesu8.prototype.write = function(str) { - var buf = Buffer.alloc(str.length * 3), bufIdx = 0; - for (var i = 0; i < str.length; i++) { - var charCode = str.charCodeAt(i); - // Naive implementation, but it works because CESU-8 is especially easy - // to convert from UTF-16 (which all JS strings are encoded in). - if (charCode < 0x80) - buf[bufIdx++] = charCode; - else if (charCode < 0x800) { - buf[bufIdx++] = 0xC0 + (charCode >>> 6); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } - else { // charCode will always be < 0x10000 in javascript. - buf[bufIdx++] = 0xE0 + (charCode >>> 12); - buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); - buf[bufIdx++] = 0x80 + (charCode & 0x3f); - } - } - return buf.slice(0, bufIdx); -} -InternalEncoderCesu8.prototype.end = function() { -} +/***/ }), -//------------------------------------------------------------------------------ -// CESU-8 decoder is not implemented in Node v4.0+ +/***/ 56401: +/***/ ((module, exports, __nccwpck_require__) => { -function InternalDecoderCesu8(options, codec) { - this.acc = 0; - this.contBytes = 0; - this.accBytes = 0; - this.defaultCharUnicode = codec.defaultCharUnicode; -} +/** + * This is the web browser implementation of `debug()`. + * + * Expose `debug()` as the module. + */ -InternalDecoderCesu8.prototype.write = function(buf) { - var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, - res = ''; - for (var i = 0; i < buf.length; i++) { - var curByte = buf[i]; - if ((curByte & 0xC0) !== 0x80) { // Leading byte - if (contBytes > 0) { // Previous code is invalid - res += this.defaultCharUnicode; - contBytes = 0; - } +exports = module.exports = __nccwpck_require__(60545); +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; +exports.storage = 'undefined' != typeof chrome + && 'undefined' != typeof chrome.storage + ? chrome.storage.local + : localstorage(); - if (curByte < 0x80) { // Single-byte code - res += String.fromCharCode(curByte); - } else if (curByte < 0xE0) { // Two-byte code - acc = curByte & 0x1F; - contBytes = 1; accBytes = 1; - } else if (curByte < 0xF0) { // Three-byte code - acc = curByte & 0x0F; - contBytes = 2; accBytes = 1; - } else { // Four or more are not supported for CESU-8. - res += this.defaultCharUnicode; - } - } else { // Continuation byte - if (contBytes > 0) { // We're waiting for it. - acc = (acc << 6) | (curByte & 0x3f); - contBytes--; accBytes++; - if (contBytes === 0) { - // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) - if (accBytes === 2 && acc < 0x80 && acc > 0) - res += this.defaultCharUnicode; - else if (accBytes === 3 && acc < 0x800) - res += this.defaultCharUnicode; - else - // Actually add character. - res += String.fromCharCode(acc); - } - } else { // Unexpected continuation byte - res += this.defaultCharUnicode; - } - } - } - this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; - return res; -} +/** + * Colors. + */ -InternalDecoderCesu8.prototype.end = function() { - var res = 0; - if (this.contBytes > 0) - res += this.defaultCharUnicode; - return res; +exports.colors = [ + 'lightseagreen', + 'forestgreen', + 'goldenrod', + 'dodgerblue', + 'darkorchid', + 'crimson' +]; + +/** + * Currently only WebKit-based Web Inspectors, Firefox >= v31, + * and the Firebug extension (any Firefox version) are known + * to support "%c" CSS customizations. + * + * TODO: add a `localStorage` variable to explicitly enable/disable colors + */ + +function useColors() { + // NB: In an Electron preload script, document will be defined but not fully + // initialized. Since we know we're in Chrome, we'll just detect this case + // explicitly + if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { + return true; + } + + // is webkit? http://stackoverflow.com/a/16459606/376773 + // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 + return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || + // is firebug? http://stackoverflow.com/a/398120/376773 + (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || + // is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || + // double check webkit in userAgent just in case we are in a worker + (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); } +/** + * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. + */ -/***/ }), +exports.formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (err) { + return '[UnexpectedJSONParseError]: ' + err.message; + } +}; -/***/ 26657: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +/** + * Colorize log arguments if enabled. + * + * @api public + */ -var Buffer = __nccwpck_require__(15118).Buffer; +function formatArgs(args) { + var useColors = this.useColors; -// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that -// correspond to encoded bytes (if 128 - then lower half is ASCII). + args[0] = (useColors ? '%c' : '') + + this.namespace + + (useColors ? ' %c' : ' ') + + args[0] + + (useColors ? '%c ' : ' ') + + '+' + exports.humanize(this.diff); -exports._sbcs = SBCSCodec; -function SBCSCodec(codecOptions, iconv) { - if (!codecOptions) - throw new Error("SBCS codec is called without the data.") - - // Prepare char buffer for decoding. - if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) - throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); - - if (codecOptions.chars.length === 128) { - var asciiString = ""; - for (var i = 0; i < 128; i++) - asciiString += String.fromCharCode(i); - codecOptions.chars = asciiString + codecOptions.chars; - } + if (!useColors) return; - this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); - - // Encoding buffer. - var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); + var c = 'color: ' + this.color; + args.splice(1, 0, c, 'color: inherit') - for (var i = 0; i < codecOptions.chars.length; i++) - encodeBuf[codecOptions.chars.charCodeAt(i)] = i; + // the final "%c" is somewhat tricky, because there could be other + // arguments passed either before or after the %c, so we need to + // figure out the correct index to insert the CSS into + var index = 0; + var lastC = 0; + args[0].replace(/%[a-zA-Z%]/g, function(match) { + if ('%%' === match) return; + index++; + if ('%c' === match) { + // we only are interested in the *last* %c + // (the user may have provided their own) + lastC = index; + } + }); - this.encodeBuf = encodeBuf; + args.splice(lastC, 0, c); } -SBCSCodec.prototype.encoder = SBCSEncoder; -SBCSCodec.prototype.decoder = SBCSDecoder; - +/** + * Invokes `console.log()` when available. + * No-op when `console.log` is not a "function". + * + * @api public + */ -function SBCSEncoder(options, codec) { - this.encodeBuf = codec.encodeBuf; +function log() { + // this hackery is required for IE8/9, where + // the `console.log` function doesn't have 'apply' + return 'object' === typeof console + && console.log + && Function.prototype.apply.call(console.log, console, arguments); } -SBCSEncoder.prototype.write = function(str) { - var buf = Buffer.alloc(str.length); - for (var i = 0; i < str.length; i++) - buf[i] = this.encodeBuf[str.charCodeAt(i)]; - - return buf; +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + try { + if (null == namespaces) { + exports.storage.removeItem('debug'); + } else { + exports.storage.debug = namespaces; + } + } catch(e) {} } -SBCSEncoder.prototype.end = function() { -} +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ +function load() { + var r; + try { + r = exports.storage.debug; + } catch(e) {} -function SBCSDecoder(options, codec) { - this.decodeBuf = codec.decodeBuf; -} + // If debug isn't set in LS, and we're in Electron, try to load $DEBUG + if (!r && typeof process !== 'undefined' && 'env' in process) { + r = process.env.DEBUG; + } -SBCSDecoder.prototype.write = function(buf) { - // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. - var decodeBuf = this.decodeBuf; - var newBuf = Buffer.alloc(buf.length*2); - var idx1 = 0, idx2 = 0; - for (var i = 0; i < buf.length; i++) { - idx1 = buf[i]*2; idx2 = i*2; - newBuf[idx2] = decodeBuf[idx1]; - newBuf[idx2+1] = decodeBuf[idx1+1]; - } - return newBuf.toString('ucs2'); + return r; } -SBCSDecoder.prototype.end = function() { +/** + * Enable namespaces listed in `localStorage.debug` initially. + */ + +exports.enable(load()); + +/** + * Localstorage attempts to return the localstorage. + * + * This is necessary because safari throws + * when a user disables cookies/localstorage + * and you attempt to access it. + * + * @return {LocalStorage} + * @api private + */ + +function localstorage() { + try { + return window.localStorage; + } catch (e) {} } /***/ }), -/***/ 21012: -/***/ ((module) => { +/***/ 60545: +/***/ ((module, exports, __nccwpck_require__) => { -"use strict"; +/** + * This is the common logic for both the Node.js and web browser + * implementations of `debug()`. + * + * Expose `debug()` as the module. + */ -// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. -module.exports = { - "437": "cp437", - "737": "cp737", - "775": "cp775", - "850": "cp850", - "852": "cp852", - "855": "cp855", - "856": "cp856", - "857": "cp857", - "858": "cp858", - "860": "cp860", - "861": "cp861", - "862": "cp862", - "863": "cp863", - "864": "cp864", - "865": "cp865", - "866": "cp866", - "869": "cp869", - "874": "windows874", - "922": "cp922", - "1046": "cp1046", - "1124": "cp1124", - "1125": "cp1125", - "1129": "cp1129", - "1133": "cp1133", - "1161": "cp1161", - "1162": "cp1162", - "1163": "cp1163", - "1250": "windows1250", - "1251": "windows1251", - "1252": "windows1252", - "1253": "windows1253", - "1254": "windows1254", - "1255": "windows1255", - "1256": "windows1256", - "1257": "windows1257", - "1258": "windows1258", - "28591": "iso88591", - "28592": "iso88592", - "28593": "iso88593", - "28594": "iso88594", - "28595": "iso88595", - "28596": "iso88596", - "28597": "iso88597", - "28598": "iso88598", - "28599": "iso88599", - "28600": "iso885910", - "28601": "iso885911", - "28603": "iso885913", - "28604": "iso885914", - "28605": "iso885915", - "28606": "iso885916", - "windows874": { - "type": "_sbcs", - "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "win874": "windows874", - "cp874": "windows874", - "windows1250": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "win1250": "windows1250", - "cp1250": "windows1250", - "windows1251": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "win1251": "windows1251", - "cp1251": "windows1251", - "windows1252": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "win1252": "windows1252", - "cp1252": "windows1252", - "windows1253": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "win1253": "windows1253", - "cp1253": "windows1253", - "windows1254": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "win1254": "windows1254", - "cp1254": "windows1254", - "windows1255": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "win1255": "windows1255", - "cp1255": "windows1255", - "windows1256": { - "type": "_sbcs", - "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" - }, - "win1256": "windows1256", - "cp1256": "windows1256", - "windows1257": { - "type": "_sbcs", - "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" - }, - "win1257": "windows1257", - "cp1257": "windows1257", - "windows1258": { - "type": "_sbcs", - "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "win1258": "windows1258", - "cp1258": "windows1258", - "iso88591": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28591": "iso88591", - "iso88592": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" - }, - "cp28592": "iso88592", - "iso88593": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" - }, - "cp28593": "iso88593", - "iso88594": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" - }, - "cp28594": "iso88594", - "iso88595": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" - }, - "cp28595": "iso88595", - "iso88596": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" - }, - "cp28596": "iso88596", - "iso88597": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" - }, - "cp28597": "iso88597", - "iso88598": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" - }, - "cp28598": "iso88598", - "iso88599": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" - }, - "cp28599": "iso88599", - "iso885910": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" - }, - "cp28600": "iso885910", - "iso885911": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "cp28601": "iso885911", - "iso885913": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" - }, - "cp28603": "iso885913", - "iso885914": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" - }, - "cp28604": "iso885914", - "iso885915": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "cp28605": "iso885915", - "iso885916": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" - }, - "cp28606": "iso885916", - "cp437": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm437": "cp437", - "csibm437": "cp437", - "cp737": { - "type": "_sbcs", - "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " - }, - "ibm737": "cp737", - "csibm737": "cp737", - "cp775": { - "type": "_sbcs", - "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " - }, - "ibm775": "cp775", - "csibm775": "cp775", - "cp850": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm850": "cp850", - "csibm850": "cp850", - "cp852": { - "type": "_sbcs", - "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " - }, - "ibm852": "cp852", - "csibm852": "cp852", - "cp855": { - "type": "_sbcs", - "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " - }, - "ibm855": "cp855", - "csibm855": "cp855", - "cp856": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm856": "cp856", - "csibm856": "cp856", - "cp857": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " - }, - "ibm857": "cp857", - "csibm857": "cp857", - "cp858": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " - }, - "ibm858": "cp858", - "csibm858": "cp858", - "cp860": { - "type": "_sbcs", - "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm860": "cp860", - "csibm860": "cp860", - "cp861": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm861": "cp861", - "csibm861": "cp861", - "cp862": { - "type": "_sbcs", - "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm862": "cp862", - "csibm862": "cp862", - "cp863": { - "type": "_sbcs", - "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm863": "cp863", - "csibm863": "cp863", - "cp864": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" - }, - "ibm864": "cp864", - "csibm864": "cp864", - "cp865": { - "type": "_sbcs", - "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, - "ibm865": "cp865", - "csibm865": "cp865", - "cp866": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " - }, - "ibm866": "cp866", - "csibm866": "cp866", - "cp869": { - "type": "_sbcs", - "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " - }, - "ibm869": "cp869", - "csibm869": "cp869", - "cp922": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" - }, - "ibm922": "cp922", - "csibm922": "cp922", - "cp1046": { - "type": "_sbcs", - "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" - }, - "ibm1046": "cp1046", - "csibm1046": "cp1046", - "cp1124": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" - }, - "ibm1124": "cp1124", - "csibm1124": "cp1124", - "cp1125": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " - }, - "ibm1125": "cp1125", - "csibm1125": "cp1125", - "cp1129": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1129": "cp1129", - "csibm1129": "cp1129", - "cp1133": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" - }, - "ibm1133": "cp1133", - "csibm1133": "cp1133", - "cp1161": { - "type": "_sbcs", - "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " - }, - "ibm1161": "cp1161", - "csibm1161": "cp1161", - "cp1162": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" - }, - "ibm1162": "cp1162", - "csibm1162": "cp1162", - "cp1163": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" - }, - "ibm1163": "cp1163", - "csibm1163": "cp1163", - "maccroatian": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" - }, - "maccyrillic": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "macgreek": { - "type": "_sbcs", - "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" - }, - "maciceland": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macroman": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macromania": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macthai": { - "type": "_sbcs", - "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" - }, - "macturkish": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" - }, - "macukraine": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" - }, - "koi8r": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8u": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8ru": { - "type": "_sbcs", - "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "koi8t": { - "type": "_sbcs", - "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" - }, - "armscii8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" - }, - "rk1048": { - "type": "_sbcs", - "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "tcvn": { - "type": "_sbcs", - "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" - }, - "georgianacademy": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "georgianps": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" - }, - "pt154": { - "type": "_sbcs", - "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" - }, - "viscii": { - "type": "_sbcs", - "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" - }, - "iso646cn": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "iso646jp": { - "type": "_sbcs", - "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" - }, - "hproman8": { - "type": "_sbcs", - "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" - }, - "macintosh": { - "type": "_sbcs", - "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" - }, - "ascii": { - "type": "_sbcs", - "chars": "��������������������������������������������������������������������������������������������������������������������������������" - }, - "tis620": { - "type": "_sbcs", - "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" +exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; +exports.coerce = coerce; +exports.disable = disable; +exports.enable = enable; +exports.enabled = enabled; +exports.humanize = __nccwpck_require__(80761); + +/** + * The currently active debug mode names, and names to skip. + */ + +exports.names = []; +exports.skips = []; + +/** + * Map of special "%n" handling functions, for the debug "format" argument. + * + * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". + */ + +exports.formatters = {}; + +/** + * Previous log timestamp. + */ + +var prevTime; + +/** + * Select a color. + * @param {String} namespace + * @return {Number} + * @api private + */ + +function selectColor(namespace) { + var hash = 0, i; + + for (i in namespace) { + hash = ((hash << 5) - hash) + namespace.charCodeAt(i); + hash |= 0; // Convert to 32bit integer + } + + return exports.colors[Math.abs(hash) % exports.colors.length]; +} + +/** + * Create a debugger with the given `namespace`. + * + * @param {String} namespace + * @return {Function} + * @api public + */ + +function createDebug(namespace) { + + function debug() { + // disabled? + if (!debug.enabled) return; + + var self = debug; + + // set `diff` timestamp + var curr = +new Date(); + var ms = curr - (prevTime || curr); + self.diff = ms; + self.prev = prevTime; + self.curr = curr; + prevTime = curr; + + // turn the `arguments` into a proper Array + var args = new Array(arguments.length); + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i]; + } + + args[0] = exports.coerce(args[0]); + + if ('string' !== typeof args[0]) { + // anything else let's inspect with %O + args.unshift('%O'); + } + + // apply any `formatters` transformations + var index = 0; + args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { + // if we encounter an escaped % then don't increase the array index + if (match === '%%') return match; + index++; + var formatter = exports.formatters[format]; + if ('function' === typeof formatter) { + var val = args[index]; + match = formatter.call(self, val); + + // now we need to remove `args[index]` since it's inlined in the `format` + args.splice(index, 1); + index--; + } + return match; + }); + + // apply env-specific formatting (colors, etc.) + exports.formatArgs.call(self, args); + + var logFn = debug.log || exports.log || console.log.bind(console); + logFn.apply(self, args); + } + + debug.namespace = namespace; + debug.enabled = exports.enabled(namespace); + debug.useColors = exports.useColors(); + debug.color = selectColor(namespace); + + // env-specific initialization logic for debug instances + if ('function' === typeof exports.init) { + exports.init(debug); + } + + return debug; +} + +/** + * Enables a debug mode by namespaces. This can include modes + * separated by a colon and wildcards. + * + * @param {String} namespaces + * @api public + */ + +function enable(namespaces) { + exports.save(namespaces); + + exports.names = []; + exports.skips = []; + + var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); + var len = split.length; + + for (var i = 0; i < len; i++) { + if (!split[i]) continue; // ignore empty strings + namespaces = split[i].replace(/\*/g, '.*?'); + if (namespaces[0] === '-') { + exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); + } else { + exports.names.push(new RegExp('^' + namespaces + '$')); + } + } +} + +/** + * Disable debug output. + * + * @api public + */ + +function disable() { + exports.enable(''); +} + +/** + * Returns true if the given mode name is enabled, false otherwise. + * + * @param {String} name + * @return {Boolean} + * @api public + */ + +function enabled(name) { + var i, len; + for (i = 0, len = exports.skips.length; i < len; i++) { + if (exports.skips[i].test(name)) { + return false; + } + } + for (i = 0, len = exports.names.length; i < len; i++) { + if (exports.names[i].test(name)) { + return true; + } } + return false; +} + +/** + * Coerce `val`. + * + * @param {Mixed} val + * @return {Mixed} + * @api private + */ + +function coerce(val) { + if (val instanceof Error) return val.stack || val.message; + return val; } + /***/ }), -/***/ 41080: -/***/ ((module) => { +/***/ 65612: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +/** + * Detect Electron renderer process, which is node, but we should + * treat as a browser. + */ +if (typeof process !== 'undefined' && process.type === 'renderer') { + module.exports = __nccwpck_require__(56401); +} else { + module.exports = __nccwpck_require__(4706); +} -// Manually added data to be used by sbcs codec in addition to generated one. -module.exports = { - // Not supported by iconv, not sure why. - "10029": "maccenteuro", - "maccenteuro": { - "type": "_sbcs", - "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" - }, +/***/ }), - "808": "cp808", - "ibm808": "cp808", - "cp808": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " - }, +/***/ 4706: +/***/ ((module, exports, __nccwpck_require__) => { - "mik": { - "type": "_sbcs", - "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " - }, +/** + * Module dependencies. + */ - // Aliases of generated encodings. - "ascii8bit": "ascii", - "usascii": "ascii", - "ansix34": "ascii", - "ansix341968": "ascii", - "ansix341986": "ascii", - "csascii": "ascii", - "cp367": "ascii", - "ibm367": "ascii", - "isoir6": "ascii", - "iso646us": "ascii", - "iso646irv": "ascii", - "us": "ascii", +var tty = __nccwpck_require__(33867); +var util = __nccwpck_require__(31669); - "latin1": "iso88591", - "latin2": "iso88592", - "latin3": "iso88593", - "latin4": "iso88594", - "latin5": "iso88599", - "latin6": "iso885910", - "latin7": "iso885913", - "latin8": "iso885914", - "latin9": "iso885915", - "latin10": "iso885916", +/** + * This is the Node.js implementation of `debug()`. + * + * Expose `debug()` as the module. + */ - "csisolatin1": "iso88591", - "csisolatin2": "iso88592", - "csisolatin3": "iso88593", - "csisolatin4": "iso88594", - "csisolatincyrillic": "iso88595", - "csisolatinarabic": "iso88596", - "csisolatingreek" : "iso88597", - "csisolatinhebrew": "iso88598", - "csisolatin5": "iso88599", - "csisolatin6": "iso885910", +exports = module.exports = __nccwpck_require__(60545); +exports.init = init; +exports.log = log; +exports.formatArgs = formatArgs; +exports.save = save; +exports.load = load; +exports.useColors = useColors; - "l1": "iso88591", - "l2": "iso88592", - "l3": "iso88593", - "l4": "iso88594", - "l5": "iso88599", - "l6": "iso885910", - "l7": "iso885913", - "l8": "iso885914", - "l9": "iso885915", - "l10": "iso885916", +/** + * Colors. + */ - "isoir14": "iso646jp", - "isoir57": "iso646cn", - "isoir100": "iso88591", - "isoir101": "iso88592", - "isoir109": "iso88593", - "isoir110": "iso88594", - "isoir144": "iso88595", - "isoir127": "iso88596", - "isoir126": "iso88597", - "isoir138": "iso88598", - "isoir148": "iso88599", - "isoir157": "iso885910", - "isoir166": "tis620", - "isoir179": "iso885913", - "isoir199": "iso885914", - "isoir203": "iso885915", - "isoir226": "iso885916", +exports.colors = [6, 2, 3, 4, 5, 1]; - "cp819": "iso88591", - "ibm819": "iso88591", +/** + * Build up the default `inspectOpts` object from the environment variables. + * + * $ DEBUG_COLORS=no DEBUG_DEPTH=10 DEBUG_SHOW_HIDDEN=enabled node script.js + */ - "cyrillic": "iso88595", +exports.inspectOpts = Object.keys(process.env).filter(function (key) { + return /^debug_/i.test(key); +}).reduce(function (obj, key) { + // camel-case + var prop = key + .substring(6) + .toLowerCase() + .replace(/_([a-z])/g, function (_, k) { return k.toUpperCase() }); + + // coerce string value into JS value + var val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) val = true; + else if (/^(no|off|false|disabled)$/i.test(val)) val = false; + else if (val === 'null') val = null; + else val = Number(val); + + obj[prop] = val; + return obj; +}, {}); + +/** + * The file descriptor to write the `debug()` calls to. + * Set the `DEBUG_FD` env variable to override with another value. i.e.: + * + * $ DEBUG_FD=3 node script.js 3>debug.log + */ + +var fd = parseInt(process.env.DEBUG_FD, 10) || 2; + +if (1 !== fd && 2 !== fd) { + util.deprecate(function(){}, 'except for stderr(2) and stdout(1), any other usage of DEBUG_FD is deprecated. Override debug.log if you want to use a different log function (https://git.io/debug_fd)')() +} + +var stream = 1 === fd ? process.stdout : + 2 === fd ? process.stderr : + createWritableStdioStream(fd); + +/** + * Is stdout a TTY? Colored output is enabled when `true`. + */ + +function useColors() { + return 'colors' in exports.inspectOpts + ? Boolean(exports.inspectOpts.colors) + : tty.isatty(fd); +} + +/** + * Map %o to `util.inspect()`, all on a single line. + */ + +exports.formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts) + .split('\n').map(function(str) { + return str.trim() + }).join(' '); +}; + +/** + * Map %o to `util.inspect()`, allowing multiple lines if needed. + */ + +exports.formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util.inspect(v, this.inspectOpts); +}; + +/** + * Adds ANSI color escape codes if enabled. + * + * @api public + */ + +function formatArgs(args) { + var name = this.namespace; + var useColors = this.useColors; + + if (useColors) { + var c = this.color; + var prefix = ' \u001b[3' + c + ';1m' + name + ' ' + '\u001b[0m'; + + args[0] = prefix + args[0].split('\n').join('\n' + prefix); + args.push('\u001b[3' + c + 'm+' + exports.humanize(this.diff) + '\u001b[0m'); + } else { + args[0] = new Date().toUTCString() + + ' ' + name + ' ' + args[0]; + } +} + +/** + * Invokes `util.format()` with the specified arguments and writes to `stream`. + */ + +function log() { + return stream.write(util.format.apply(util, arguments) + '\n'); +} + +/** + * Save `namespaces`. + * + * @param {String} namespaces + * @api private + */ + +function save(namespaces) { + if (null == namespaces) { + // If you set a process.env field to null or undefined, it gets cast to the + // string 'null' or 'undefined'. Just delete instead. + delete process.env.DEBUG; + } else { + process.env.DEBUG = namespaces; + } +} + +/** + * Load `namespaces`. + * + * @return {String} returns the previously persisted debug modes + * @api private + */ + +function load() { + return process.env.DEBUG; +} + +/** + * Copied from `node/src/node.js`. + * + * XXX: It's lame that node doesn't expose this API out-of-the-box. It also + * relies on the undocumented `tty_wrap.guessHandleType()` which is also lame. + */ + +function createWritableStdioStream (fd) { + var stream; + var tty_wrap = process.binding('tty_wrap'); + + // Note stream._type is used for test-module-load-list.js + + switch (tty_wrap.guessHandleType(fd)) { + case 'TTY': + stream = new tty.WriteStream(fd); + stream._type = 'tty'; + + // Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + case 'FILE': + var fs = __nccwpck_require__(35747); + stream = new fs.SyncWriteStream(fd, { autoClose: false }); + stream._type = 'fs'; + break; + + case 'PIPE': + case 'TCP': + var net = __nccwpck_require__(11631); + stream = new net.Socket({ + fd: fd, + readable: false, + writable: true + }); + + // FIXME Should probably have an option in net.Socket to create a + // stream from an existing fd which is writable only. But for now + // we'll just add this hack and set the `readable` member to false. + // Test: ./node test/fixtures/echo.js < /etc/passwd + stream.readable = false; + stream.read = null; + stream._type = 'pipe'; + + // FIXME Hack to have stream not keep the event loop alive. + // See https://github.com/joyent/node/issues/1726 + if (stream._handle && stream._handle.unref) { + stream._handle.unref(); + } + break; + + default: + // Probably an error on in uv_guess_handle() + throw new Error('Implement me. Unknown stream file type!'); + } + + // For supporting legacy API we put the FD here. + stream.fd = fd; + + stream._isStdio = true; + + return stream; +} + +/** + * Init logic for `debug` instances. + * + * Create a new `inspectOpts` object in case `useColors` is set + * differently for a particular `debug` instance. + */ - "arabic": "iso88596", - "arabic8": "iso88596", - "ecma114": "iso88596", - "asmo708": "iso88596", +function init (debug) { + debug.inspectOpts = {}; - "greek" : "iso88597", - "greek8" : "iso88597", - "ecma118" : "iso88597", - "elot928" : "iso88597", + var keys = Object.keys(exports.inspectOpts); + for (var i = 0; i < keys.length; i++) { + debug.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } +} - "hebrew": "iso88598", - "hebrew8": "iso88598", +/** + * Enable namespaces listed in `process.env.DEBUG` initially. + */ - "turkish": "iso88599", - "turkish8": "iso88599", +exports.enable(load()); - "thai": "iso885911", - "thai8": "iso885911", - "celtic": "iso885914", - "celtic8": "iso885914", - "isoceltic": "iso885914", +/***/ }), - "tis6200": "tis620", - "tis62025291": "tis620", - "tis62025330": "tis620", +/***/ 80761: +/***/ ((module) => { - "10000": "macroman", - "10006": "macgreek", - "10007": "maccyrillic", - "10079": "maciceland", - "10081": "macturkish", +/** + * Helpers. + */ - "cspc8codepage437": "cp437", - "cspc775baltic": "cp775", - "cspc850multilingual": "cp850", - "cspcp852": "cp852", - "cspc862latinhebrew": "cp862", - "cpgr": "cp869", +var s = 1000; +var m = s * 60; +var h = m * 60; +var d = h * 24; +var y = d * 365.25; - "msee": "cp1250", - "mscyrl": "cp1251", - "msansi": "cp1252", - "msgreek": "cp1253", - "msturk": "cp1254", - "mshebr": "cp1255", - "msarab": "cp1256", - "winbaltrim": "cp1257", +/** + * Parse or format the given `val`. + * + * Options: + * + * - `long` verbose formatting [false] + * + * @param {String|Number} val + * @param {Object} [options] + * @throws {Error} throw an error if val is not a non-empty string or a number + * @return {String|Number} + * @api public + */ - "cp20866": "koi8r", - "20866": "koi8r", - "ibm878": "koi8r", - "cskoi8r": "koi8r", +module.exports = function(val, options) { + options = options || {}; + var type = typeof val; + if (type === 'string' && val.length > 0) { + return parse(val); + } else if (type === 'number' && isNaN(val) === false) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + 'val is not a non-empty string or a valid number. val=' + + JSON.stringify(val) + ); +}; - "cp21866": "koi8u", - "21866": "koi8u", - "ibm1168": "koi8u", +/** + * Parse the given `str` and return milliseconds. + * + * @param {String} str + * @return {Number} + * @api private + */ - "strk10482002": "rk1048", +function parse(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match = /^((?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|years?|yrs?|y)?$/i.exec( + str + ); + if (!match) { + return; + } + var n = parseFloat(match[1]); + var type = (match[2] || 'ms').toLowerCase(); + switch (type) { + case 'years': + case 'year': + case 'yrs': + case 'yr': + case 'y': + return n * y; + case 'days': + case 'day': + case 'd': + return n * d; + case 'hours': + case 'hour': + case 'hrs': + case 'hr': + case 'h': + return n * h; + case 'minutes': + case 'minute': + case 'mins': + case 'min': + case 'm': + return n * m; + case 'seconds': + case 'second': + case 'secs': + case 'sec': + case 's': + return n * s; + case 'milliseconds': + case 'millisecond': + case 'msecs': + case 'msec': + case 'ms': + return n; + default: + return undefined; + } +} - "tcvn5712": "tcvn", - "tcvn57121": "tcvn", +/** + * Short format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - "gb198880": "iso646cn", - "cn": "iso646cn", +function fmtShort(ms) { + if (ms >= d) { + return Math.round(ms / d) + 'd'; + } + if (ms >= h) { + return Math.round(ms / h) + 'h'; + } + if (ms >= m) { + return Math.round(ms / m) + 'm'; + } + if (ms >= s) { + return Math.round(ms / s) + 's'; + } + return ms + 'ms'; +} - "csiso14jisc6220ro": "iso646jp", - "jisc62201969ro": "iso646jp", - "jp": "iso646jp", +/** + * Long format for `ms`. + * + * @param {Number} ms + * @return {String} + * @api private + */ - "cshproman8": "hproman8", - "r8": "hproman8", - "roman8": "hproman8", - "xroman8": "hproman8", - "ibm1051": "hproman8", +function fmtLong(ms) { + return plural(ms, d, 'day') || + plural(ms, h, 'hour') || + plural(ms, m, 'minute') || + plural(ms, s, 'second') || + ms + ' ms'; +} - "mac": "macintosh", - "csmacintosh": "macintosh", -}; +/** + * Pluralization helper. + */ +function plural(ms, n, name) { + if (ms < n) { + return; + } + if (ms < n * 1.5) { + return Math.floor(ms / n) + ' ' + name; + } + return Math.ceil(ms / n) + ' ' + name + 's'; +} /***/ }), -/***/ 11155: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 9486: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var Buffer = __nccwpck_require__(15118).Buffer; - -// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js - -// == UTF16-BE codec. ========================================================== +const path = __nccwpck_require__(85622); +const locatePath = __nccwpck_require__(63447); -exports.utf16be = Utf16BECodec; -function Utf16BECodec() { -} +module.exports = (filename, opts = {}) => { + const startDir = path.resolve(opts.cwd || ''); + const {root} = path.parse(startDir); -Utf16BECodec.prototype.encoder = Utf16BEEncoder; -Utf16BECodec.prototype.decoder = Utf16BEDecoder; -Utf16BECodec.prototype.bomAware = true; + const filenames = [].concat(filename); + return new Promise(resolve => { + (function find(dir) { + locatePath(filenames, {cwd: dir}).then(file => { + if (file) { + resolve(path.join(dir, file)); + } else if (dir === root) { + resolve(null); + } else { + find(path.dirname(dir)); + } + }); + })(startDir); + }); +}; -// -- Encoding +module.exports.sync = (filename, opts = {}) => { + let dir = path.resolve(opts.cwd || ''); + const {root} = path.parse(dir); -function Utf16BEEncoder() { -} + const filenames = [].concat(filename); -Utf16BEEncoder.prototype.write = function(str) { - var buf = Buffer.from(str, 'ucs2'); - for (var i = 0; i < buf.length; i += 2) { - var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; - } - return buf; -} + // eslint-disable-next-line no-constant-condition + while (true) { + const file = locatePath.sync(filenames, {cwd: dir}); -Utf16BEEncoder.prototype.end = function() { -} + if (file) { + return path.join(dir, file); + } + if (dir === root) { + return null; + } -// -- Decoding + dir = path.dirname(dir); + } +}; -function Utf16BEDecoder() { - this.overflowByte = -1; -} -Utf16BEDecoder.prototype.write = function(buf) { - if (buf.length == 0) - return ''; +/***/ }), - var buf2 = Buffer.alloc(buf.length + 1), - i = 0, j = 0; +/***/ 35298: +/***/ ((module) => { - if (this.overflowByte !== -1) { - buf2[0] = buf[0]; - buf2[1] = this.overflowByte; - i = 1; j = 2; - } +"use strict"; - for (; i < buf.length-1; i += 2, j+= 2) { - buf2[j] = buf[i+1]; - buf2[j+1] = buf[i]; - } - this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; +// You may be tempted to copy and paste this, +// but take a look at the commit history first, +// this is a moving target so relying on the module +// is the best way to make sure the optimization +// method is kept up to date and compatible with +// every Node version. - return buf2.slice(0, j).toString('ucs2'); +function flatstr (s) { + s | 0 + return s } -Utf16BEDecoder.prototype.end = function() { -} +module.exports = flatstr +/***/ }), -// == UTF-16 codec ============================================================= -// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. -// Defaults to UTF-16LE, as it's prevalent and default in Node. -// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le -// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); +/***/ 68329: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). +if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); -exports.utf16 = Utf16Codec; -function Utf16Codec(codecOptions, iconv) { - this.iconv = iconv; -} +var util = __nccwpck_require__(31669), + fs = __nccwpck_require__(35747), + EventEmitter = __nccwpck_require__(28614).EventEmitter, + crypto = __nccwpck_require__(76417); -Utf16Codec.prototype.encoder = Utf16Encoder; -Utf16Codec.prototype.decoder = Utf16Decoder; +function File(properties) { + EventEmitter.call(this); + this.size = 0; + this.path = null; + this.name = null; + this.type = null; + this.hash = null; + this.lastModifiedDate = null; -// -- Encoding (pass-through) + this._writeStream = null; + + for (var key in properties) { + this[key] = properties[key]; + } -function Utf16Encoder(options, codec) { - options = options || {}; - if (options.addBOM === undefined) - options.addBOM = true; - this.encoder = codec.iconv.getEncoder('utf-16le', options); + if(typeof this.hash === 'string') { + this.hash = crypto.createHash(properties.hash); + } else { + this.hash = null; + } } +module.exports = File; +util.inherits(File, EventEmitter); -Utf16Encoder.prototype.write = function(str) { - return this.encoder.write(str); -} +File.prototype.open = function() { + this._writeStream = new fs.WriteStream(this.path); +}; -Utf16Encoder.prototype.end = function() { - return this.encoder.end(); -} +File.prototype.toJSON = function() { + var json = { + size: this.size, + path: this.path, + name: this.name, + type: this.type, + mtime: this.lastModifiedDate, + length: this.length, + filename: this.filename, + mime: this.mime + }; + if (this.hash && this.hash != "") { + json.hash = this.hash; + } + return json; +}; +File.prototype.write = function(buffer, cb) { + var self = this; + if (self.hash) { + self.hash.update(buffer); + } -// -- Decoding + if (this._writeStream.closed) { + return cb(); + } -function Utf16Decoder(options, codec) { - this.decoder = null; - this.initialBytes = []; - this.initialBytesLen = 0; + this._writeStream.write(buffer, function() { + self.lastModifiedDate = new Date(); + self.size += buffer.length; + self.emit('progress', self.size); + cb(); + }); +}; - this.options = options || {}; - this.iconv = codec.iconv; -} +File.prototype.end = function(cb) { + var self = this; + if (self.hash) { + self.hash = self.hash.digest('hex'); + } + this._writeStream.end(function() { + self.emit('end'); + cb(); + }); +}; -Utf16Decoder.prototype.write = function(buf) { - if (!this.decoder) { - // Codec is not chosen yet. Accumulate initial bytes. - this.initialBytes.push(buf); - this.initialBytesLen += buf.length; - - if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) - return ''; - // We have enough bytes -> detect endianness. - var buf = Buffer.concat(this.initialBytes), - encoding = detectEncoding(buf, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); - this.initialBytes.length = this.initialBytesLen = 0; - } +/***/ }), - return this.decoder.write(buf); -} +/***/ 7973: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -Utf16Decoder.prototype.end = function() { - if (!this.decoder) { - var buf = Buffer.concat(this.initialBytes), - encoding = detectEncoding(buf, this.options.defaultEncoding); - this.decoder = this.iconv.getDecoder(encoding, this.options); +if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); - var res = this.decoder.write(buf), - trail = this.decoder.end(); +var crypto = __nccwpck_require__(76417); +var fs = __nccwpck_require__(35747); +var util = __nccwpck_require__(31669), + path = __nccwpck_require__(85622), + File = __nccwpck_require__(68329), + MultipartParser = __nccwpck_require__(31323).MultipartParser, + QuerystringParser = __nccwpck_require__(80825)/* .QuerystringParser */ .l, + OctetParser = __nccwpck_require__(48680)/* .OctetParser */ .h, + JSONParser = __nccwpck_require__(715)/* .JSONParser */ .c, + StringDecoder = __nccwpck_require__(24304).StringDecoder, + EventEmitter = __nccwpck_require__(28614).EventEmitter, + Stream = __nccwpck_require__(92413).Stream, + os = __nccwpck_require__(12087); - return trail ? (res + trail) : res; - } - return this.decoder.end(); -} +function IncomingForm(opts) { + if (!(this instanceof IncomingForm)) return new IncomingForm(opts); + EventEmitter.call(this); -function detectEncoding(buf, defaultEncoding) { - var enc = defaultEncoding || 'utf-16le'; + opts=opts||{}; - if (buf.length >= 2) { - // Check BOM. - if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM - enc = 'utf-16be'; - else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM - enc = 'utf-16le'; - else { - // No BOM found. Try to deduce encoding from initial content. - // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. - // So, we count ASCII as if it was LE or BE, and decide from that. - var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions - _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. + this.error = null; + this.ended = false; - for (var i = 0; i < _len; i += 2) { - if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; - if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; - } + this.maxFields = opts.maxFields || 1000; + this.maxFieldsSize = opts.maxFieldsSize || 20 * 1024 * 1024; + this.maxFileSize = opts.maxFileSize || 200 * 1024 * 1024; + this.keepExtensions = opts.keepExtensions || false; + this.uploadDir = opts.uploadDir || (os.tmpdir && os.tmpdir()) || os.tmpDir(); + this.encoding = opts.encoding || 'utf-8'; + this.headers = null; + this.type = null; + this.hash = opts.hash || false; + this.multiples = opts.multiples || false; - if (asciiCharsBE > asciiCharsLE) - enc = 'utf-16be'; - else if (asciiCharsBE < asciiCharsLE) - enc = 'utf-16le'; - } - } + this.bytesReceived = null; + this.bytesExpected = null; + + this._parser = null; + this._flushing = 0; + this._fieldsSize = 0; + this._fileSize = 0; + this.openedFiles = []; - return enc; + return this; } +util.inherits(IncomingForm, EventEmitter); +exports.c = IncomingForm; +IncomingForm.prototype.parse = function(req, cb) { + this.pause = function() { + try { + req.pause(); + } catch (err) { + // the stream was destroyed + if (!this.ended) { + // before it was completed, crash & burn + this._error(err); + } + return false; + } + return true; + }; + this.resume = function() { + try { + req.resume(); + } catch (err) { + // the stream was destroyed + if (!this.ended) { + // before it was completed, crash & burn + this._error(err); + } + return false; + } + return true; + }; -/***/ }), - -/***/ 51644: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // Setup callback first, so we don't miss anything from data events emitted + // immediately. + if (cb) { + var fields = {}, files = {}; + this + .on('field', function(name, value) { + fields[name] = value; + }) + .on('file', function(name, file) { + if (this.multiples) { + if (files[name]) { + if (!Array.isArray(files[name])) { + files[name] = [files[name]]; + } + files[name].push(file); + } else { + files[name] = file; + } + } else { + files[name] = file; + } + }) + .on('error', function(err) { + cb(err, fields, files); + }) + .on('end', function() { + cb(null, fields, files); + }); + } -"use strict"; + // Parse headers and setup the parser, ready to start listening for data. + this.writeHeaders(req.headers); -var Buffer = __nccwpck_require__(15118).Buffer; + // Start listening for data. + var self = this; + req + .on('error', function(err) { + self._error(err); + }) + .on('aborted', function() { + self.emit('aborted'); + self._error(new Error('Request aborted')); + }) + .on('data', function(buffer) { + self.write(buffer); + }) + .on('end', function() { + if (self.error) { + return; + } -// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 -// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 + var err = self._parser.end(); + if (err) { + self._error(err); + } + }); -exports.utf7 = Utf7Codec; -exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 -function Utf7Codec(codecOptions, iconv) { - this.iconv = iconv; + return this; }; -Utf7Codec.prototype.encoder = Utf7Encoder; -Utf7Codec.prototype.decoder = Utf7Decoder; -Utf7Codec.prototype.bomAware = true; +IncomingForm.prototype.writeHeaders = function(headers) { + this.headers = headers; + this._parseContentLength(); + this._parseContentType(); +}; +IncomingForm.prototype.write = function(buffer) { + if (this.error) { + return; + } + if (!this._parser) { + this._error(new Error('uninitialized parser')); + return; + } -// -- Encoding + this.bytesReceived += buffer.length; + this.emit('progress', this.bytesReceived, this.bytesExpected); -var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + var bytesParsed = this._parser.write(buffer); + if (bytesParsed !== buffer.length) { + this._error(new Error('parser error, '+bytesParsed+' of '+buffer.length+' bytes parsed')); + } -function Utf7Encoder(options, codec) { - this.iconv = codec.iconv; -} + return bytesParsed; +}; -Utf7Encoder.prototype.write = function(str) { - // Naive implementation. - // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". - return Buffer.from(str.replace(nonDirectChars, function(chunk) { - return "+" + (chunk === '+' ? '' : - this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) - + "-"; - }.bind(this))); -} +IncomingForm.prototype.pause = function() { + // this does nothing, unless overwritten in IncomingForm.parse + return false; +}; -Utf7Encoder.prototype.end = function() { -} +IncomingForm.prototype.resume = function() { + // this does nothing, unless overwritten in IncomingForm.parse + return false; +}; +IncomingForm.prototype.onPart = function(part) { + // this method can be overwritten by the user + this.handlePart(part); +}; -// -- Decoding +IncomingForm.prototype.handlePart = function(part) { + var self = this; -function Utf7Decoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} + // This MUST check exactly for undefined. You can not change it to !part.filename. + if (part.filename === undefined) { + var value = '' + , decoder = new StringDecoder(this.encoding); -var base64Regex = /[A-Za-z0-9\/+]/; -var base64Chars = []; -for (var i = 0; i < 256; i++) - base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + part.on('data', function(buffer) { + self._fieldsSize += buffer.length; + if (self._fieldsSize > self.maxFieldsSize) { + self._error(new Error('maxFieldsSize exceeded, received '+self._fieldsSize+' bytes of field data')); + return; + } + value += decoder.write(buffer); + }); -var plusChar = '+'.charCodeAt(0), - minusChar = '-'.charCodeAt(0), - andChar = '&'.charCodeAt(0); + part.on('end', function() { + self.emit('field', part.name, value); + }); + return; + } -Utf7Decoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; + this._flushing++; - // The decoder is more involved as we must handle chunks in stream. + var file = new File({ + path: this._uploadPath(part.filename), + name: part.filename, + type: part.mime, + hash: self.hash + }); - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '+' - if (buf[i] == plusChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; - } - } else { // We decode base64. - if (!base64Chars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" - res += "+"; - } else { - var b64str = base64Accum + buf.slice(lastI, i).toString(); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } + this.emit('fileBegin', part.name, file); - if (buf[i] != minusChar) // Minus is absorbed after base64. - i--; + file.open(); + this.openedFiles.push(file); - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } - } + part.on('data', function(buffer) { + self._fileSize += buffer.length; + if (self._fileSize > self.maxFileSize) { + self._error(new Error('maxFileSize exceeded, received '+self._fileSize+' bytes of file data')); + return; } - - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString(); - - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); - - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + if (buffer.length == 0) { + return; } + self.pause(); + file.write(buffer, function() { + self.resume(); + }); + }); - this.inBase64 = inBase64; - this.base64Accum = base64Accum; + part.on('end', function() { + file.end(function() { + self._flushing--; + self.emit('file', part.name, file); + self._maybeEnd(); + }); + }); +}; - return res; +function dummyParser(self) { + return { + end: function () { + self.ended = true; + self._maybeEnd(); + return null; + } + }; } -Utf7Decoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); +IncomingForm.prototype._parseContentType = function() { + if (this.bytesExpected === 0) { + this._parser = dummyParser(this); + return; + } - this.inBase64 = false; - this.base64Accum = ''; - return res; -} + if (!this.headers['content-type']) { + this._error(new Error('bad content-type header, no content-type')); + return; + } + if (this.headers['content-type'].match(/octet-stream/i)) { + this._initOctetStream(); + return; + } -// UTF-7-IMAP codec. -// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) -// Differences: -// * Base64 part is started by "&" instead of "+" -// * Direct characters are 0x20-0x7E, except "&" (0x26) -// * In Base64, "," is used instead of "/" -// * Base64 must not be used to represent direct characters. -// * No implicit shift back from Base64 (should always end with '-') -// * String must end in non-shifted position. -// * "-&" while in base64 is not allowed. + if (this.headers['content-type'].match(/urlencoded/i)) { + this._initUrlencoded(); + return; + } + if (this.headers['content-type'].match(/multipart/i)) { + var m = this.headers['content-type'].match(/boundary=(?:"([^"]+)"|([^;]+))/i); + if (m) { + this._initMultipart(m[1] || m[2]); + } else { + this._error(new Error('bad content-type header, no multipart boundary')); + } + return; + } -exports.utf7imap = Utf7IMAPCodec; -function Utf7IMAPCodec(codecOptions, iconv) { - this.iconv = iconv; -}; + if (this.headers['content-type'].match(/json/i)) { + this._initJSONencoded(); + return; + } -Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; -Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; -Utf7IMAPCodec.prototype.bomAware = true; + this._error(new Error('bad content-type header, unknown content-type: '+this.headers['content-type'])); +}; +IncomingForm.prototype._error = function(err) { + if (this.error || this.ended) { + return; + } -// -- Encoding + this.error = err; + this.emit('error', err); -function Utf7IMAPEncoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = Buffer.alloc(6); - this.base64AccumIdx = 0; -} + if (Array.isArray(this.openedFiles)) { + this.openedFiles.forEach(function(file) { + file._writeStream.destroy(); + setTimeout(fs.unlink, 0, file.path, function(error) { }); + }); + } +}; -Utf7IMAPEncoder.prototype.write = function(str) { - var inBase64 = this.inBase64, - base64Accum = this.base64Accum, - base64AccumIdx = this.base64AccumIdx, - buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; +IncomingForm.prototype._parseContentLength = function() { + this.bytesReceived = 0; + if (this.headers['content-length']) { + this.bytesExpected = parseInt(this.headers['content-length'], 10); + } else if (this.headers['transfer-encoding'] === undefined) { + this.bytesExpected = 0; + } - for (var i = 0; i < str.length; i++) { - var uChar = str.charCodeAt(i); - if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. - if (inBase64) { - if (base64AccumIdx > 0) { - bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - base64AccumIdx = 0; - } + if (this.bytesExpected !== null) { + this.emit('progress', this.bytesReceived, this.bytesExpected); + } +}; - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - inBase64 = false; - } +IncomingForm.prototype._newParser = function() { + return new MultipartParser(); +}; - if (!inBase64) { - buf[bufIdx++] = uChar; // Write direct character +IncomingForm.prototype._initMultipart = function(boundary) { + this.type = 'multipart'; - if (uChar === andChar) // Ampersand -> '&-' - buf[bufIdx++] = minusChar; - } + var parser = new MultipartParser(), + self = this, + headerField, + headerValue, + part; - } else { // Non-direct character - if (!inBase64) { - buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. - inBase64 = true; - } - if (inBase64) { - base64Accum[base64AccumIdx++] = uChar >> 8; - base64Accum[base64AccumIdx++] = uChar & 0xFF; + parser.initWithBoundary(boundary); - if (base64AccumIdx == base64Accum.length) { - bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); - base64AccumIdx = 0; - } - } - } - } + parser.onPartBegin = function() { + part = new Stream(); + part.readable = true; + part.headers = {}; + part.name = null; + part.filename = null; + part.mime = null; - this.inBase64 = inBase64; - this.base64AccumIdx = base64AccumIdx; + part.transferEncoding = 'binary'; + part.transferBuffer = ''; - return buf.slice(0, bufIdx); -} + headerField = ''; + headerValue = ''; + }; -Utf7IMAPEncoder.prototype.end = function() { - var buf = Buffer.alloc(10), bufIdx = 0; - if (this.inBase64) { - if (this.base64AccumIdx > 0) { - bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); - this.base64AccumIdx = 0; - } + parser.onHeaderField = function(b, start, end) { + headerField += b.toString(self.encoding, start, end); + }; - buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. - this.inBase64 = false; - } + parser.onHeaderValue = function(b, start, end) { + headerValue += b.toString(self.encoding, start, end); + }; - return buf.slice(0, bufIdx); -} + parser.onHeaderEnd = function() { + headerField = headerField.toLowerCase(); + part.headers[headerField] = headerValue; + // matches either a quoted-string or a token (RFC 2616 section 19.5.1) + var m = headerValue.match(/\bname=("([^"]*)"|([^\(\)<>@,;:\\"\/\[\]\?=\{\}\s\t/]+))/i); + if (headerField == 'content-disposition') { + if (m) { + part.name = m[2] || m[3] || ''; + } -// -- Decoding + part.filename = self._fileName(headerValue); + } else if (headerField == 'content-type') { + part.mime = headerValue; + } else if (headerField == 'content-transfer-encoding') { + part.transferEncoding = headerValue.toLowerCase(); + } -function Utf7IMAPDecoder(options, codec) { - this.iconv = codec.iconv; - this.inBase64 = false; - this.base64Accum = ''; -} + headerField = ''; + headerValue = ''; + }; -var base64IMAPChars = base64Chars.slice(); -base64IMAPChars[','.charCodeAt(0)] = true; + parser.onHeadersEnd = function() { + switch(part.transferEncoding){ + case 'binary': + case '7bit': + case '8bit': + parser.onPartData = function(b, start, end) { + part.emit('data', b.slice(start, end)); + }; -Utf7IMAPDecoder.prototype.write = function(buf) { - var res = "", lastI = 0, - inBase64 = this.inBase64, - base64Accum = this.base64Accum; + parser.onPartEnd = function() { + part.emit('end'); + }; + break; - // The decoder is more involved as we must handle chunks in stream. - // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). + case 'base64': + parser.onPartData = function(b, start, end) { + part.transferBuffer += b.slice(start, end).toString('ascii'); - for (var i = 0; i < buf.length; i++) { - if (!inBase64) { // We're in direct mode. - // Write direct chars until '&' - if (buf[i] == andChar) { - res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. - lastI = i+1; - inBase64 = true; - } - } else { // We decode base64. - if (!base64IMAPChars[buf[i]]) { // Base64 ended. - if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" - res += "&"; - } else { - var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } + /* + four bytes (chars) in base64 converts to three bytes in binary + encoding. So we should always work with a number of bytes that + can be divided by 4, it will result in a number of buytes that + can be divided vy 3. + */ + var offset = parseInt(part.transferBuffer.length / 4, 10) * 4; + part.emit('data', new Buffer(part.transferBuffer.substring(0, offset), 'base64')); + part.transferBuffer = part.transferBuffer.substring(offset); + }; - if (buf[i] != minusChar) // Minus may be absorbed after base64. - i--; + parser.onPartEnd = function() { + part.emit('data', new Buffer(part.transferBuffer, 'base64')); + part.emit('end'); + }; + break; - lastI = i+1; - inBase64 = false; - base64Accum = ''; - } - } + default: + return self._error(new Error('unknown transfer-encoding')); } - if (!inBase64) { - res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. - } else { - var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); + self.onPart(part); + }; - var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. - base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. - b64str = b64str.slice(0, canBeDecoded); - res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); - } + parser.onEnd = function() { + self.ended = true; + self._maybeEnd(); + }; - this.inBase64 = inBase64; - this.base64Accum = base64Accum; + this._parser = parser; +}; - return res; -} +IncomingForm.prototype._fileName = function(headerValue) { + // matches either a quoted-string or a token (RFC 2616 section 19.5.1) + var m = headerValue.match(/\bfilename=("(.*?)"|([^\(\)<>@,;:\\"\/\[\]\?=\{\}\s\t/]+))($|;\s)/i); + if (!m) return; -Utf7IMAPDecoder.prototype.end = function() { - var res = ""; - if (this.inBase64 && this.base64Accum.length > 0) - res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + var match = m[2] || m[3] || ''; + var filename = match.substr(match.lastIndexOf('\\') + 1); + filename = filename.replace(/%22/g, '"'); + filename = filename.replace(/&#([\d]{4});/g, function(m, code) { + return String.fromCharCode(code); + }); + return filename; +}; - this.inBase64 = false; - this.base64Accum = ''; - return res; -} +IncomingForm.prototype._initUrlencoded = function() { + this.type = 'urlencoded'; + var parser = new QuerystringParser(this.maxFields) + , self = this; + parser.onField = function(key, val) { + self.emit('field', key, val); + }; + parser.onEnd = function() { + self.ended = true; + self._maybeEnd(); + }; -/***/ }), + this._parser = parser; +}; -/***/ 67961: -/***/ ((__unused_webpack_module, exports) => { +IncomingForm.prototype._initOctetStream = function() { + this.type = 'octet-stream'; + var filename = this.headers['x-file-name']; + var mime = this.headers['content-type']; -"use strict"; + var file = new File({ + path: this._uploadPath(filename), + name: filename, + type: mime + }); + this.emit('fileBegin', filename, file); + file.open(); + this.openedFiles.push(file); + this._flushing++; -var BOMChar = '\uFEFF'; + var self = this; -exports.PrependBOM = PrependBOMWrapper -function PrependBOMWrapper(encoder, options) { - this.encoder = encoder; - this.addBOM = true; -} + self._parser = new OctetParser(); -PrependBOMWrapper.prototype.write = function(str) { - if (this.addBOM) { - str = BOMChar + str; - this.addBOM = false; + //Keep track of writes that haven't finished so we don't emit the file before it's done being written + var outstandingWrites = 0; + + self._parser.on('data', function(buffer){ + self.pause(); + outstandingWrites++; + + file.write(buffer, function() { + outstandingWrites--; + self.resume(); + + if(self.ended){ + self._parser.emit('doneWritingFile'); + } + }); + }); + + self._parser.on('end', function(){ + self._flushing--; + self.ended = true; + + var done = function(){ + file.end(function() { + self.emit('file', 'file', file); + self._maybeEnd(); + }); + }; + + if(outstandingWrites === 0){ + done(); + } else { + self._parser.once('doneWritingFile', done); } + }); +}; - return this.encoder.write(str); -} +IncomingForm.prototype._initJSONencoded = function() { + this.type = 'json'; -PrependBOMWrapper.prototype.end = function() { - return this.encoder.end(); -} + var parser = new JSONParser(this) + , self = this; + parser.onField = function(key, val) { + self.emit('field', key, val); + }; -//------------------------------------------------------------------------------ + parser.onEnd = function() { + self.ended = true; + self._maybeEnd(); + }; -exports.StripBOM = StripBOMWrapper; -function StripBOMWrapper(decoder, options) { - this.decoder = decoder; - this.pass = false; - this.options = options || {}; -} + this._parser = parser; +}; -StripBOMWrapper.prototype.write = function(buf) { - var res = this.decoder.write(buf); - if (this.pass || !res) - return res; +IncomingForm.prototype._uploadPath = function(filename) { + var buf = crypto.randomBytes(16); + var name = 'upload_' + buf.toString('hex'); - if (res[0] === BOMChar) { - res = res.slice(1); - if (typeof this.options.stripBOM === 'function') - this.options.stripBOM(); - } + if (this.keepExtensions) { + var ext = path.extname(filename); + ext = ext.replace(/(\.[a-z0-9]+).*/i, '$1'); - this.pass = true; - return res; -} + name += ext; + } -StripBOMWrapper.prototype.end = function() { - return this.decoder.end(); -} + return path.join(this.uploadDir, name); +}; + +IncomingForm.prototype._maybeEnd = function() { + if (!this.ended || this._flushing || this.error) { + return; + } + this.emit('end'); +}; /***/ }), -/***/ 30393: +/***/ 95265: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; - -var Buffer = __nccwpck_require__(64293).Buffer; -// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer +var IncomingForm = __nccwpck_require__(7973)/* .IncomingForm */ .c; +IncomingForm.IncomingForm = IncomingForm; +module.exports = IncomingForm; -// == Extend Node primitives to use iconv-lite ================================= -module.exports = function (iconv) { - var original = undefined; // Place to keep original methods. +/***/ }), - // Node authors rewrote Buffer internals to make it compatible with - // Uint8Array and we cannot patch key functions since then. - // Note: this does use older Buffer API on a purpose - iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array); +/***/ 715: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - iconv.extendNodeEncodings = function extendNodeEncodings() { - if (original) return; - original = {}; +if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); - if (!iconv.supportsNodeEncodingsExtension) { - console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); - console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); - return; - } +var Buffer = __nccwpck_require__(64293).Buffer; - var nodeNativeEncodings = { - 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, - 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, - }; +function JSONParser(parent) { + this.parent = parent; + this.chunks = []; + this.bytesWritten = 0; +} +exports.c = JSONParser; - Buffer.isNativeEncoding = function(enc) { - return enc && nodeNativeEncodings[enc.toLowerCase()]; - } +JSONParser.prototype.write = function(buffer) { + this.bytesWritten += buffer.length; + this.chunks.push(buffer); + return buffer.length; +}; - // -- SlowBuffer ----------------------------------------------------------- - var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; +JSONParser.prototype.end = function() { + try { + var fields = JSON.parse(Buffer.concat(this.chunks)); + for (var field in fields) { + this.onField(field, fields[field]); + } + } catch (e) { + this.parent.emit('error', e); + } + this.data = null; - original.SlowBufferToString = SlowBuffer.prototype.toString; - SlowBuffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); + this.onEnd(); +}; - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferToString.call(this, encoding, start, end); - // Otherwise, use our decoding method. - if (typeof start == 'undefined') start = 0; - if (typeof end == 'undefined') end = this.length; - return iconv.decode(this.slice(start, end), encoding); - } +/***/ }), - original.SlowBufferWrite = SlowBuffer.prototype.write; - SlowBuffer.prototype.write = function(string, offset, length, encoding) { - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length; - length = undefined; - } - } else { // legacy - var swap = encoding; - encoding = offset; - offset = length; - length = swap; - } +/***/ 31323: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; - } - } - encoding = String(encoding || 'utf8').toLowerCase(); +var Buffer = __nccwpck_require__(64293).Buffer, + s = 0, + S = + { PARSER_UNINITIALIZED: s++, + START: s++, + START_BOUNDARY: s++, + HEADER_FIELD_START: s++, + HEADER_FIELD: s++, + HEADER_VALUE_START: s++, + HEADER_VALUE: s++, + HEADER_VALUE_ALMOST_DONE: s++, + HEADERS_ALMOST_DONE: s++, + PART_DATA_START: s++, + PART_DATA: s++, + PART_END: s++, + END: s++ + }, - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.SlowBufferWrite.call(this, string, offset, length, encoding); + f = 1, + F = + { PART_BOUNDARY: f, + LAST_BOUNDARY: f *= 2 + }, - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); + LF = 10, + CR = 13, + SPACE = 32, + HYPHEN = 45, + COLON = 58, + A = 97, + Z = 122, - // Otherwise, use our encoding method. - var buf = iconv.encode(string, encoding); - if (buf.length < length) length = buf.length; - buf.copy(this, offset, 0, length); - return length; - } + lower = function(c) { + return c | 0x20; + }; - // -- Buffer --------------------------------------------------------------- +for (s in S) { + exports[s] = S[s]; +} - original.BufferIsEncoding = Buffer.isEncoding; - Buffer.isEncoding = function(encoding) { - return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); - } +function MultipartParser() { + this.boundary = null; + this.boundaryChars = null; + this.lookbehind = null; + this.state = S.PARSER_UNINITIALIZED; - original.BufferByteLength = Buffer.byteLength; - Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { - encoding = String(encoding || 'utf8').toLowerCase(); + this.index = null; + this.flags = 0; +} +exports.MultipartParser = MultipartParser; - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferByteLength.call(this, str, encoding); +MultipartParser.stateToString = function(stateNumber) { + for (var state in S) { + var number = S[state]; + if (number === stateNumber) return state; + } +}; - // Slow, I know, but we don't have a better way yet. - return iconv.encode(str, encoding).length; - } +MultipartParser.prototype.initWithBoundary = function(str) { + this.boundary = new Buffer(str.length+4); + this.boundary.write('\r\n--', 0); + this.boundary.write(str, 4); + this.lookbehind = new Buffer(this.boundary.length+8); + this.state = S.START; - original.BufferToString = Buffer.prototype.toString; - Buffer.prototype.toString = function(encoding, start, end) { - encoding = String(encoding || 'utf8').toLowerCase(); + this.boundaryChars = {}; + for (var i = 0; i < this.boundary.length; i++) { + this.boundaryChars[this.boundary[i]] = true; + } +}; - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferToString.call(this, encoding, start, end); +MultipartParser.prototype.write = function(buffer) { + var self = this, + i = 0, + len = buffer.length, + prevIndex = this.index, + index = this.index, + state = this.state, + flags = this.flags, + lookbehind = this.lookbehind, + boundary = this.boundary, + boundaryChars = this.boundaryChars, + boundaryLength = this.boundary.length, + boundaryEnd = boundaryLength - 1, + bufferLength = buffer.length, + c, + cl, - // Otherwise, use our decoding method. - if (typeof start == 'undefined') start = 0; - if (typeof end == 'undefined') end = this.length; - return iconv.decode(this.slice(start, end), encoding); + mark = function(name) { + self[name+'Mark'] = i; + }, + clear = function(name) { + delete self[name+'Mark']; + }, + callback = function(name, buffer, start, end) { + if (start !== undefined && start === end) { + return; } - original.BufferWrite = Buffer.prototype.write; - Buffer.prototype.write = function(string, offset, length, encoding) { - var _offset = offset, _length = length, _encoding = encoding; - // Support both (string, offset, length, encoding) - // and the legacy (string, encoding, offset, length) - if (isFinite(offset)) { - if (!isFinite(length)) { - encoding = length; - length = undefined; - } - } else { // legacy - var swap = encoding; - encoding = offset; - offset = length; - length = swap; - } - - encoding = String(encoding || 'utf8').toLowerCase(); + var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); + if (callbackSymbol in self) { + self[callbackSymbol](buffer, start, end); + } + }, + dataCallback = function(name, clear) { + var markSymbol = name+'Mark'; + if (!(markSymbol in self)) { + return; + } - // Use native conversion when possible - if (Buffer.isNativeEncoding(encoding)) - return original.BufferWrite.call(this, string, _offset, _length, _encoding); + if (!clear) { + callback(name, buffer, self[markSymbol], buffer.length); + self[markSymbol] = 0; + } else { + callback(name, buffer, self[markSymbol], i); + delete self[markSymbol]; + } + }; - offset = +offset || 0; - var remaining = this.length - offset; - if (!length) { - length = remaining; - } else { - length = +length; - if (length > remaining) { - length = remaining; - } - } + for (i = 0; i < len; i++) { + c = buffer[i]; + switch (state) { + case S.PARSER_UNINITIALIZED: + return i; + case S.START: + index = 0; + state = S.START_BOUNDARY; + case S.START_BOUNDARY: + if (index == boundary.length - 2) { + if (c == HYPHEN) { + flags |= F.LAST_BOUNDARY; + } else if (c != CR) { + return i; + } + index++; + break; + } else if (index - 1 == boundary.length - 2) { + if (flags & F.LAST_BOUNDARY && c == HYPHEN){ + callback('end'); + state = S.END; + flags = 0; + } else if (!(flags & F.LAST_BOUNDARY) && c == LF) { + index = 0; + callback('partBegin'); + state = S.HEADER_FIELD_START; + } else { + return i; + } + break; + } - if (string.length > 0 && (length < 0 || offset < 0)) - throw new RangeError('attempt to write beyond buffer bounds'); + if (c != boundary[index+2]) { + index = -2; + } + if (c == boundary[index+2]) { + index++; + } + break; + case S.HEADER_FIELD_START: + state = S.HEADER_FIELD; + mark('headerField'); + index = 0; + case S.HEADER_FIELD: + if (c == CR) { + clear('headerField'); + state = S.HEADERS_ALMOST_DONE; + break; + } - // Otherwise, use our encoding method. - var buf = iconv.encode(string, encoding); - if (buf.length < length) length = buf.length; - buf.copy(this, offset, 0, length); - return length; + index++; + if (c == HYPHEN) { + break; + } - // TODO: Set _charsWritten. + if (c == COLON) { + if (index == 1) { + // empty header field + return i; + } + dataCallback('headerField', true); + state = S.HEADER_VALUE_START; + break; } + cl = lower(c); + if (cl < A || cl > Z) { + return i; + } + break; + case S.HEADER_VALUE_START: + if (c == SPACE) { + break; + } - // -- Readable ------------------------------------------------------------- - if (iconv.supportsStreams) { - var Readable = __nccwpck_require__(92413).Readable; + mark('headerValue'); + state = S.HEADER_VALUE; + case S.HEADER_VALUE: + if (c == CR) { + dataCallback('headerValue', true); + callback('headerEnd'); + state = S.HEADER_VALUE_ALMOST_DONE; + } + break; + case S.HEADER_VALUE_ALMOST_DONE: + if (c != LF) { + return i; + } + state = S.HEADER_FIELD_START; + break; + case S.HEADERS_ALMOST_DONE: + if (c != LF) { + return i; + } - original.ReadableSetEncoding = Readable.prototype.setEncoding; - Readable.prototype.setEncoding = function setEncoding(enc, options) { - // Use our own decoder, it has the same interface. - // We cannot use original function as it doesn't handle BOM-s. - this._readableState.decoder = iconv.getDecoder(enc, options); - this._readableState.encoding = enc; - } + callback('headersEnd'); + state = S.PART_DATA_START; + break; + case S.PART_DATA_START: + state = S.PART_DATA; + mark('partData'); + case S.PART_DATA: + prevIndex = index; - Readable.prototype.collect = iconv._collect; + if (index === 0) { + // boyer-moore derrived algorithm to safely skip non-boundary data + i += boundaryEnd; + while (i < bufferLength && !(buffer[i] in boundaryChars)) { + i += boundaryLength; + } + i -= boundaryEnd; + c = buffer[i]; } - } - // Remove iconv-lite Node primitive extensions. - iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { - if (!iconv.supportsNodeEncodingsExtension) - return; - if (!original) - throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") + if (index < boundary.length) { + if (boundary[index] == c) { + if (index === 0) { + dataCallback('partData', true); + } + index++; + } else { + index = 0; + } + } else if (index == boundary.length) { + index++; + if (c == CR) { + // CR = part boundary + flags |= F.PART_BOUNDARY; + } else if (c == HYPHEN) { + // HYPHEN = end boundary + flags |= F.LAST_BOUNDARY; + } else { + index = 0; + } + } else if (index - 1 == boundary.length) { + if (flags & F.PART_BOUNDARY) { + index = 0; + if (c == LF) { + // unset the PART_BOUNDARY flag + flags &= ~F.PART_BOUNDARY; + callback('partEnd'); + callback('partBegin'); + state = S.HEADER_FIELD_START; + break; + } + } else if (flags & F.LAST_BOUNDARY) { + if (c == HYPHEN) { + callback('partEnd'); + callback('end'); + state = S.END; + flags = 0; + } else { + index = 0; + } + } else { + index = 0; + } + } - delete Buffer.isNativeEncoding; + if (index > 0) { + // when matching a possible boundary, keep a lookbehind reference + // in case it turns out to be a false lead + lookbehind[index-1] = c; + } else if (prevIndex > 0) { + // if our boundary turned out to be rubbish, the captured lookbehind + // belongs to partData + callback('partData', lookbehind, 0, prevIndex); + prevIndex = 0; + mark('partData'); - var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; + // reconsider the current character even so it interrupted the sequence + // it could be the beginning of a new sequence + i--; + } - SlowBuffer.prototype.toString = original.SlowBufferToString; - SlowBuffer.prototype.write = original.SlowBufferWrite; + break; + case S.END: + break; + default: + return i; + } + } - Buffer.isEncoding = original.BufferIsEncoding; - Buffer.byteLength = original.BufferByteLength; - Buffer.prototype.toString = original.BufferToString; - Buffer.prototype.write = original.BufferWrite; + dataCallback('headerField'); + dataCallback('headerValue'); + dataCallback('partData'); - if (iconv.supportsStreams) { - var Readable = __nccwpck_require__(92413).Readable; + this.index = index; + this.state = state; + this.flags = flags; - Readable.prototype.setEncoding = original.ReadableSetEncoding; - delete Readable.prototype.collect; - } + return len; +}; - original = undefined; +MultipartParser.prototype.end = function() { + var callback = function(self, name) { + var callbackSymbol = 'on'+name.substr(0, 1).toUpperCase()+name.substr(1); + if (callbackSymbol in self) { + self[callbackSymbol](); } -} - + }; + if ((this.state == S.HEADER_FIELD_START && this.index === 0) || + (this.state == S.PART_DATA && this.index == this.boundary.length)) { + callback(this, 'partEnd'); + callback(this, 'end'); + } else if (this.state != S.END) { + return new Error('MultipartParser.end(): stream ended unexpectedly: ' + this.explain()); + } +}; -/***/ }), +MultipartParser.prototype.explain = function() { + return 'state = ' + MultipartParser.stateToString(this.state); +}; -/***/ 19032: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -"use strict"; +/***/ }), +/***/ 48680: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// Some environments don't have global Buffer (e.g. React Native). -// Solution would be installing npm modules "buffer" and "stream" explicitly. -var Buffer = __nccwpck_require__(15118).Buffer; +var EventEmitter = __nccwpck_require__(28614).EventEmitter + , util = __nccwpck_require__(31669); -var bomHandling = __nccwpck_require__(67961), - iconv = module.exports; +function OctetParser(options){ + if(!(this instanceof OctetParser)) return new OctetParser(options); + EventEmitter.call(this); +} -// All codecs and aliases are kept here, keyed by encoding name/alias. -// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. -iconv.encodings = null; +util.inherits(OctetParser, EventEmitter); -// Characters emitted in case of error. -iconv.defaultCharUnicode = '�'; -iconv.defaultCharSingleByte = '?'; +exports.h = OctetParser; -// Public API. -iconv.encode = function encode(str, encoding, options) { - str = "" + (str || ""); // Ensure string. +OctetParser.prototype.write = function(buffer) { + this.emit('data', buffer); + return buffer.length; +}; - var encoder = iconv.getEncoder(encoding, options); +OctetParser.prototype.end = function() { + this.emit('end'); +}; - var res = encoder.write(str); - var trail = encoder.end(); - - return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; -} -iconv.decode = function decode(buf, encoding, options) { - if (typeof buf === 'string') { - if (!iconv.skipDecodeWarning) { - console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); - iconv.skipDecodeWarning = true; - } +/***/ }), - buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. - } +/***/ 80825: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - var decoder = iconv.getDecoder(encoding, options); +if (global.GENTLY) __nccwpck_require__(94120) = GENTLY.hijack(require); - var res = decoder.write(buf); - var trail = decoder.end(); +// This is a buffering parser, not quite as nice as the multipart one. +// If I find time I'll rewrite this to be fully streaming as well +var querystring = __nccwpck_require__(71191); - return trail ? (res + trail) : res; +function QuerystringParser(maxKeys) { + this.maxKeys = maxKeys; + this.buffer = ''; } +exports.l = QuerystringParser; -iconv.encodingExists = function encodingExists(enc) { - try { - iconv.getCodec(enc); - return true; - } catch (e) { - return false; - } -} +QuerystringParser.prototype.write = function(buffer) { + this.buffer += buffer.toString('ascii'); + return buffer.length; +}; -// Legacy aliases to convert functions -iconv.toEncoding = iconv.encode; -iconv.fromEncoding = iconv.decode; +QuerystringParser.prototype.end = function() { + var fields = querystring.parse(this.buffer, '&', '=', { maxKeys: this.maxKeys }); + for (var field in fields) { + this.onField(field, fields[field]); + } + this.buffer = ''; -// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. -iconv._codecDataCache = {}; -iconv.getCodec = function getCodec(encoding) { - if (!iconv.encodings) - iconv.encodings = __nccwpck_require__(82733); // Lazy load all encoding definitions. - - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - var enc = iconv._canonicalizeEncoding(encoding); + this.onEnd(); +}; - // Traverse iconv.encodings to find actual codec. - var codecOptions = {}; - while (true) { - var codec = iconv._codecDataCache[enc]; - if (codec) - return codec; - var codecDef = iconv.encodings[enc]; - switch (typeof codecDef) { - case "string": // Direct alias to other encoding. - enc = codecDef; - break; +/***/ }), - case "object": // Alias with options. Can be layered. - for (var key in codecDef) - codecOptions[key] = codecDef[key]; +/***/ 46868: +/***/ ((module) => { - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; - - enc = codecDef.type; - break; +"use strict"; +/*! + * forwarded + * Copyright(c) 2014-2017 Douglas Christopher Wilson + * MIT Licensed + */ - case "function": // Codec itself. - if (!codecOptions.encodingName) - codecOptions.encodingName = enc; - // The codec function must load all tables and return object with .encoder and .decoder methods. - // It'll be called only once (for each different options object). - codec = new codecDef(codecOptions, iconv); - iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. - return codec; +/** + * Module exports. + * @public + */ - default: - throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); - } - } -} +module.exports = forwarded -iconv._canonicalizeEncoding = function(encoding) { - // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. - return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); -} +/** + * Get all addresses in the request, using the `X-Forwarded-For` header. + * + * @param {object} req + * @return {array} + * @public + */ -iconv.getEncoder = function getEncoder(encoding, options) { - var codec = iconv.getCodec(encoding), - encoder = new codec.encoder(options, codec); +function forwarded (req) { + if (!req) { + throw new TypeError('argument req is required') + } - if (codec.bomAware && options && options.addBOM) - encoder = new bomHandling.PrependBOM(encoder, options); + // simple header parsing + var proxyAddrs = parse(req.headers['x-forwarded-for'] || '') + var socketAddr = getSocketAddr(req) + var addrs = [socketAddr].concat(proxyAddrs) - return encoder; + // return all addresses + return addrs } -iconv.getDecoder = function getDecoder(encoding, options) { - var codec = iconv.getCodec(encoding), - decoder = new codec.decoder(options, codec); - - if (codec.bomAware && !(options && options.stripBOM === false)) - decoder = new bomHandling.StripBOM(decoder, options); +/** + * Get the socket address for a request. + * + * @param {object} req + * @return {string} + * @private + */ - return decoder; +function getSocketAddr (req) { + return req.socket + ? req.socket.remoteAddress + : req.connection.remoteAddress } +/** + * Parse the X-Forwarded-For header. + * + * @param {string} header + * @private + */ -// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. -var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; -if (nodeVer) { +function parse (header) { + var end = header.length + var list = [] + var start = header.length - // Load streaming support in Node v0.10+ - var nodeVerArr = nodeVer.split(".").map(Number); - if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { - __nccwpck_require__(76409)(iconv); + // gather addresses, backwards + for (var i = header.length - 1; i >= 0; i--) { + switch (header.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + } + break + case 0x2c: /* , */ + if (start !== end) { + list.push(header.substring(start, end)) + } + start = end = i + break + default: + start = i + break } + } - // Load Node primitive extensions. - __nccwpck_require__(30393)(iconv); -} + // final address + if (start !== end) { + list.push(header.substring(start, end)) + } -if (false) {} + return list +} /***/ }), -/***/ 76409: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 83136: +/***/ ((module) => { "use strict"; +/*! + * fresh + * Copyright(c) 2012 TJ Holowaychuk + * Copyright(c) 2016-2017 Douglas Christopher Wilson + * MIT Licensed + */ -var Buffer = __nccwpck_require__(64293).Buffer, - Transform = __nccwpck_require__(92413).Transform; +/** + * RegExp to check for no-cache token in Cache-Control. + * @private + */ -// == Exports ================================================================== -module.exports = function(iconv) { - - // Additional Public API. - iconv.encodeStream = function encodeStream(encoding, options) { - return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); - } +var CACHE_CONTROL_NO_CACHE_REGEXP = /(?:^|,)\s*?no-cache\s*?(?:,|$)/ - iconv.decodeStream = function decodeStream(encoding, options) { - return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); - } +/** + * Module exports. + * @public + */ - iconv.supportsStreams = true; +module.exports = fresh +/** + * Check freshness of the response using request and response headers. + * + * @param {Object} reqHeaders + * @param {Object} resHeaders + * @return {Boolean} + * @public + */ - // Not published yet. - iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; - iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; - iconv._collect = IconvLiteDecoderStream.prototype.collect; -}; +function fresh (reqHeaders, resHeaders) { + // fields + var modifiedSince = reqHeaders['if-modified-since'] + var noneMatch = reqHeaders['if-none-match'] + // unconditional request + if (!modifiedSince && !noneMatch) { + return false + } -// == Encoder stream ======================================================= -function IconvLiteEncoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.decodeStrings = false; // We accept only strings, so we don't need to decode them. - Transform.call(this, options); -} + // Always return stale when Cache-Control: no-cache + // to support end-to-end reload requests + // https://tools.ietf.org/html/rfc2616#section-14.9.4 + var cacheControl = reqHeaders['cache-control'] + if (cacheControl && CACHE_CONTROL_NO_CACHE_REGEXP.test(cacheControl)) { + return false + } -IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteEncoderStream } -}); + // if-none-match + if (noneMatch && noneMatch !== '*') { + var etag = resHeaders['etag'] -IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { - if (typeof chunk != 'string') - return done(new Error("Iconv encoding stream needs strings as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res); - done(); + if (!etag) { + return false } - catch (e) { - done(e); + + var etagStale = true + var matches = parseTokenList(noneMatch) + for (var i = 0; i < matches.length; i++) { + var match = matches[i] + if (match === etag || match === 'W/' + etag || 'W/' + match === etag) { + etagStale = false + break + } } -} -IconvLiteEncoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res); - done(); + if (etagStale) { + return false } - catch (e) { - done(e); + } + + // if-modified-since + if (modifiedSince) { + var lastModified = resHeaders['last-modified'] + var modifiedStale = !lastModified || !(parseHttpDate(lastModified) <= parseHttpDate(modifiedSince)) + + if (modifiedStale) { + return false } -} + } -IconvLiteEncoderStream.prototype.collect = function(cb) { - var chunks = []; - this.on('error', cb); - this.on('data', function(chunk) { chunks.push(chunk); }); - this.on('end', function() { - cb(null, Buffer.concat(chunks)); - }); - return this; + return true } +/** + * Parse an HTTP Date into a number. + * + * @param {string} date + * @private + */ + +function parseHttpDate (date) { + var timestamp = date && Date.parse(date) -// == Decoder stream ======================================================= -function IconvLiteDecoderStream(conv, options) { - this.conv = conv; - options = options || {}; - options.encoding = this.encoding = 'utf8'; // We output strings. - Transform.call(this, options); + // istanbul ignore next: guard against date.js Date.parse patching + return typeof timestamp === 'number' + ? timestamp + : NaN } -IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { - constructor: { value: IconvLiteDecoderStream } -}); +/** + * Parse a HTTP token list. + * + * @param {string} str + * @private + */ -IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { - if (!Buffer.isBuffer(chunk)) - return done(new Error("Iconv decoding stream needs buffers as its input.")); - try { - var res = this.conv.write(chunk); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); - } -} +function parseTokenList (str) { + var end = 0 + var list = [] + var start = 0 -IconvLiteDecoderStream.prototype._flush = function(done) { - try { - var res = this.conv.end(); - if (res && res.length) this.push(res, this.encoding); - done(); - } - catch (e) { - done(e); + // gather tokens + for (var i = 0, len = str.length; i < len; i++) { + switch (str.charCodeAt(i)) { + case 0x20: /* */ + if (start === end) { + start = end = i + 1 + } + break + case 0x2c: /* , */ + list.push(str.substring(start, end)) + start = end = i + 1 + break + default: + end = i + 1 + break } -} + } -IconvLiteDecoderStream.prototype.collect = function(cb) { - var res = ''; - this.on('error', cb); - this.on('data', function(chunk) { res += chunk; }); - this.on('end', function() { - cb(null, res); - }); - return this; -} + // final token + list.push(str.substring(start, end)) + return list +} /***/ }), -/***/ 91230: +/***/ 19320: /***/ ((module) => { -// A simple implementation of make-array -function makeArray (subject) { - return Array.isArray(subject) - ? subject - : [subject] -} +"use strict"; -const EMPTY = '' -const SPACE = ' ' -const ESCAPE = '\\' -const REGEX_TEST_BLANK_LINE = /^\s+$/ -const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/ -const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/ -const REGEX_SPLITALL_CRLF = /\r?\n/g -// /foo, -// ./foo, -// ../foo, -// . -// .. -const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/ -const SLASH = '/' -const KEY_IGNORE = typeof Symbol !== 'undefined' - ? Symbol.for('node-ignore') - /* istanbul ignore next */ - : 'node-ignore' +/* eslint no-invalid-this: 1 */ -const define = (object, key, value) => - Object.defineProperty(object, key, {value}) +var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; +var slice = Array.prototype.slice; +var toStr = Object.prototype.toString; +var funcType = '[object Function]'; -const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g +module.exports = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.call(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slice.call(arguments, 1); -// Sanitize the range of a regular expression -// The cases are complicated, see test cases for details -const sanitizeRange = range => range.replace( - REGEX_REGEXP_RANGE, - (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) - ? match - // Invalid range (out of order) which is ok for gitignore rules but - // fatal for JavaScript regular expression, so eliminate it. - : EMPTY -) + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + args.concat(slice.call(arguments)) + ); + if (Object(result) === result) { + return result; + } + return this; + } else { + return target.apply( + that, + args.concat(slice.call(arguments)) + ); + } + }; -// See fixtures #59 -const cleanRangeBackSlash = slashes => { - const {length} = slashes - return slashes.slice(0, length - length % 2) -} + var boundLength = Math.max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs.push('$' + i); + } -// > If the pattern ends with a slash, -// > it is removed for the purpose of the following description, -// > but it would only find a match with a directory. -// > In other words, foo/ will match a directory foo and paths underneath it, -// > but will not match a regular file or a symbolic link foo -// > (this is consistent with the way how pathspec works in general in Git). -// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' -// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call -// you could use option `mark: true` with `glob` + bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder); -// '`foo/`' should not continue with the '`..`' -const REPLACERS = [ + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } - // > Trailing spaces are ignored unless they are quoted with backslash ("\") - [ - // (a\ ) -> (a ) - // (a ) -> (a) - // (a \ ) -> (a ) - /\\?\s+$/, - match => match.indexOf('\\') === 0 - ? SPACE - : EMPTY - ], + return bound; +}; - // replace (\ ) with ' ' - [ - /\\\s/g, - () => SPACE - ], - // Escape metacharacters - // which is written down by users but means special for regular expressions. +/***/ }), - // > There are 12 characters with special meanings: - // > - the backslash \, - // > - the caret ^, - // > - the dollar sign $, - // > - the period or dot ., - // > - the vertical bar or pipe symbol |, - // > - the question mark ?, - // > - the asterisk or star *, - // > - the plus sign +, - // > - the opening parenthesis (, - // > - the closing parenthesis ), - // > - and the opening square bracket [, - // > - the opening curly brace {, - // > These special characters are often called "metacharacters". - [ - /[\\$.|*+(){^]/g, - match => `\\${match}` - ], +/***/ 88334: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - [ - // > a question mark (?) matches a single character - /(?!\\)\?/g, - () => '[^/]' - ], +"use strict"; - // leading slash - [ - // > A leading slash matches the beginning of the pathname. - // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". - // A leading slash matches the beginning of the pathname - /^\//, - () => '^' - ], +var implementation = __nccwpck_require__(19320); - // replace special metacharacter slash after the leading slash - [ - /\//g, - () => '\\/' - ], +module.exports = Function.prototype.bind || implementation; - [ - // > A leading "**" followed by a slash means match in all directories. - // > For example, "**/foo" matches file or directory "foo" anywhere, - // > the same as pattern "foo". - // > "**/foo/bar" matches file or directory "bar" anywhere that is directly - // > under directory "foo". - // Notice that the '*'s have been replaced as '\\*' - /^\^*\\\*\\\*\\\//, - // '**/foo' <-> 'foo' - () => '^(?:.*\\/)?' - ], +/***/ }), - // starting - [ - // there will be no leading '/' - // (which has been replaced by section "leading slash") - // If starts with '**', adding a '^' to the regular expression also works - /^(?=[^^])/, - function startingReplacer () { - // If has a slash `/` at the beginning or middle - return !/\/(?!$)/.test(this) - // > Prior to 2.22.1 - // > If the pattern does not contain a slash /, - // > Git treats it as a shell glob pattern - // Actually, if there is only a trailing slash, - // git also treats it as a shell glob pattern +/***/ 74538: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // After 2.22.1 (compatible but clearer) - // > If there is a separator at the beginning or middle (or both) - // > of the pattern, then the pattern is relative to the directory - // > level of the particular .gitignore file itself. - // > Otherwise the pattern may also match at any level below - // > the .gitignore level. - ? '(?:^|\\/)' +"use strict"; - // > Otherwise, Git treats the pattern as a shell glob suitable for - // > consumption by fnmatch(3) - : '^' - } - ], - // two globstars - [ - // Use lookahead assertions so that we could match more than one `'/**'` - /\\\/\\\*\\\*(?=\\\/|$)/g, +var undefined; - // Zero, one or several directories - // should not use '*', or it will be replaced by the next replacer +var $SyntaxError = SyntaxError; +var $Function = Function; +var $TypeError = TypeError; - // Check if it is not the last `'/**'` - (_, index, str) => index + 6 < str.length +// eslint-disable-next-line consistent-return +var getEvalledConstructor = function (expressionSyntax) { + try { + return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')(); + } catch (e) {} +}; - // case: /**/ - // > A slash followed by two consecutive asterisks then a slash matches - // > zero or more directories. - // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. - // '/**/' - ? '(?:\\/[^\\/]+)*' +var $gOPD = Object.getOwnPropertyDescriptor; +if ($gOPD) { + try { + $gOPD({}, ''); + } catch (e) { + $gOPD = null; // this is IE 8, which has a broken gOPD + } +} - // case: /** - // > A trailing `"/**"` matches everything inside. +var throwTypeError = function () { + throw new $TypeError(); +}; +var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + +var hasSymbols = __nccwpck_require__(40587)(); + +var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto + +var needsEval = {}; + +var TypedArray = typeof Uint8Array === 'undefined' ? undefined : getProto(Uint8Array); + +var INTRINSICS = { + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols ? getProto([][Symbol.iterator]()) : undefined, + '%AsyncFromSyncIteratorPrototype%': undefined, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined : BigInt, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': EvalError, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined : FinalizationRegistry, + '%Function%': $Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols ? getProto(getProto([][Symbol.iterator]())) : undefined, + '%JSON%': typeof JSON === 'object' ? JSON : undefined, + '%Map%': typeof Map === 'undefined' ? undefined : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols ? undefined : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': Object, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined : Proxy, + '%RangeError%': RangeError, + '%ReferenceError%': ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols ? undefined : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols ? getProto(''[Symbol.iterator]()) : undefined, + '%Symbol%': hasSymbols ? Symbol : undefined, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined : Uint32Array, + '%URIError%': URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined : WeakSet +}; + +var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getEvalledConstructor('async function () {}'); + } else if (name === '%GeneratorFunction%') { + value = getEvalledConstructor('function* () {}'); + } else if (name === '%AsyncGeneratorFunction%') { + value = getEvalledConstructor('async function* () {}'); + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen) { + value = getProto(gen.prototype); + } + } - // #21: everything inside but it should not include the current folder - : '\\/.+' - ], + INTRINSICS[name] = value; + + return value; +}; + +var LEGACY_ALIASES = { + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] +}; - // intermediate wildcards - [ - // Never replace escaped '*' - // ignore rule '\*' will match the path '*' +var bind = __nccwpck_require__(88334); +var hasOwn = __nccwpck_require__(76339); +var $concat = bind.call(Function.call, Array.prototype.concat); +var $spliceApply = bind.call(Function.apply, Array.prototype.splice); +var $replace = bind.call(Function.call, String.prototype.replace); +var $strSlice = bind.call(Function.call, String.prototype.slice); + +/* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ +var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; +var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ +var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; +}; +/* end adaptation */ - // 'abc.*/' -> go - // 'abc.*' -> skip this rule - /(^|[^\\]+)\\\*(?=.+)/g, +var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } - // '*.js' matches '.js' - // '*.js' doesn't match 'abc' - (_, p1) => `${p1}[^\\/]*` - ], + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } - [ - // unescape, revert step 3 except for back slash - // For example, if a user escape a '\\*', - // after step 3, the result will be '\\\\\\*' - /\\\\\\(?=[$.|*+(){^])/g, - () => ESCAPE - ], + return { + alias: alias, + name: intrinsicName, + value: value + }; + } - [ - // '\\\\' -> '\\' - /\\\\/g, - () => ESCAPE - ], + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); +}; - [ - // > The range notation, e.g. [a-zA-Z], - // > can be used to match one of the characters in a range. +module.exports = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } - // `\` is escaped by step 3 - /(\\)?\[([^\]/]*?)(\\*)($|\])/g, - (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE - // '\\[bar]' -> '\\\\[bar\\]' - ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` - : close === ']' - ? endEscape.length % 2 === 0 - // A normal case, and it is a range notation - // '[bar]' - // '[bar\\\\]' - ? `[${sanitizeRange(range)}${endEscape}]` - // Invalid range notaton - // '[bar\\]' -> '[bar\\\\]' - : '[]' - : '[]' - ], + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; - // ending - [ - // 'js' will not match 'js.' - // 'ab' will not match 'abc' - /(?:[^*])$/, + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; - // WTF! - // https://git-scm.com/docs/gitignore - // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) - // which re-fixes #24, #38 + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } - // > If there is a separator at the end of the pattern then the pattern - // > will only match directories, otherwise the pattern can match both - // > files and directories. + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } - // 'js*' will not match 'a.js' - // 'js/' will not match 'a.js' - // 'js' will match 'a.js' and 'a.js/' - match => /\/$/.test(match) - // foo/ will not match 'foo' - ? `${match}$` - // foo matches 'foo' and 'foo/' - : `${match}(?=$|\\/$)` - ], + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; - // trailing wildcard - [ - /(\^|\\\/)?\\\*$/, - (_, p1) => { - const prefix = p1 - // '\^': - // '/*' does not match EMPTY - // '/*' does not match everything + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } - // '\\\/': - // 'abc/*' does not match 'abc/' - ? `${p1}[^/]+` + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; +}; - // 'a*' matches 'a' - // 'a*' matches 'aa' - : '[^/]*' - return `${prefix}(?=$|\\/$)` - } - ], -] +/***/ }), -// A simple cache, because an ignore rule only has only one certain meaning -const regexCache = Object.create(null) +/***/ 67356: +/***/ ((module) => { -// @param {pattern} -const makeRegex = (pattern, negative, ignorecase) => { - const r = regexCache[pattern] - if (r) { - return r - } +"use strict"; - // const replacers = negative - // ? NEGATIVE_REPLACERS - // : POSITIVE_REPLACERS - const source = REPLACERS.reduce( - (prev, current) => prev.replace(current[0], current[1].bind(pattern)), - pattern - ) +module.exports = clone - return regexCache[pattern] = ignorecase - ? new RegExp(source, 'i') - : new RegExp(source) +var getPrototypeOf = Object.getPrototypeOf || function (obj) { + return obj.__proto__ } -const isString = subject => typeof subject === 'string' +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj -// > A blank line matches no files, so it can serve as a separator for readability. -const checkPattern = pattern => pattern - && isString(pattern) - && !REGEX_TEST_BLANK_LINE.test(pattern) + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) } + else + var copy = Object.create(null) - // > A line starting with # serves as a comment. - && pattern.indexOf('#') !== 0 + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) -const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF) + return copy +} -class IgnoreRule { - constructor ( - origin, - pattern, - negative, - regex - ) { - this.origin = origin - this.pattern = pattern - this.negative = negative - this.regex = regex + +/***/ }), + +/***/ 77758: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var fs = __nccwpck_require__(35747) +var polyfills = __nccwpck_require__(20263) +var legacy = __nccwpck_require__(73086) +var clone = __nccwpck_require__(67356) + +var util = __nccwpck_require__(31669) + +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol + +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' +} + +function noop () {} + +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue + } + }) +} + +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) } -} -const createRule = (pattern, ignorecase) => { - const origin = pattern - let negative = false +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) + + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + resetQueue() + } - // > An optional prefix "!" which negates the pattern; - if (pattern.indexOf('!') === 0) { - negative = true - pattern = pattern.substr(1) - } + if (typeof cb === 'function') + cb.apply(this, arguments) + }) + } - pattern = pattern - // > Put a backslash ("\") in front of the first "!" for patterns that - // > begin with a literal "!", for example, `"\!important!.txt"`. - .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') - // > Put a backslash ("\") in front of the first hash for patterns that - // > begin with a hash. - .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#') + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) - const regex = makeRegex(pattern, negative, ignorecase) + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + resetQueue() + } - return new IgnoreRule( - origin, - pattern, - negative, - regex - ) + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) + + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + __nccwpck_require__(42357).equal(fs[gracefulQueue].length, 0) + }) + } } -const throwError = (message, Ctor) => { - throw new Ctor(message) +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); } -const checkPath = (path, originalPath, doThrow) => { - if (!isString(path)) { - return doThrow( - `path must be a string, but got \`${originalPath}\``, - TypeError - ) - } +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} - // We don't know if we should ignore EMPTY, so throw - if (!path) { - return doThrow(`path must not be empty`, TypeError) - } +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch - // Check if it is a relative path - if (checkPath.isNotRelative(path)) { - const r = '`path.relative()`d' - return doThrow( - `path should be a ${r} string, but got "${originalPath}"`, - RangeError - ) - } + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - return true -} + return go$readFile(path, options, cb) -const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) + function go$readFile (path, options, cb, startTime) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } -checkPath.isNotRelative = isNotRelative -checkPath.convert = p => p + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null -class Ignore { - constructor ({ - ignorecase = true - } = {}) { - this._rules = [] - this._ignorecase = ignorecase - define(this, KEY_IGNORE, true) - this._initCache() + return go$writeFile(path, data, options, cb) + + function go$writeFile (path, data, options, cb, startTime) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } } - _initCache () { - this._ignoreCache = Object.create(null) - this._testCache = Object.create(null) + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$appendFile(path, data, options, cb) + + function go$appendFile (path, data, options, cb, startTime) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } } - _addPattern (pattern) { - // #32 - if (pattern && pattern[KEY_IGNORE]) { - this._rules = this._rules.concat(pattern._rules) - this._added = true - return + var fs$copyFile = fs.copyFile + if (fs$copyFile) + fs.copyFile = copyFile + function copyFile (src, dest, flags, cb) { + if (typeof flags === 'function') { + cb = flags + flags = 0 } + return go$copyFile(src, dest, flags, cb) - if (checkPattern(pattern)) { - const rule = createRule(pattern, this._ignorecase) - this._added = true - this._rules.push(rule) + function go$copyFile (src, dest, flags, cb, startTime) { + return fs$copyFile(src, dest, flags, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) } } - // @param {Array | string | Ignore} pattern - add (pattern) { - this._added = false + var fs$readdir = fs.readdir + fs.readdir = readdir + function readdir (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null - makeArray( - isString(pattern) - ? splitPattern(pattern) - : pattern - ).forEach(this._addPattern, this) + return go$readdir(path, options, cb) - // Some rules have just added to the ignore, - // making the behavior changed. - if (this._added) { - this._initCache() + function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, options, function (err, files) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readdir, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (files && files.sort) + files.sort() + + if (typeof cb === 'function') + cb.call(this, err, files) + } + }) } + } - return this + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream } - // legacy - addPattern (pattern) { - return this.add(pattern) + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open } - // | ignored : unignored - // negative | 0:0 | 0:1 | 1:0 | 1:1 - // -------- | ------- | ------- | ------- | -------- - // 0 | TEST | TEST | SKIP | X - // 1 | TESTIF | SKIP | TEST | X + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } - // - SKIP: always skip - // - TEST: always test - // - TESTIF: only test if checkUnignored - // - X: that never happen + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) - // @param {boolean} whether should check if the path is unignored, - // setting `checkUnignored` to `false` could reduce additional - // path matching. + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) - // @returns {TestResult} true if a file is ignored - _testOne (path, checkUnignored) { - let ignored = false - let unignored = false + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } - this._rules.forEach(rule => { - const {negative} = rule - if ( - unignored === negative && ignored !== unignored - || negative && !ignored && !unignored && !checkUnignored - ) { - return + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() + + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() } + }) + } - const matched = rule.regex.test(path) + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } - if (matched) { - ignored = !negative - unignored = negative + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) } }) + } - return { - ignored, - unignored - } + function createReadStream (path, options) { + return new fs.ReadStream(path, options) } - // @returns {TestResult} - _test (originalPath, cache, checkUnignored, slices) { - const path = originalPath - // Supports nullable path - && checkPath.convert(originalPath) + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } - checkPath(path, originalPath, throwError) + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null - return this._t(path, cache, checkUnignored, slices) - } + return go$open(path, flags, mode, cb) - _t (path, cache, checkUnignored, slices) { - if (path in cache) { - return cache[path] + function go$open (path, flags, mode, cb, startTime) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) } + } - if (!slices) { - // path/to/a.js - // ['path', 'to', 'a.js'] - slices = path.split(SLASH) - } + return fs +} - slices.pop() +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) + retry() +} - // If the path has no parent directory, just test it - if (!slices.length) { - return cache[path] = this._testOne(path, checkUnignored) +// keep track of the timeout between retry() calls +var retryTimer + +// reset the startTime and lastTime to now +// this resets the start of the 60 second overall timeout as well as the +// delay between attempts so that we'll retry these jobs sooner +function resetQueue () { + var now = Date.now() + for (var i = 0; i < fs[gracefulQueue].length; ++i) { + // entries that are only a length of 2 are from an older version, don't + // bother modifying those since they'll be retried anyway. + if (fs[gracefulQueue][i].length > 2) { + fs[gracefulQueue][i][3] = now // startTime + fs[gracefulQueue][i][4] = now // lastTime } + } + // call retry to make sure we're actively processing the queue + retry() +} - const parent = this._t( - slices.join(SLASH) + SLASH, - cache, - checkUnignored, - slices - ) +function retry () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer) + retryTimer = undefined - // If the path contains a parent directory, check the parent first - return cache[path] = parent.ignored - // > It is not possible to re-include a file if a parent directory of - // > that file is excluded. - ? parent - : this._testOne(path, checkUnignored) - } + if (fs[gracefulQueue].length === 0) + return - ignores (path) { - return this._test(path, this._ignoreCache, false).ignored + var elem = fs[gracefulQueue].shift() + var fn = elem[0] + var args = elem[1] + // these items may be unset if they were added by an older graceful-fs + var err = elem[2] + var startTime = elem[3] + var lastTime = elem[4] + + // if we don't have a startTime we have no way of knowing if we've waited + // long enough, so go ahead and retry this item now + if (startTime === undefined) { + debug('RETRY', fn.name, args) + fn.apply(null, args) + } else if (Date.now() - startTime >= 60000) { + // it's been more than 60 seconds total, bail now + debug('TIMEOUT', fn.name, args) + var cb = args.pop() + if (typeof cb === 'function') + cb.call(null, err) + } else { + // the amount of time between the last attempt and right now + var sinceAttempt = Date.now() - lastTime + // the amount of time between when we first tried, and when we last tried + // rounded up to at least 1 + var sinceStart = Math.max(lastTime - startTime, 1) + // backoff. wait longer than the total time we've been retrying, but only + // up to a maximum of 100ms + var desiredDelay = Math.min(sinceStart * 1.2, 100) + // it's been long enough since the last retry, do it again + if (sinceAttempt >= desiredDelay) { + debug('RETRY', fn.name, args) + fn.apply(null, args.concat([startTime])) + } else { + // if we can't do this job yet, push it to the end of the queue + // and let the next iteration check again + fs[gracefulQueue].push(elem) + } } - createFilter () { - return path => !this.ignores(path) + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0) } +} - filter (paths) { - return makeArray(paths).filter(this.createFilter()) - } - // @returns {TestResult} - test (path) { - return this._test(path, this._testCache, true) +/***/ }), + +/***/ 73086: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var Stream = __nccwpck_require__(92413).Stream + +module.exports = legacy + +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream } -} -const factory = options => new Ignore(options) + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); -const returnFalse = () => false + Stream.call(this); -const isPathValid = path => - checkPath(path && checkPath.convert(path), path, returnFalse) + var self = this; -factory.isPathValid = isPathValid + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; -// Fixes typescript -factory.default = factory + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; -module.exports = factory + options = options || {}; -// Windows -// -------------------------------------------------------------- -/* istanbul ignore if */ -if ( - // Detect `process` so that it can run in browsers. - typeof process !== 'undefined' - && ( - process.env && process.env.IGNORE_TEST_WIN32 - || process.platform === 'win32' - ) -) { - /* eslint no-control-regex: "off" */ - const makePosix = str => /^\\\\\?\\/.test(str) - || /["<>|\u0000-\u001F]+/u.test(str) - ? str - : str.replace(/\\/g, '/') + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } - checkPath.convert = makePosix + if (this.encoding) this.setEncoding(this.encoding); - // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' - // 'd:\\foo' - const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i - checkPath.isNotRelative = path => - REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) - || isNotRelative(path) -} + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } + if (this.start > this.end) { + throw new Error('start must be <= end'); + } -/***/ }), + this.pos = this.start; + } -/***/ 98043: -/***/ ((module) => { + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } -"use strict"; + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } -module.exports = (string, count = 1, options) => { - options = { - indent: ' ', - includeEmptyLines: false, - ...options - }; + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); - if (typeof string !== 'string') { - throw new TypeError( - `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` - ); - } + Stream.call(this); - if (typeof count !== 'number') { - throw new TypeError( - `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` - ); - } + this.path = path; + this.fd = null; + this.writable = true; - if (typeof options.indent !== 'string') { - throw new TypeError( - `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` - ); - } + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } - if (count === 0) { - return string; - } + this.pos = this.start; + } - const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; + this.busy = false; + this._queue = []; - return string.replace(regex, options.indent.repeat(count)); -}; + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } +} /***/ }), -/***/ 44124: +/***/ 20263: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var constants = __nccwpck_require__(27619) + +var origCwd = process.cwd +var cwd = null + +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform + +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} try { - var util = __nccwpck_require__(31669); - if (typeof util.inherits !== 'function') throw ''; - module.exports = util.inherits; -} catch (e) { - module.exports = __nccwpck_require__(8544); + process.cwd() +} catch (er) {} + +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir = process.chdir + process.chdir = function (d) { + cwd = null + chdir.call(process, d) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) } +module.exports = patch -/***/ }), +function patch (fs) { + // (re-)implement some things that are known busted or missing. -/***/ 8544: -/***/ ((module) => { + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) } -} + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. -/***/ }), + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) -/***/ 30545: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) -"use strict"; + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) -Object.defineProperty(exports, "__esModule", ({ value: true })); -const command_1 = __nccwpck_require__(90803); -const utils_1 = __nccwpck_require__(94832); -const RedisParser = __nccwpck_require__(53315); -const SubscriptionSet_1 = __nccwpck_require__(73527); -const debug = utils_1.Debug("dataHandler"); -class DataHandler { - constructor(redis, parserOptions) { - this.redis = redis; - const parser = new RedisParser({ - stringNumbers: parserOptions.stringNumbers, - returnBuffers: !parserOptions.dropBufferSupport, - returnError: (err) => { - this.returnError(err); - }, - returnFatalError: (err) => { - this.returnFatalError(err); - }, - returnReply: (reply) => { - this.returnReply(reply); - }, - }); - redis.stream.on("data", (data) => { - parser.execute(data); - }); - } - returnFatalError(err) { - err.message += ". Please report this."; - this.redis.recoverFromFatalError(err, err, { offlineQueue: false }); + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) + + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) + + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) + + // if lchmod/lchown do not exist, then make them no-ops + if (!fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) } - returnError(err) { - const item = this.shiftCommand(err); - if (!item) { - return; - } - err.command = { - name: item.command.name, - args: item.command.args, - }; - this.redis.handleReconnection(err, item); + fs.lchmodSync = function () {} + } + if (!fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) } - returnReply(reply) { - if (this.handleMonitorReply(reply)) { - return; - } - if (this.handleSubscriberReply(reply)) { - return; - } - const item = this.shiftCommand(reply); - if (!item) { - return; - } - if (command_1.default.checkFlag("ENTER_SUBSCRIBER_MODE", item.command.name)) { - this.redis.condition.subscriber = new SubscriptionSet_1.default(); - this.redis.condition.subscriber.add(item.command.name, reply[1].toString()); - if (!fillSubCommand(item.command, reply[2])) { - this.redis.commandQueue.unshift(item); - } - } - else if (command_1.default.checkFlag("EXIT_SUBSCRIBER_MODE", item.command.name)) { - if (!fillUnsubCommand(item.command, reply[2])) { - this.redis.commandQueue.unshift(item); - } + fs.lchownSync = function () {} + } + + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. + + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = (function (fs$rename) { return function (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; } - else { - item.command.resolve(reply); + if (cb) cb(er) + }) + }})(fs.rename) + } + + // if read() returns EAGAIN, then just try it again. + fs.read = (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) } - handleSubscriberReply(reply) { - if (!this.redis.condition.subscriber) { - return false; - } - const replyType = Array.isArray(reply) ? reply[0].toString() : null; - debug('receive reply "%s" in subscriber mode', replyType); - switch (replyType) { - case "message": - if (this.redis.listeners("message").length > 0) { - // Check if there're listeners to avoid unnecessary `toString()`. - this.redis.emit("message", reply[1].toString(), reply[2].toString()); - } - this.redis.emit("messageBuffer", reply[1], reply[2]); - break; - case "pmessage": { - const pattern = reply[1].toString(); - if (this.redis.listeners("pmessage").length > 0) { - this.redis.emit("pmessage", pattern, reply[2].toString(), reply[3].toString()); - } - this.redis.emit("pmessageBuffer", pattern, reply[2], reply[3]); - break; - } - case "subscribe": - case "psubscribe": { - const channel = reply[1].toString(); - this.redis.condition.subscriber.add(replyType, channel); - const item = this.shiftCommand(reply); - if (!item) { - return; - } - if (!fillSubCommand(item.command, reply[2])) { - this.redis.commandQueue.unshift(item); - } - break; - } - case "unsubscribe": - case "punsubscribe": { - const channel = reply[1] ? reply[1].toString() : null; - if (channel) { - this.redis.condition.subscriber.del(replyType, channel); - } - const count = reply[2]; - if (count === 0) { - this.redis.condition.subscriber = false; - } - const item = this.shiftCommand(reply); - if (!item) { - return; - } - if (!fillUnsubCommand(item.command, count)) { - this.redis.commandQueue.unshift(item); - } - break; - } - default: { - const item = this.shiftCommand(reply); - if (!item) { - return; - } - item.command.resolve(reply); - } + + // This ensures `util.promisify` works as it does for native `fs.read`. + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) + return read + })(fs.read) + + fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue } - return true; + throw er + } } - handleMonitorReply(reply) { - if (this.redis.status !== "monitoring") { - return false; + }})(fs.readSync) + + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return } - const replyStr = reply.toString(); - if (replyStr === "OK") { - // Valid commands in the monitoring mode are AUTH and MONITOR, - // both of which always reply with 'OK'. - // So if we got an 'OK', we can make certain that - // the reply is made to AUTH & MONITO. - return false; + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } + + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) } - // Since commands sent in the monitoring mode will trigger an exception, - // any replies we received in the monitoring mode should consider to be - // realtime monitor data instead of result of commands. - const len = replyStr.indexOf(" "); - const timestamp = replyStr.slice(0, len); - const argindex = replyStr.indexOf('"'); - const args = replyStr - .slice(argindex + 1, -1) - .split('" "') - .map((elem) => elem.replace(/\\"/g, '"')); - const dbAndSource = replyStr.slice(len + 2, argindex - 2).split(" "); - this.redis.emit("monitor", timestamp, args, dbAndSource[1], dbAndSource[0]); - return true; + } + return ret } - shiftCommand(reply) { - const item = this.redis.commandQueue.shift(); - if (!item) { - const message = "Command queue state error. If you can reproduce this, please report it."; - const error = new Error(message + - (reply instanceof Error - ? ` Last error: ${reply.message}` - : ` Last reply: ${reply.toString()}`)); - this.redis.emit("error", error); - return null; + } + + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK")) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } + + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } } - return item; + return ret + } + + } else { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} } -} -exports.default = DataHandler; -function fillSubCommand(command, count) { - // TODO: use WeakMap here - if (typeof command.remainReplies === "undefined") { - command.remainReplies = command.args.length; + } + + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) } - if (--command.remainReplies === 0) { - command.resolve(count); - return true; + } + + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } } - return false; -} -function fillUnsubCommand(command, count) { - if (typeof command.remainReplies === "undefined") { - command.remainReplies = command.args.length; + } + + + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) } - if (command.remainReplies === 0) { - if (count === 0) { - command.resolve(count); - return true; + } + + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 } - return false; + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) } - if (--command.remainReplies === 0) { - command.resolve(count); - return true; + } + + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + return stats; } - return false; + } + + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true + + if (er.code === "ENOSYS") + return true + + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } + + return false + } } /***/ }), -/***/ 6134: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 31621: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const stream_1 = __nccwpck_require__(92413); -/** - * Convenient class to convert the process of scaning keys to a readable stream. - * - * @export - * @class ScanStream - * @extends {Readable} - */ -class ScanStream extends stream_1.Readable { - constructor(opt) { - super(opt); - this.opt = opt; - this._redisCursor = "0"; - this._redisDrained = false; - } - _read() { - if (this._redisDrained) { - this.push(null); - return; - } - const args = [this._redisCursor]; - if (this.opt.key) { - args.unshift(this.opt.key); - } - if (this.opt.match) { - args.push("MATCH", this.opt.match); - } - if (this.opt.count) { - args.push("COUNT", String(this.opt.count)); - } - this.opt.redis[this.opt.command](args, (err, res) => { - if (err) { - this.emit("error", err); - return; - } - this._redisCursor = res[0] instanceof Buffer ? res[0].toString() : res[0]; - if (this._redisCursor === "0") { - this._redisDrained = true; - } - this.push(res[1]); - }); - } - close() { - this._redisDrained = true; - } -} -exports.default = ScanStream; +module.exports = (flag, argv) => { + argv = argv || process.argv; + const prefix = flag.startsWith('-') ? '' : (flag.length === 1 ? '-' : '--'); + const pos = argv.indexOf(prefix + flag); + const terminatorPos = argv.indexOf('--'); + return pos !== -1 && (terminatorPos === -1 ? true : pos < terminatorPos); +}; /***/ }), -/***/ 73527: -/***/ ((__unused_webpack_module, exports) => { +/***/ 40587: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -/** - * Tiny class to simplify dealing with subscription set - * - * @export - * @class SubscriptionSet - */ -class SubscriptionSet { - constructor() { - this.set = { - subscribe: {}, - psubscribe: {}, - }; - } - add(set, channel) { - this.set[mapSet(set)][channel] = true; - } - del(set, channel) { - delete this.set[mapSet(set)][channel]; - } - channels(set) { - return Object.keys(this.set[mapSet(set)]); - } - isEmpty() { - return (this.channels("subscribe").length === 0 && - this.channels("psubscribe").length === 0); - } -} -exports.default = SubscriptionSet; -function mapSet(set) { - if (set === "unsubscribe") { - return "subscribe"; - } - if (set === "punsubscribe") { - return "psubscribe"; - } - return set; -} + +var origSymbol = typeof Symbol !== 'undefined' && Symbol; +var hasSymbolSham = __nccwpck_require__(57747); + +module.exports = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); +}; /***/ }), -/***/ 97873: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 57747: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const PromiseContainer = __nccwpck_require__(71475); -const calculateSlot = __nccwpck_require__(48481); -const standard_as_callback_1 = __nccwpck_require__(91543); -exports.kExec = Symbol("exec"); -exports.kCallbacks = Symbol("callbacks"); -exports.notAllowedAutoPipelineCommands = [ - "auth", - "info", - "script", - "quit", - "cluster", - "pipeline", - "multi", - "subscribe", - "psubscribe", - "unsubscribe", - "unpsubscribe", -]; -function findAutoPipeline(client, _commandName, ...args) { - if (!client.isCluster) { - return "main"; - } - // We have slot information, we can improve routing by grouping slots served by the same subset of nodes - return client.slots[calculateSlot(args[0])].join(","); -} -function executeAutoPipeline(client, slotKey) { - /* - If a pipeline is already executing, keep queueing up commands - since ioredis won't serve two pipelines at the same time - */ - if (client._runningAutoPipelines.has(slotKey)) { - return; - } - client._runningAutoPipelines.add(slotKey); - // Get the pipeline and immediately delete it so that new commands are queued on a new pipeline - const pipeline = client._autoPipelines.get(slotKey); - client._autoPipelines.delete(slotKey); - const callbacks = pipeline[exports.kCallbacks]; - // Perform the call - pipeline.exec(function (err, results) { - client._runningAutoPipelines.delete(slotKey); - /* - Invoke all callback in nextTick so the stack is cleared - and callbacks can throw errors without affecting other callbacks. - */ - if (err) { - for (let i = 0; i < callbacks.length; i++) { - process.nextTick(callbacks[i], err); - } - } - else { - for (let i = 0; i < callbacks.length; i++) { - process.nextTick(callbacks[i], ...results[i]); - } - } - // If there is another pipeline on the same node, immediately execute it without waiting for nextTick - if (client._autoPipelines.has(slotKey)) { - executeAutoPipeline(client, slotKey); - } - }); -} -function shouldUseAutoPipelining(client, commandName) { - return (client.options.enableAutoPipelining && - !client.isPipeline && - !exports.notAllowedAutoPipelineCommands.includes(commandName) && - !client.options.autoPipeliningIgnoredCommands.includes(commandName)); -} -exports.shouldUseAutoPipelining = shouldUseAutoPipelining; -function executeWithAutoPipelining(client, commandName, args, callback) { - const CustomPromise = PromiseContainer.get(); - // On cluster mode let's wait for slots to be available - if (client.isCluster && !client.slots.length) { - return new CustomPromise(function (resolve, reject) { - client.delayUntilReady((err) => { - if (err) { - reject(err); - return; - } - executeWithAutoPipelining(client, commandName, args, callback).then(resolve, reject); - }); - }); - } - const slotKey = findAutoPipeline(client, commandName, ...args); - if (!client._autoPipelines.has(slotKey)) { - const pipeline = client.pipeline(); - pipeline[exports.kExec] = false; - pipeline[exports.kCallbacks] = []; - client._autoPipelines.set(slotKey, pipeline); - } - const pipeline = client._autoPipelines.get(slotKey); - /* - Mark the pipeline as scheduled. - The symbol will make sure that the pipeline is only scheduled once per tick. - New commands are appended to an already scheduled pipeline. - */ - if (!pipeline[exports.kExec]) { - pipeline[exports.kExec] = true; - /* - Deferring with setImmediate so we have a chance to capture multiple - commands that can be scheduled by I/O events already in the event loop queue. - */ - setImmediate(executeAutoPipeline, client, slotKey); - } - // Create the promise which will execute the - const autoPipelinePromise = new CustomPromise(function (resolve, reject) { - pipeline[exports.kCallbacks].push(function (err, value) { - if (err) { - reject(err); - return; - } - resolve(value); - }); - pipeline[commandName](...args); - }); - return standard_as_callback_1.default(autoPipelinePromise, callback); -} -exports.executeWithAutoPipelining = executeWithAutoPipelining; +/* eslint complexity: [2, 18], max-statements: [2, 33] */ +module.exports = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } -/***/ }), + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } -/***/ 35835: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } -"use strict"; + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } -Object.defineProperty(exports, "__esModule", ({ value: true })); -const dns_1 = __nccwpck_require__(40881); -exports.DEFAULT_CLUSTER_OPTIONS = { - clusterRetryStrategy: (times) => Math.min(100 + times * 2, 2000), - enableOfflineQueue: true, - enableReadyCheck: true, - scaleReads: "master", - maxRedirections: 16, - retryDelayOnFailover: 100, - retryDelayOnClusterDown: 100, - retryDelayOnTryAgain: 100, - slotsRefreshTimeout: 1000, - slotsRefreshInterval: 5000, - dnsLookup: dns_1.lookup, - enableAutoPipelining: false, - autoPipeliningIgnoredCommands: [], - maxScriptsCachingTime: 60000, + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + var descriptor = Object.getOwnPropertyDescriptor(obj, sym); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; }; /***/ }), -/***/ 18394: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 76339: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const util_1 = __nccwpck_require__(94582); -const utils_1 = __nccwpck_require__(94832); -const redis_1 = __nccwpck_require__(83609); -const debug = utils_1.Debug("cluster:subscriber"); -const SUBSCRIBER_CONNECTION_NAME = "ioredisClusterSubscriber"; -class ClusterSubscriber { - constructor(connectionPool, emitter) { - this.connectionPool = connectionPool; - this.emitter = emitter; - this.started = false; - this.subscriber = null; - this.connectionPool.on("-node", (_, key) => { - if (!this.started || !this.subscriber) { - return; - } - if (util_1.getNodeKey(this.subscriber.options) === key) { - debug("subscriber has left, selecting a new one..."); - this.selectSubscriber(); - } - }); - this.connectionPool.on("+node", () => { - if (!this.started || this.subscriber) { - return; - } - debug("a new node is discovered and there is no subscriber, selecting a new one..."); - this.selectSubscriber(); - }); - } - getInstance() { - return this.subscriber; - } - selectSubscriber() { - const lastActiveSubscriber = this.lastActiveSubscriber; - // Disconnect the previous subscriber even if there - // will not be a new one. - if (lastActiveSubscriber) { - lastActiveSubscriber.disconnect(); - } - const sampleNode = utils_1.sample(this.connectionPool.getNodes()); - if (!sampleNode) { - debug("selecting subscriber failed since there is no node discovered in the cluster yet"); - this.subscriber = null; - return; - } - const { options } = sampleNode; - debug("selected a subscriber %s:%s", options.host, options.port); - /* - * Create a specialized Redis connection for the subscription. - * Note that auto reconnection is enabled here. - * - * `enableReadyCheck` is also enabled because although subscription is allowed - * while redis is loading data from the disk, we can check if the password - * provided for the subscriber is correct, and if not, the current subscriber - * will be disconnected and a new subscriber will be selected. - */ - this.subscriber = new redis_1.default({ - port: options.port, - host: options.host, - username: options.username, - password: options.password, - enableReadyCheck: true, - connectionName: SUBSCRIBER_CONNECTION_NAME, - lazyConnect: true, - tls: options.tls, - }); - // Ignore the errors since they're handled in the connection pool. - this.subscriber.on("error", utils_1.noop); - // Re-subscribe previous channels - const previousChannels = { subscribe: [], psubscribe: [] }; - if (lastActiveSubscriber) { - const condition = lastActiveSubscriber.condition || lastActiveSubscriber.prevCondition; - if (condition && condition.subscriber) { - previousChannels.subscribe = condition.subscriber.channels("subscribe"); - previousChannels.psubscribe = condition.subscriber.channels("psubscribe"); - } - } - if (previousChannels.subscribe.length || - previousChannels.psubscribe.length) { - let pending = 0; - for (const type of ["subscribe", "psubscribe"]) { - const channels = previousChannels[type]; - if (channels.length) { - pending += 1; - debug("%s %d channels", type, channels.length); - this.subscriber[type](channels) - .then(() => { - if (!--pending) { - this.lastActiveSubscriber = this.subscriber; - } - }) - .catch(utils_1.noop); - } - } - } - else { - this.lastActiveSubscriber = this.subscriber; - } - for (const event of ["message", "messageBuffer"]) { - this.subscriber.on(event, (arg1, arg2) => { - this.emitter.emit(event, arg1, arg2); - }); - } - for (const event of ["pmessage", "pmessageBuffer"]) { - this.subscriber.on(event, (arg1, arg2, arg3) => { - this.emitter.emit(event, arg1, arg2, arg3); - }); - } - } - start() { - this.started = true; - this.selectSubscriber(); - debug("started"); - } - stop() { - this.started = false; - if (this.subscriber) { - this.subscriber.disconnect(); - this.subscriber = null; - } - debug("stopped"); - } -} -exports.default = ClusterSubscriber; +var bind = __nccwpck_require__(88334); -/***/ }), +module.exports = bind.call(Function.call, Object.prototype.hasOwnProperty); -/***/ 34589: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +/***/ }), -Object.defineProperty(exports, "__esModule", ({ value: true })); -const events_1 = __nccwpck_require__(28614); -const utils_1 = __nccwpck_require__(94832); -const util_1 = __nccwpck_require__(94582); -const redis_1 = __nccwpck_require__(83609); -const debug = utils_1.Debug("cluster:connectionPool"); -class ConnectionPool extends events_1.EventEmitter { - constructor(redisOptions) { - super(); - this.redisOptions = redisOptions; - // master + slave = all - this.nodes = { - all: {}, - master: {}, - slave: {}, - }; - this.specifiedOptions = {}; - } - getNodes(role = "all") { - const nodes = this.nodes[role]; - return Object.keys(nodes).map((key) => nodes[key]); - } - getInstanceByKey(key) { - return this.nodes.all[key]; - } - getSampleInstance(role) { - const keys = Object.keys(this.nodes[role]); - const sampleKey = utils_1.sample(keys); - return this.nodes[role][sampleKey]; - } - /** - * Find or create a connection to the node - * - * @param {IRedisOptions} node - * @param {boolean} [readOnly=false] - * @returns {*} - * @memberof ConnectionPool - */ - findOrCreate(node, readOnly = false) { - const key = util_1.getNodeKey(node); - readOnly = Boolean(readOnly); - if (this.specifiedOptions[key]) { - Object.assign(node, this.specifiedOptions[key]); - } - else { - this.specifiedOptions[key] = node; - } - let redis; - if (this.nodes.all[key]) { - redis = this.nodes.all[key]; - if (redis.options.readOnly !== readOnly) { - redis.options.readOnly = readOnly; - debug("Change role of %s to %s", key, readOnly ? "slave" : "master"); - redis[readOnly ? "readonly" : "readwrite"]().catch(utils_1.noop); - if (readOnly) { - delete this.nodes.master[key]; - this.nodes.slave[key] = redis; - } - else { - delete this.nodes.slave[key]; - this.nodes.master[key] = redis; - } - } - } - else { - debug("Connecting to %s as %s", key, readOnly ? "slave" : "master"); - redis = new redis_1.default(utils_1.defaults({ - // Never try to reconnect when a node is lose, - // instead, waiting for a `MOVED` error and - // fetch the slots again. - retryStrategy: null, - // Offline queue should be enabled so that - // we don't need to wait for the `ready` event - // before sending commands to the node. - enableOfflineQueue: true, - readOnly: readOnly, - }, node, this.redisOptions, { lazyConnect: true })); - this.nodes.all[key] = redis; - this.nodes[readOnly ? "slave" : "master"][key] = redis; - redis.once("end", () => { - this.removeNode(key); - this.emit("-node", redis, key); - if (!Object.keys(this.nodes.all).length) { - this.emit("drain"); - } - }); - this.emit("+node", redis, key); - redis.on("error", function (error) { - this.emit("nodeError", error, key); - }); - } - return redis; - } - /** - * Remove a node from the pool. - */ - removeNode(key) { - const { nodes } = this; - if (nodes.all[key]) { - debug("Remove %s from the pool", key); - delete nodes.all[key]; - } - delete nodes.master[key]; - delete nodes.slave[key]; - } - /** - * Reset the pool with a set of nodes. - * The old node will be removed. - * - * @param {(Array)} nodes - * @memberof ConnectionPool - */ - reset(nodes) { - debug("Reset with %O", nodes); - const newNodes = {}; - nodes.forEach((node) => { - const key = util_1.getNodeKey(node); - // Don't override the existing (master) node - // when the current one is slave. - if (!(node.readOnly && newNodes[key])) { - newNodes[key] = node; - } - }); - Object.keys(this.nodes.all).forEach((key) => { - if (!newNodes[key]) { - debug("Disconnect %s because the node does not hold any slot", key); - this.nodes.all[key].disconnect(); - this.removeNode(key); - } - }); - Object.keys(newNodes).forEach((key) => { - const node = newNodes[key]; - this.findOrCreate(node, node.readOnly); - }); - } -} -exports.default = ConnectionPool; +/***/ 95193: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +/*! + * http-errors + * Copyright(c) 2014 Jonathan Ong + * Copyright(c) 2016 Douglas Christopher Wilson + * MIT Licensed + */ -/***/ }), -/***/ 12770: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/** + * Module dependencies. + * @private + */ -"use strict"; +var deprecate = __nccwpck_require__(18883)('http-errors') +var setPrototypeOf = __nccwpck_require__(40414) +var statuses = __nccwpck_require__(57415) +var inherits = __nccwpck_require__(8682) +var toIdentifier = __nccwpck_require__(46399) -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils_1 = __nccwpck_require__(94832); -const Deque = __nccwpck_require__(42342); -const debug = utils_1.Debug("delayqueue"); /** - * Queue that runs items after specified duration + * Module exports. + * @public + */ + +module.exports = createError +module.exports.HttpError = createHttpErrorConstructor() + +// Populate exports for all constructors +populateConstructorExports(module.exports, statuses.codes, module.exports.HttpError) + +/** + * Get the code class of a status code. + * @private + */ + +function codeClass (status) { + return Number(String(status).charAt(0) + '00') +} + +/** + * Create a new HTTP Error. * - * @export - * @class DelayQueue + * @returns {Error} + * @public */ -class DelayQueue { - constructor() { - this.queues = {}; - this.timeouts = {}; + +function createError () { + // so much arity going on ~_~ + var err + var msg + var status = 500 + var props = {} + for (var i = 0; i < arguments.length; i++) { + var arg = arguments[i] + if (arg instanceof Error) { + err = arg + status = err.status || err.statusCode || status + continue } - /** - * Add a new item to the queue - * - * @param {string} bucket bucket name - * @param {Function} item function that will run later - * @param {IDelayQueueOptions} options - * @memberof DelayQueue - */ - push(bucket, item, options) { - const callback = options.callback || process.nextTick; - if (!this.queues[bucket]) { - this.queues[bucket] = new Deque(); - } - const queue = this.queues[bucket]; - queue.push(item); - if (!this.timeouts[bucket]) { - this.timeouts[bucket] = setTimeout(() => { - callback(() => { - this.timeouts[bucket] = null; - this.execute(bucket); - }); - }, options.timeout); + switch (typeof arg) { + case 'string': + msg = arg + break + case 'number': + status = arg + if (i !== 0) { + deprecate('non-first-argument status code; replace with createError(' + arg + ', ...)') } + break + case 'object': + props = arg + break } - execute(bucket) { - const queue = this.queues[bucket]; - if (!queue) { - return; - } - const { length } = queue; - if (!length) { - return; - } - debug("send %d commands in %s queue", length, bucket); - this.queues[bucket] = null; - while (queue.length > 0) { - queue.shift()(); - } + } + + if (typeof status === 'number' && (status < 400 || status >= 600)) { + deprecate('non-error status code; use only 4xx or 5xx status codes') + } + + if (typeof status !== 'number' || + (!statuses[status] && (status < 400 || status >= 600))) { + status = 500 + } + + // constructor + var HttpError = createError[status] || createError[codeClass(status)] + + if (!err) { + // create error + err = HttpError + ? new HttpError(msg) + : new Error(msg || statuses[status]) + Error.captureStackTrace(err, createError) + } + + if (!HttpError || !(err instanceof HttpError) || err.status !== status) { + // add properties to generic error + err.expose = status < 500 + err.status = err.statusCode = status + } + + for (var key in props) { + if (key !== 'status' && key !== 'statusCode') { + err[key] = props[key] } + } + + return err } -exports.default = DelayQueue; +/** + * Create HTTP error abstract base class. + * @private + */ -/***/ }), +function createHttpErrorConstructor () { + function HttpError () { + throw new TypeError('cannot construct abstract class') + } -/***/ 17208: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + inherits(HttpError, Error) -"use strict"; + return HttpError +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -const events_1 = __nccwpck_require__(28614); -const ClusterAllFailedError_1 = __nccwpck_require__(97282); -const utils_1 = __nccwpck_require__(94832); -const ConnectionPool_1 = __nccwpck_require__(34589); -const util_1 = __nccwpck_require__(94582); -const ClusterSubscriber_1 = __nccwpck_require__(18394); -const DelayQueue_1 = __nccwpck_require__(12770); -const ScanStream_1 = __nccwpck_require__(6134); -const redis_errors_1 = __nccwpck_require__(81879); -const standard_as_callback_1 = __nccwpck_require__(91543); -const PromiseContainer = __nccwpck_require__(71475); -const ClusterOptions_1 = __nccwpck_require__(35835); -const utils_2 = __nccwpck_require__(94832); -const commands = __nccwpck_require__(98020); -const command_1 = __nccwpck_require__(90803); -const redis_1 = __nccwpck_require__(83609); -const commander_1 = __nccwpck_require__(33642); -const Deque = __nccwpck_require__(42342); -const debug = utils_1.Debug("cluster"); /** - * Client for the official Redis Cluster - * - * @class Cluster - * @extends {EventEmitter} + * Create a constructor for a client error. + * @private */ -class Cluster extends events_1.EventEmitter { - /** - * Creates an instance of Cluster. - * - * @param {((string | number | object)[])} startupNodes - * @param {IClusterOptions} [options={}] - * @memberof Cluster - */ - constructor(startupNodes, options = {}) { - super(); - this.slots = []; - this.retryAttempts = 0; - this.delayQueue = new DelayQueue_1.default(); - this.offlineQueue = new Deque(); - this.isRefreshing = false; - this.isCluster = true; - this._autoPipelines = new Map(); - this._runningAutoPipelines = new Set(); - this._readyDelayedCallbacks = []; - this._addedScriptHashes = {}; - /** - * Every time Cluster#connect() is called, this value will be - * auto-incrementing. The purpose of this value is used for - * discarding previous connect attampts when creating a new - * connection. - * - * @private - * @type {number} - * @memberof Cluster - */ - this.connectionEpoch = 0; - commander_1.default.call(this); - this.startupNodes = startupNodes; - this.options = utils_1.defaults({}, options, ClusterOptions_1.DEFAULT_CLUSTER_OPTIONS, this.options); - // validate options - if (typeof this.options.scaleReads !== "function" && - ["all", "master", "slave"].indexOf(this.options.scaleReads) === -1) { - throw new Error('Invalid option scaleReads "' + - this.options.scaleReads + - '". Expected "all", "master", "slave" or a custom function'); - } - this.connectionPool = new ConnectionPool_1.default(this.options.redisOptions); - this.connectionPool.on("-node", (redis, key) => { - this.emit("-node", redis); - }); - this.connectionPool.on("+node", (redis) => { - this.emit("+node", redis); - }); - this.connectionPool.on("drain", () => { - this.setStatus("close"); - }); - this.connectionPool.on("nodeError", (error, key) => { - this.emit("node error", error, key); - }); - this.subscriber = new ClusterSubscriber_1.default(this.connectionPool, this); - if (this.options.lazyConnect) { - this.setStatus("wait"); - } - else { - this.connect().catch((err) => { - debug("connecting failed: %s", err); - }); - } - } - resetOfflineQueue() { - this.offlineQueue = new Deque(); - } - clearNodesRefreshInterval() { - if (this.slotsTimer) { - clearTimeout(this.slotsTimer); - this.slotsTimer = null; - } - } - resetNodesRefreshInterval() { - if (this.slotsTimer) { - return; - } - const nextRound = () => { - this.slotsTimer = setTimeout(() => { - debug('refreshing slot caches... (triggered by "slotsRefreshInterval" option)'); - this.refreshSlotsCache(() => { - nextRound(); - }); - }, this.options.slotsRefreshInterval); - }; - nextRound(); - } - /** - * Connect to a cluster - * - * @returns {Promise} - * @memberof Cluster - */ - connect() { - const Promise = PromiseContainer.get(); - return new Promise((resolve, reject) => { - if (this.status === "connecting" || - this.status === "connect" || - this.status === "ready") { - reject(new Error("Redis is already connecting/connected")); - return; - } - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = setInterval(() => { - this._addedScriptHashes = {}; - }, this.options.maxScriptsCachingTime); - const epoch = ++this.connectionEpoch; - this.setStatus("connecting"); - this.resolveStartupNodeHostnames() - .then((nodes) => { - if (this.connectionEpoch !== epoch) { - debug("discard connecting after resolving startup nodes because epoch not match: %d != %d", epoch, this.connectionEpoch); - reject(new redis_errors_1.RedisError("Connection is discarded because a new connection is made")); - return; - } - if (this.status !== "connecting") { - debug("discard connecting after resolving startup nodes because the status changed to %s", this.status); - reject(new redis_errors_1.RedisError("Connection is aborted")); - return; - } - this.connectionPool.reset(nodes); - function readyHandler() { - this.setStatus("ready"); - this.retryAttempts = 0; - this.executeOfflineCommands(); - this.resetNodesRefreshInterval(); - resolve(); - } - let closeListener = undefined; - const refreshListener = () => { - this.invokeReadyDelayedCallbacks(undefined); - this.removeListener("close", closeListener); - this.manuallyClosing = false; - this.setStatus("connect"); - if (this.options.enableReadyCheck) { - this.readyCheck((err, fail) => { - if (err || fail) { - debug("Ready check failed (%s). Reconnecting...", err || fail); - if (this.status === "connect") { - this.disconnect(true); - } - } - else { - readyHandler.call(this); - } - }); - } - else { - readyHandler.call(this); - } - }; - closeListener = function () { - const error = new Error("None of startup nodes is available"); - this.removeListener("refresh", refreshListener); - this.invokeReadyDelayedCallbacks(error); - reject(error); - }; - this.once("refresh", refreshListener); - this.once("close", closeListener); - this.once("close", this.handleCloseEvent.bind(this)); - this.refreshSlotsCache(function (err) { - if (err && err.message === "Failed to refresh slots cache.") { - redis_1.default.prototype.silentEmit.call(this, "error", err); - this.connectionPool.reset([]); - } - }.bind(this)); - this.subscriber.start(); - }) - .catch((err) => { - this.setStatus("close"); - this.handleCloseEvent(err); - this.invokeReadyDelayedCallbacks(err); - reject(err); - }); - }); - } - /** - * Called when closed to check whether a reconnection should be made - * - * @private - * @memberof Cluster - */ - handleCloseEvent(reason) { - if (reason) { - debug("closed because %s", reason); - } - let retryDelay; - if (!this.manuallyClosing && - typeof this.options.clusterRetryStrategy === "function") { - retryDelay = this.options.clusterRetryStrategy.call(this, ++this.retryAttempts, reason); - } - if (typeof retryDelay === "number") { - this.setStatus("reconnecting"); - this.reconnectTimeout = setTimeout(function () { - this.reconnectTimeout = null; - debug("Cluster is disconnected. Retrying after %dms", retryDelay); - this.connect().catch(function (err) { - debug("Got error %s when reconnecting. Ignoring...", err); - }); - }.bind(this), retryDelay); - } - else { - this.setStatus("end"); - this.flushQueue(new Error("None of startup nodes is available")); - } + +function createClientErrorConstructor (HttpError, name, code) { + var className = name.match(/Error$/) ? name : name + 'Error' + + function ClientError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ClientError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ClientError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ClientError, HttpError) + nameFunc(ClientError, className) + + ClientError.prototype.status = code + ClientError.prototype.statusCode = code + ClientError.prototype.expose = true + + return ClientError +} + +/** + * Create a constructor for a server error. + * @private + */ + +function createServerErrorConstructor (HttpError, name, code) { + var className = name.match(/Error$/) ? name : name + 'Error' + + function ServerError (message) { + // create the error object + var msg = message != null ? message : statuses[code] + var err = new Error(msg) + + // capture a stack trace to the construction point + Error.captureStackTrace(err, ServerError) + + // adjust the [[Prototype]] + setPrototypeOf(err, ServerError.prototype) + + // redefine the error message + Object.defineProperty(err, 'message', { + enumerable: true, + configurable: true, + value: msg, + writable: true + }) + + // redefine the error name + Object.defineProperty(err, 'name', { + enumerable: false, + configurable: true, + value: className, + writable: true + }) + + return err + } + + inherits(ServerError, HttpError) + nameFunc(ServerError, className) + + ServerError.prototype.status = code + ServerError.prototype.statusCode = code + ServerError.prototype.expose = false + + return ServerError +} + +/** + * Set the name of a function, if possible. + * @private + */ + +function nameFunc (func, name) { + var desc = Object.getOwnPropertyDescriptor(func, 'name') + + if (desc && desc.configurable) { + desc.value = name + Object.defineProperty(func, 'name', desc) + } +} + +/** + * Populate the exports object with constructors for every error class. + * @private + */ + +function populateConstructorExports (exports, codes, HttpError) { + codes.forEach(function forEachCode (code) { + var CodeError + var name = toIdentifier(statuses[code]) + + switch (codeClass(code)) { + case 400: + CodeError = createClientErrorConstructor(HttpError, name, code) + break + case 500: + CodeError = createServerErrorConstructor(HttpError, name, code) + break } - /** - * Disconnect from every node in the cluster. - * - * @param {boolean} [reconnect=false] - * @memberof Cluster - */ - disconnect(reconnect = false) { - const status = this.status; - this.setStatus("disconnecting"); - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = null; - if (!reconnect) { - this.manuallyClosing = true; - } - if (this.reconnectTimeout && !reconnect) { - clearTimeout(this.reconnectTimeout); - this.reconnectTimeout = null; - debug("Canceled reconnecting attempts"); - } - this.clearNodesRefreshInterval(); - this.subscriber.stop(); - if (status === "wait") { - this.setStatus("close"); - this.handleCloseEvent(); + + if (CodeError) { + // export the constructor + exports[code] = CodeError + exports[name] = CodeError + } + }) + + // backwards-compatibility + exports["I'mateapot"] = deprecate.function(exports.ImATeapot, + '"I\'mateapot"; use "ImATeapot" instead') +} + + +/***/ }), + +/***/ 8682: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +try { + var util = __nccwpck_require__(31669); + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + module.exports = __nccwpck_require__(25250); +} + + +/***/ }), + +/***/ 25250: +/***/ ((module) => { + +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }); + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } +} + + +/***/ }), + +/***/ 15098: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __awaiter = (this && this.__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()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const net_1 = __importDefault(__nccwpck_require__(11631)); +const tls_1 = __importDefault(__nccwpck_require__(4016)); +const url_1 = __importDefault(__nccwpck_require__(78835)); +const assert_1 = __importDefault(__nccwpck_require__(42357)); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const agent_base_1 = __nccwpck_require__(49690); +const parse_proxy_response_1 = __importDefault(__nccwpck_require__(595)); +const debug = debug_1.default('https-proxy-agent:agent'); +/** + * The `HttpsProxyAgent` implements an HTTP Agent subclass that connects to + * the specified "HTTP(s) proxy server" in order to proxy HTTPS requests. + * + * Outgoing HTTP requests are first tunneled through the proxy server using the + * `CONNECT` HTTP request method to establish a connection to the proxy server, + * and then the proxy server connects to the destination target and issues the + * HTTP request from the proxy server. + * + * `https:` requests have their socket connection upgraded to TLS once + * the connection to the proxy server has been established. + * + * @api public + */ +class HttpsProxyAgent extends agent_base_1.Agent { + constructor(_opts) { + let opts; + if (typeof _opts === 'string') { + opts = url_1.default.parse(_opts); } else { - this.connectionPool.reset([]); - } - } - /** - * Quit the cluster gracefully. - * - * @param {CallbackFunction<'OK'>} [callback] - * @returns {Promise<'OK'>} - * @memberof Cluster - */ - quit(callback) { - const status = this.status; - this.setStatus("disconnecting"); - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = null; - this.manuallyClosing = true; - if (this.reconnectTimeout) { - clearTimeout(this.reconnectTimeout); - this.reconnectTimeout = null; + opts = _opts; } - this.clearNodesRefreshInterval(); - this.subscriber.stop(); - const Promise = PromiseContainer.get(); - if (status === "wait") { - const ret = standard_as_callback_1.default(Promise.resolve("OK"), callback); - // use setImmediate to make sure "close" event - // being emitted after quit() is returned - setImmediate(function () { - this.setStatus("close"); - this.handleCloseEvent(); - }.bind(this)); - return ret; + if (!opts) { + throw new Error('an HTTP(S) proxy server `host` and `port` must be specified!'); } - return standard_as_callback_1.default(Promise.all(this.nodes().map((node) => node.quit().catch((err) => { - // Ignore the error caused by disconnecting since - // we're disconnecting... - if (err.message === utils_2.CONNECTION_CLOSED_ERROR_MSG) { - return "OK"; - } - throw err; - }))).then(() => "OK"), callback); - } - /** - * Create a new instance with the same startup nodes and options as the current one. - * - * @example - * ```js - * var cluster = new Redis.Cluster([{ host: "127.0.0.1", port: "30001" }]); - * var anotherCluster = cluster.duplicate(); - * ``` - * - * @public - * @param {((string | number | object)[])} [overrideStartupNodes=[]] - * @param {IClusterOptions} [overrideOptions={}] - * @memberof Cluster - */ - duplicate(overrideStartupNodes = [], overrideOptions = {}) { - const startupNodes = overrideStartupNodes.length > 0 - ? overrideStartupNodes - : this.startupNodes.slice(0); - const options = Object.assign({}, this.options, overrideOptions); - return new Cluster(startupNodes, options); - } - /** - * Get nodes with the specified role - * - * @param {NodeRole} [role='all'] - * @returns {any[]} - * @memberof Cluster - */ - nodes(role = "all") { - if (role !== "all" && role !== "master" && role !== "slave") { - throw new Error('Invalid role "' + role + '". Expected "all", "master" or "slave"'); + debug('creating new HttpsProxyAgent instance: %o', opts); + super(opts); + const proxy = Object.assign({}, opts); + // If `true`, then connect to the proxy server over TLS. + // Defaults to `false`. + this.secureProxy = opts.secureProxy || isHTTPS(proxy.protocol); + // Prefer `hostname` over `host`, and set the `port` if needed. + proxy.host = proxy.hostname || proxy.host; + if (typeof proxy.port === 'string') { + proxy.port = parseInt(proxy.port, 10); } - return this.connectionPool.getNodes(role); - } - // This is needed in order not to install a listener for each auto pipeline - delayUntilReady(callback) { - this._readyDelayedCallbacks.push(callback); - } - /** - * Get the number of commands queued in automatic pipelines. - * - * This is not available (and returns 0) until the cluster is connected and slots information have been received. - */ - get autoPipelineQueueSize() { - let queued = 0; - for (const pipeline of this._autoPipelines.values()) { - queued += pipeline.length; + if (!proxy.port && proxy.host) { + proxy.port = this.secureProxy ? 443 : 80; } - return queued; - } - /** - * Change cluster instance's status - * - * @private - * @param {ClusterStatus} status - * @memberof Cluster - */ - setStatus(status) { - debug("status: %s -> %s", this.status || "[empty]", status); - this.status = status; - process.nextTick(() => { - this.emit(status); - }); - } - /** - * Refresh the slot cache - * - * @private - * @param {CallbackFunction} [callback] - * @memberof Cluster - */ - refreshSlotsCache(callback) { - if (this.isRefreshing) { - if (typeof callback === "function") { - process.nextTick(callback); - } - return; + // ALPN is supported by Node.js >= v5. + // attempt to negotiate http/1.1 for proxy servers that support http/2 + if (this.secureProxy && !('ALPNProtocols' in proxy)) { + proxy.ALPNProtocols = ['http 1.1']; } - this.isRefreshing = true; - const _this = this; - const wrapper = function (error) { - _this.isRefreshing = false; - if (typeof callback === "function") { - callback(error); - } - }; - const nodes = utils_2.shuffle(this.connectionPool.getNodes()); - let lastNodeError = null; - function tryNode(index) { - if (index === nodes.length) { - const error = new ClusterAllFailedError_1.default("Failed to refresh slots cache.", lastNodeError); - return wrapper(error); - } - const node = nodes[index]; - const key = `${node.options.host}:${node.options.port}`; - debug("getting slot cache from %s", key); - _this.getInfoFromNode(node, function (err) { - switch (_this.status) { - case "close": - case "end": - return wrapper(new Error("Cluster is disconnected.")); - case "disconnecting": - return wrapper(new Error("Cluster is disconnecting.")); - } - if (err) { - _this.emit("node error", err, key); - lastNodeError = err; - tryNode(index + 1); - } - else { - _this.emit("refresh"); - wrapper(); - } - }); + if (proxy.host && proxy.path) { + // If both a `host` and `path` are specified then it's most likely + // the result of a `url.parse()` call... we need to remove the + // `path` portion so that `net.connect()` doesn't attempt to open + // that as a Unix socket file. + delete proxy.path; + delete proxy.pathname; } - tryNode(0); + this.proxy = proxy; } /** - * Flush offline queue with error. + * Called when the node-core HTTP client library is creating a + * new HTTP request. * - * @param {Error} error - * @memberof Cluster + * @api protected */ - flushQueue(error) { - let item; - while (this.offlineQueue.length > 0) { - item = this.offlineQueue.shift(); - item.command.reject(error); - } - } - executeOfflineCommands() { - if (this.offlineQueue.length) { - debug("send %d commands in offline queue", this.offlineQueue.length); - const offlineQueue = this.offlineQueue; - this.resetOfflineQueue(); - while (offlineQueue.length > 0) { - const item = offlineQueue.shift(); - this.sendCommand(item.command, item.stream, item.node); - } - } - } - natMapper(nodeKey) { - if (this.options.natMap && typeof this.options.natMap === "object") { - const key = typeof nodeKey === "string" - ? nodeKey - : `${nodeKey.host}:${nodeKey.port}`; - const mapped = this.options.natMap[key]; - if (mapped) { - debug("NAT mapping %s -> %O", key, mapped); - return Object.assign({}, mapped); - } - } - return typeof nodeKey === "string" - ? util_1.nodeKeyToRedisOptions(nodeKey) - : nodeKey; - } - sendCommand(command, stream, node) { - if (this.status === "wait") { - this.connect().catch(utils_1.noop); - } - if (this.status === "end") { - command.reject(new Error(utils_2.CONNECTION_CLOSED_ERROR_MSG)); - return command.promise; - } - let to = this.options.scaleReads; - if (to !== "master") { - const isCommandReadOnly = command.isReadOnly || - (commands.exists(command.name) && - commands.hasFlag(command.name, "readonly")); - if (!isCommandReadOnly) { - to = "master"; + callback(req, opts) { + return __awaiter(this, void 0, void 0, function* () { + const { proxy, secureProxy } = this; + // Create a socket connection to the proxy server. + let socket; + if (secureProxy) { + debug('Creating `tls.Socket`: %o', proxy); + socket = tls_1.default.connect(proxy); } - } - let targetSlot = node ? node.slot : command.getSlot(); - const ttl = {}; - const _this = this; - if (!node && !command.__is_reject_overwritten) { - // eslint-disable-next-line @typescript-eslint/camelcase - command.__is_reject_overwritten = true; - const reject = command.reject; - command.reject = function (err) { - const partialTry = tryConnection.bind(null, true); - _this.handleError(err, ttl, { - moved: function (slot, key) { - debug("command %s is moved to %s", command.name, key); - targetSlot = Number(slot); - if (_this.slots[slot]) { - _this.slots[slot][0] = key; - } - else { - _this.slots[slot] = [key]; - } - _this.connectionPool.findOrCreate(_this.natMapper(key)); - tryConnection(); - debug("refreshing slot caches... (triggered by MOVED error)"); - _this.refreshSlotsCache(); - }, - ask: function (slot, key) { - debug("command %s is required to ask %s:%s", command.name, key); - const mapped = _this.natMapper(key); - _this.connectionPool.findOrCreate(mapped); - tryConnection(false, `${mapped.host}:${mapped.port}`); - }, - tryagain: partialTry, - clusterDown: partialTry, - connectionClosed: partialTry, - maxRedirections: function (redirectionError) { - reject.call(command, redirectionError); - }, - defaults: function () { - reject.call(command, err); - }, - }); - }; - } - tryConnection(); - function tryConnection(random, asking) { - if (_this.status === "end") { - command.reject(new redis_errors_1.AbortError("Cluster is ended.")); - return; + else { + debug('Creating `net.Socket`: %o', proxy); + socket = net_1.default.connect(proxy); } - let redis; - if (_this.status === "ready" || command.name === "cluster") { - if (node && node.redis) { - redis = node.redis; - } - else if (command_1.default.checkFlag("ENTER_SUBSCRIBER_MODE", command.name) || - command_1.default.checkFlag("EXIT_SUBSCRIBER_MODE", command.name)) { - redis = _this.subscriber.getInstance(); - if (!redis) { - command.reject(new redis_errors_1.AbortError("No subscriber for the cluster")); - return; - } - } - else { - if (!random) { - if (typeof targetSlot === "number" && _this.slots[targetSlot]) { - const nodeKeys = _this.slots[targetSlot]; - if (typeof to === "function") { - const nodes = nodeKeys.map(function (key) { - return _this.connectionPool.getInstanceByKey(key); - }); - redis = to(nodes, command); - if (Array.isArray(redis)) { - redis = utils_2.sample(redis); - } - if (!redis) { - redis = nodes[0]; - } - } - else { - let key; - if (to === "all") { - key = utils_2.sample(nodeKeys); - } - else if (to === "slave" && nodeKeys.length > 1) { - key = utils_2.sample(nodeKeys, 1); - } - else { - key = nodeKeys[0]; - } - redis = _this.connectionPool.getInstanceByKey(key); - } - } - if (asking) { - redis = _this.connectionPool.getInstanceByKey(asking); - redis.asking(); - } - } - if (!redis) { - redis = - (typeof to === "function" - ? null - : _this.connectionPool.getSampleInstance(to)) || - _this.connectionPool.getSampleInstance("all"); - } - } - if (node && !node.redis) { - node.redis = redis; - } + const headers = Object.assign({}, proxy.headers); + const hostname = `${opts.host}:${opts.port}`; + let payload = `CONNECT ${hostname} HTTP/1.1\r\n`; + // Inject the `Proxy-Authorization` header if necessary. + if (proxy.auth) { + headers['Proxy-Authorization'] = `Basic ${Buffer.from(proxy.auth).toString('base64')}`; } - if (redis) { - redis.sendCommand(command, stream); + // The `Host` header should only include the port + // number when it is not the default port. + let { host, port, secureEndpoint } = opts; + if (!isDefaultPort(port, secureEndpoint)) { + host += `:${port}`; } - else if (_this.options.enableOfflineQueue) { - _this.offlineQueue.push({ - command: command, - stream: stream, - node: node, - }); + headers.Host = host; + headers.Connection = 'close'; + for (const name of Object.keys(headers)) { + payload += `${name}: ${headers[name]}\r\n`; } - else { - command.reject(new Error("Cluster isn't ready and enableOfflineQueue options is false")); + const proxyResponsePromise = parse_proxy_response_1.default(socket); + socket.write(`${payload}\r\n`); + const { statusCode, buffered } = yield proxyResponsePromise; + if (statusCode === 200) { + req.once('socket', resume); + if (opts.secureEndpoint) { + const servername = opts.servername || opts.host; + if (!servername) { + throw new Error('Could not determine "servername"'); + } + // The proxy is connecting to a TLS server, so upgrade + // this socket connection to a TLS connection. + debug('Upgrading socket connection to TLS'); + return tls_1.default.connect(Object.assign(Object.assign({}, omit(opts, 'host', 'hostname', 'path', 'port')), { socket, + servername })); + } + return socket; } - } - return command.promise; + // Some other status code that's not 200... need to re-play the HTTP + // header "data" events onto the socket once the HTTP machinery is + // attached so that the node core `http` can parse and handle the + // error status code. + // Close the original socket, and a new "fake" socket is returned + // instead, so that the proxy doesn't get the HTTP request + // written to it (which may contain `Authorization` headers or other + // sensitive data). + // + // See: https://hackerone.com/reports/541502 + socket.destroy(); + const fakeSocket = new net_1.default.Socket(); + fakeSocket.readable = true; + // Need to wait for the "socket" event to re-play the "data" events. + req.once('socket', (s) => { + debug('replaying proxy buffer for failed request'); + assert_1.default(s.listenerCount('data') > 0); + // Replay the "buffered" Buffer onto the fake `socket`, since at + // this point the HTTP module machinery has been hooked up for + // the user. + s.push(buffered); + s.push(null); + }); + return fakeSocket; + }); } - handleError(error, ttl, handlers) { - if (typeof ttl.value === "undefined") { - ttl.value = this.options.maxRedirections; +} +exports.default = HttpsProxyAgent; +function resume(socket) { + socket.resume(); +} +function isDefaultPort(port, secure) { + return Boolean((!secure && port === 80) || (secure && port === 443)); +} +function isHTTPS(protocol) { + return typeof protocol === 'string' ? /^https:?$/i.test(protocol) : false; +} +function omit(obj, ...keys) { + const ret = {}; + let key; + for (key in obj) { + if (!keys.includes(key)) { + ret[key] = obj[key]; } - else { - ttl.value -= 1; + } + return ret; +} +//# sourceMappingURL=agent.js.map + +/***/ }), + +/***/ 77219: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +const agent_1 = __importDefault(__nccwpck_require__(15098)); +function createHttpsProxyAgent(opts) { + return new agent_1.default(opts); +} +(function (createHttpsProxyAgent) { + createHttpsProxyAgent.HttpsProxyAgent = agent_1.default; + createHttpsProxyAgent.prototype = agent_1.default.prototype; +})(createHttpsProxyAgent || (createHttpsProxyAgent = {})); +module.exports = createHttpsProxyAgent; +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 595: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + +"use strict"; + +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const debug_1 = __importDefault(__nccwpck_require__(38237)); +const debug = debug_1.default('https-proxy-agent:parse-proxy-response'); +function parseProxyResponse(socket) { + return new Promise((resolve, reject) => { + // we need to buffer any HTTP traffic that happens with the proxy before we get + // the CONNECT response, so that if the response is anything other than an "200" + // response code, then we can re-play the "data" events on the socket once the + // HTTP parser is hooked up... + let buffersLength = 0; + const buffers = []; + function read() { + const b = socket.read(); + if (b) + ondata(b); + else + socket.once('readable', read); } - if (ttl.value <= 0) { - handlers.maxRedirections(new Error("Too many Cluster redirections. Last error: " + error)); - return; + function cleanup() { + socket.removeListener('end', onend); + socket.removeListener('error', onerror); + socket.removeListener('close', onclose); + socket.removeListener('readable', read); } - const errv = error.message.split(" "); - if (errv[0] === "MOVED" || errv[0] === "ASK") { - handlers[errv[0] === "MOVED" ? "moved" : "ask"](errv[1], errv[2]); + function onclose(err) { + debug('onclose had error %o', err); } - else if (errv[0] === "TRYAGAIN") { - this.delayQueue.push("tryagain", handlers.tryagain, { - timeout: this.options.retryDelayOnTryAgain, - }); + function onend() { + debug('onend'); } - else if (errv[0] === "CLUSTERDOWN" && - this.options.retryDelayOnClusterDown > 0) { - this.delayQueue.push("clusterdown", handlers.connectionClosed, { - timeout: this.options.retryDelayOnClusterDown, - callback: this.refreshSlotsCache.bind(this), - }); + function onerror(err) { + cleanup(); + debug('onerror %o', err); + reject(err); } - else if (error.message === utils_2.CONNECTION_CLOSED_ERROR_MSG && - this.options.retryDelayOnFailover > 0 && - this.status === "ready") { - this.delayQueue.push("failover", handlers.connectionClosed, { - timeout: this.options.retryDelayOnFailover, - callback: this.refreshSlotsCache.bind(this), + function ondata(b) { + buffers.push(b); + buffersLength += b.length; + const buffered = Buffer.concat(buffers, buffersLength); + const endOfHeaders = buffered.indexOf('\r\n\r\n'); + if (endOfHeaders === -1) { + // keep buffering + debug('have not received end of HTTP headers yet...'); + read(); + return; + } + const firstLine = buffered.toString('ascii', 0, buffered.indexOf('\r\n')); + const statusCode = +firstLine.split(' ')[1]; + debug('got proxy server response: %o', firstLine); + resolve({ + statusCode, + buffered }); } - else { - handlers.defaults(); + socket.on('error', onerror); + socket.on('close', onclose); + socket.on('end', onend); + read(); + }); +} +exports.default = parseProxyResponse; +//# sourceMappingURL=parse-proxy-response.js.map + +/***/ }), + +/***/ 39695: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +var Buffer = __nccwpck_require__(15118).Buffer; + +// Multibyte codec. In this scheme, a character is represented by 1 or more bytes. +// Our codec supports UTF-16 surrogates, extensions for GB18030 and unicode sequences. +// To save memory and loading time, we read table files only when requested. + +exports._dbcs = DBCSCodec; + +var UNASSIGNED = -1, + GB18030_CODE = -2, + SEQ_START = -10, + NODE_START = -1000, + UNASSIGNED_NODE = new Array(0x100), + DEF_CHAR = -1; + +for (var i = 0; i < 0x100; i++) + UNASSIGNED_NODE[i] = UNASSIGNED; + + +// Class DBCSCodec reads and initializes mapping tables. +function DBCSCodec(codecOptions, iconv) { + this.encodingName = codecOptions.encodingName; + if (!codecOptions) + throw new Error("DBCS codec is called without the data.") + if (!codecOptions.table) + throw new Error("Encoding '" + this.encodingName + "' has no data."); + + // Load tables. + var mappingTable = codecOptions.table(); + + + // Decode tables: MBCS -> Unicode. + + // decodeTables is a trie, encoded as an array of arrays of integers. Internal arrays are trie nodes and all have len = 256. + // Trie root is decodeTables[0]. + // Values: >= 0 -> unicode character code. can be > 0xFFFF + // == UNASSIGNED -> unknown/unassigned sequence. + // == GB18030_CODE -> this is the end of a GB18030 4-byte sequence. + // <= NODE_START -> index of the next node in our trie to process next byte. + // <= SEQ_START -> index of the start of a character code sequence, in decodeTableSeq. + this.decodeTables = []; + this.decodeTables[0] = UNASSIGNED_NODE.slice(0); // Create root node. + + // Sometimes a MBCS char corresponds to a sequence of unicode chars. We store them as arrays of integers here. + this.decodeTableSeq = []; + + // Actual mapping tables consist of chunks. Use them to fill up decode tables. + for (var i = 0; i < mappingTable.length; i++) + this._addDecodeChunk(mappingTable[i]); + + this.defaultCharUnicode = iconv.defaultCharUnicode; + + + // Encode tables: Unicode -> DBCS. + + // `encodeTable` is array mapping from unicode char to encoded char. All its values are integers for performance. + // Because it can be sparse, it is represented as array of buckets by 256 chars each. Bucket can be null. + // Values: >= 0 -> it is a normal char. Write the value (if <=256 then 1 byte, if <=65536 then 2 bytes, etc.). + // == UNASSIGNED -> no conversion found. Output a default char. + // <= SEQ_START -> it's an index in encodeTableSeq, see below. The character starts a sequence. + this.encodeTable = []; + + // `encodeTableSeq` is used when a sequence of unicode characters is encoded as a single code. We use a tree of + // objects where keys correspond to characters in sequence and leafs are the encoded dbcs values. A special DEF_CHAR key + // means end of sequence (needed when one sequence is a strict subsequence of another). + // Objects are kept separately from encodeTable to increase performance. + this.encodeTableSeq = []; + + // Some chars can be decoded, but need not be encoded. + var skipEncodeChars = {}; + if (codecOptions.encodeSkipVals) + for (var i = 0; i < codecOptions.encodeSkipVals.length; i++) { + var val = codecOptions.encodeSkipVals[i]; + if (typeof val === 'number') + skipEncodeChars[val] = true; + else + for (var j = val.from; j <= val.to; j++) + skipEncodeChars[j] = true; } + + // Use decode trie to recursively fill out encode tables. + this._fillEncodeTable(0, 0, skipEncodeChars); + + // Add more encoding pairs when needed. + if (codecOptions.encodeAdd) { + for (var uChar in codecOptions.encodeAdd) + if (Object.prototype.hasOwnProperty.call(codecOptions.encodeAdd, uChar)) + this._setEncodeChar(uChar.charCodeAt(0), codecOptions.encodeAdd[uChar]); } - getInfoFromNode(redis, callback) { - if (!redis) { - return callback(new Error("Node is disconnected")); + + this.defCharSB = this.encodeTable[0][iconv.defaultCharSingleByte.charCodeAt(0)]; + if (this.defCharSB === UNASSIGNED) this.defCharSB = this.encodeTable[0]['?']; + if (this.defCharSB === UNASSIGNED) this.defCharSB = "?".charCodeAt(0); + + + // Load & create GB18030 tables when needed. + if (typeof codecOptions.gb18030 === 'function') { + this.gb18030 = codecOptions.gb18030(); // Load GB18030 ranges. + + // Add GB18030 decode tables. + var thirdByteNodeIdx = this.decodeTables.length; + var thirdByteNode = this.decodeTables[thirdByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + var fourthByteNodeIdx = this.decodeTables.length; + var fourthByteNode = this.decodeTables[fourthByteNodeIdx] = UNASSIGNED_NODE.slice(0); + + for (var i = 0x81; i <= 0xFE; i++) { + var secondByteNodeIdx = NODE_START - this.decodeTables[0][i]; + var secondByteNode = this.decodeTables[secondByteNodeIdx]; + for (var j = 0x30; j <= 0x39; j++) + secondByteNode[j] = NODE_START - thirdByteNodeIdx; } - // Use a duplication of the connection to avoid - // timeouts when the connection is in the blocking - // mode (e.g. waiting for BLPOP). - const duplicatedConnection = redis.duplicate({ - enableOfflineQueue: true, - enableReadyCheck: false, - retryStrategy: null, - connectionName: "ioredisClusterRefresher", - }); - // Ignore error events since we will handle - // exceptions for the CLUSTER SLOTS command. - duplicatedConnection.on("error", utils_1.noop); - duplicatedConnection.cluster("slots", utils_2.timeout((err, result) => { - duplicatedConnection.disconnect(); - if (err) { - return callback(err); - } - if (this.status === "disconnecting" || - this.status === "close" || - this.status === "end") { - debug("ignore CLUSTER.SLOTS results (count: %d) since cluster status is %s", result.length, this.status); - callback(); - return; - } - const nodes = []; - debug("cluster slots result count: %d", result.length); - for (let i = 0; i < result.length; ++i) { - const items = result[i]; - const slotRangeStart = items[0]; - const slotRangeEnd = items[1]; - const keys = []; - for (let j = 2; j < items.length; j++) { - if (!items[j][0]) { - continue; - } - items[j] = this.natMapper({ host: items[j][0], port: items[j][1] }); - items[j].readOnly = j !== 2; - nodes.push(items[j]); - keys.push(items[j].host + ":" + items[j].port); - } - debug("cluster slots result [%d]: slots %d~%d served by %s", i, slotRangeStart, slotRangeEnd, keys); - for (let slot = slotRangeStart; slot <= slotRangeEnd; slot++) { - this.slots[slot] = keys; - } - } - this.connectionPool.reset(nodes); - callback(); - }, this.options.slotsRefreshTimeout)); - } - invokeReadyDelayedCallbacks(err) { - for (const c of this._readyDelayedCallbacks) { - process.nextTick(c, err); + for (var i = 0x81; i <= 0xFE; i++) + thirdByteNode[i] = NODE_START - fourthByteNodeIdx; + for (var i = 0x30; i <= 0x39; i++) + fourthByteNode[i] = GB18030_CODE + } +} + +DBCSCodec.prototype.encoder = DBCSEncoder; +DBCSCodec.prototype.decoder = DBCSDecoder; + +// Decoder helpers +DBCSCodec.prototype._getDecodeTrieNode = function(addr) { + var bytes = []; + for (; addr > 0; addr >>= 8) + bytes.push(addr & 0xFF); + if (bytes.length == 0) + bytes.push(0); + + var node = this.decodeTables[0]; + for (var i = bytes.length-1; i > 0; i--) { // Traverse nodes deeper into the trie. + var val = node[bytes[i]]; + + if (val == UNASSIGNED) { // Create new node. + node[bytes[i]] = NODE_START - this.decodeTables.length; + this.decodeTables.push(node = UNASSIGNED_NODE.slice(0)); } - this._readyDelayedCallbacks = []; + else if (val <= NODE_START) { // Existing node. + node = this.decodeTables[NODE_START - val]; + } + else + throw new Error("Overwrite byte in " + this.encodingName + ", addr: " + addr.toString(16)); } - /** - * Check whether Cluster is able to process commands - * - * @param {Function} callback - * @private - */ - readyCheck(callback) { - this.cluster("info", function (err, res) { - if (err) { - return callback(err); - } - if (typeof res !== "string") { - return callback(); - } - let state; - const lines = res.split("\r\n"); - for (let i = 0; i < lines.length; ++i) { - const parts = lines[i].split(":"); - if (parts[0] === "cluster_state") { - state = parts[1]; - break; + return node; +} + + +DBCSCodec.prototype._addDecodeChunk = function(chunk) { + // First element of chunk is the hex mbcs code where we start. + var curAddr = parseInt(chunk[0], 16); + + // Choose the decoding node where we'll write our chars. + var writeTable = this._getDecodeTrieNode(curAddr); + curAddr = curAddr & 0xFF; + + // Write all other elements of the chunk to the table. + for (var k = 1; k < chunk.length; k++) { + var part = chunk[k]; + if (typeof part === "string") { // String, write as-is. + for (var l = 0; l < part.length;) { + var code = part.charCodeAt(l++); + if (0xD800 <= code && code < 0xDC00) { // Decode surrogate + var codeTrail = part.charCodeAt(l++); + if (0xDC00 <= codeTrail && codeTrail < 0xE000) + writeTable[curAddr++] = 0x10000 + (code - 0xD800) * 0x400 + (codeTrail - 0xDC00); + else + throw new Error("Incorrect surrogate pair in " + this.encodingName + " at chunk " + chunk[0]); } + else if (0x0FF0 < code && code <= 0x0FFF) { // Character sequence (our own encoding used) + var len = 0xFFF - code + 2; + var seq = []; + for (var m = 0; m < len; m++) + seq.push(part.charCodeAt(l++)); // Simple variation: don't support surrogates or subsequences in seq. + + writeTable[curAddr++] = SEQ_START - this.decodeTableSeq.length; + this.decodeTableSeq.push(seq); + } + else + writeTable[curAddr++] = code; // Basic char } - if (state === "fail") { - debug("cluster state not ok (%s)", state); - callback(null, state); - } - else { - callback(); - } - }); + } + else if (typeof part === "number") { // Integer, meaning increasing sequence starting with prev character. + var charCode = writeTable[curAddr - 1] + 1; + for (var l = 0; l < part; l++) + writeTable[curAddr++] = charCode++; + } + else + throw new Error("Incorrect type '" + typeof part + "' given in " + this.encodingName + " at chunk " + chunk[0]); } - dnsLookup(hostname) { - return new Promise((resolve, reject) => { - this.options.dnsLookup(hostname, (err, address) => { - if (err) { - debug("failed to resolve hostname %s to IP: %s", hostname, err.message); - reject(err); - } - else { - debug("resolved hostname %s to IP %s", hostname, address); - resolve(address); - } - }); - }); + if (curAddr > 0xFF) + throw new Error("Incorrect chunk in " + this.encodingName + " at addr " + chunk[0] + ": too long" + curAddr); +} + +// Encoder helpers +DBCSCodec.prototype._getEncodeBucket = function(uCode) { + var high = uCode >> 8; // This could be > 0xFF because of astral characters. + if (this.encodeTable[high] === undefined) + this.encodeTable[high] = UNASSIGNED_NODE.slice(0); // Create bucket on demand. + return this.encodeTable[high]; +} + +DBCSCodec.prototype._setEncodeChar = function(uCode, dbcsCode) { + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + if (bucket[low] <= SEQ_START) + this.encodeTableSeq[SEQ_START-bucket[low]][DEF_CHAR] = dbcsCode; // There's already a sequence, set a single-char subsequence of it. + else if (bucket[low] == UNASSIGNED) + bucket[low] = dbcsCode; +} + +DBCSCodec.prototype._setEncodeSequence = function(seq, dbcsCode) { + + // Get the root of character tree according to first character of the sequence. + var uCode = seq[0]; + var bucket = this._getEncodeBucket(uCode); + var low = uCode & 0xFF; + + var node; + if (bucket[low] <= SEQ_START) { + // There's already a sequence with - use it. + node = this.encodeTableSeq[SEQ_START-bucket[low]]; } - /** - * Normalize startup nodes, and resolving hostnames to IPs. - * - * This process happens every time when #connect() is called since - * #startupNodes and DNS records may chanage. - * - * @private - * @returns {Promise} - */ - resolveStartupNodeHostnames() { - if (!Array.isArray(this.startupNodes) || this.startupNodes.length === 0) { - return Promise.reject(new Error("`startupNodes` should contain at least one node.")); - } - const startupNodes = util_1.normalizeNodeOptions(this.startupNodes); - const hostnames = util_1.getUniqueHostnamesFromOptions(startupNodes); - if (hostnames.length === 0) { - return Promise.resolve(startupNodes); + else { + // There was no sequence object - allocate a new one. + node = {}; + if (bucket[low] !== UNASSIGNED) node[DEF_CHAR] = bucket[low]; // If a char was set before - make it a single-char subsequence. + bucket[low] = SEQ_START - this.encodeTableSeq.length; + this.encodeTableSeq.push(node); + } + + // Traverse the character tree, allocating new nodes as needed. + for (var j = 1; j < seq.length-1; j++) { + var oldVal = node[uCode]; + if (typeof oldVal === 'object') + node = oldVal; + else { + node = node[uCode] = {} + if (oldVal !== undefined) + node[DEF_CHAR] = oldVal } - return Promise.all(hostnames.map((hostname) => this.dnsLookup(hostname))).then((ips) => { - const hostnameToIP = utils_2.zipMap(hostnames, ips); - return startupNodes.map((node) => hostnameToIP.has(node.host) - ? Object.assign({}, node, { host: hostnameToIP.get(node.host) }) - : node); - }); } + + // Set the leaf to given dbcsCode. + uCode = seq[seq.length-1]; + node[uCode] = dbcsCode; } -Object.getOwnPropertyNames(commander_1.default.prototype).forEach((name) => { - if (!Cluster.prototype.hasOwnProperty(name)) { - Cluster.prototype[name] = commander_1.default.prototype[name]; - } -}); -const scanCommands = [ - "sscan", - "hscan", - "zscan", - "sscanBuffer", - "hscanBuffer", - "zscanBuffer", -]; -scanCommands.forEach((command) => { - Cluster.prototype[command + "Stream"] = function (key, options) { - return new ScanStream_1.default(utils_1.defaults({ - objectMode: true, - key: key, - redis: this, - command: command, - }, options)); - }; -}); -__nccwpck_require__(14645).addTransactionSupport(Cluster.prototype); -exports.default = Cluster; +DBCSCodec.prototype._fillEncodeTable = function(nodeIdx, prefix, skipEncodeChars) { + var node = this.decodeTables[nodeIdx]; + for (var i = 0; i < 0x100; i++) { + var uCode = node[i]; + var mbCode = prefix + i; + if (skipEncodeChars[mbCode]) + continue; -/***/ }), + if (uCode >= 0) + this._setEncodeChar(uCode, mbCode); + else if (uCode <= NODE_START) + this._fillEncodeTable(NODE_START - uCode, mbCode << 8, skipEncodeChars); + else if (uCode <= SEQ_START) + this._setEncodeSequence(this.decodeTableSeq[SEQ_START - uCode], mbCode); + } +} -/***/ 94582: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils_1 = __nccwpck_require__(94832); -const net_1 = __nccwpck_require__(11631); -function getNodeKey(node) { - node.port = node.port || 6379; - node.host = node.host || "127.0.0.1"; - return node.host + ":" + node.port; -} -exports.getNodeKey = getNodeKey; -function nodeKeyToRedisOptions(nodeKey) { - const portIndex = nodeKey.lastIndexOf(":"); - if (portIndex === -1) { - throw new Error(`Invalid node key ${nodeKey}`); - } - return { - host: nodeKey.slice(0, portIndex), - port: Number(nodeKey.slice(portIndex + 1)), - }; +// == Encoder ================================================================== + +function DBCSEncoder(options, codec) { + // Encoder state + this.leadSurrogate = -1; + this.seqObj = undefined; + + // Static data + this.encodeTable = codec.encodeTable; + this.encodeTableSeq = codec.encodeTableSeq; + this.defaultCharSingleByte = codec.defCharSB; + this.gb18030 = codec.gb18030; } -exports.nodeKeyToRedisOptions = nodeKeyToRedisOptions; -function normalizeNodeOptions(nodes) { - return nodes.map((node) => { - const options = {}; - if (typeof node === "object") { - Object.assign(options, node); - } - else if (typeof node === "string") { - Object.assign(options, utils_1.parseURL(node)); - } - else if (typeof node === "number") { - options.port = node; + +DBCSEncoder.prototype.write = function(str) { + var newBuf = Buffer.alloc(str.length * (this.gb18030 ? 4 : 3)), + leadSurrogate = this.leadSurrogate, + seqObj = this.seqObj, nextChar = -1, + i = 0, j = 0; + + while (true) { + // 0. Get next character. + if (nextChar === -1) { + if (i == str.length) break; + var uCode = str.charCodeAt(i++); } else { - throw new Error("Invalid argument " + node); - } - if (typeof options.port === "string") { - options.port = parseInt(options.port, 10); + var uCode = nextChar; + nextChar = -1; } - // Cluster mode only support db 0 - delete options.db; - if (!options.port) { - options.port = 6379; + + // 1. Handle surrogates. + if (0xD800 <= uCode && uCode < 0xE000) { // Char is one of surrogates. + if (uCode < 0xDC00) { // We've got lead surrogate. + if (leadSurrogate === -1) { + leadSurrogate = uCode; + continue; + } else { + leadSurrogate = uCode; + // Double lead surrogate found. + uCode = UNASSIGNED; + } + } else { // We've got trail surrogate. + if (leadSurrogate !== -1) { + uCode = 0x10000 + (leadSurrogate - 0xD800) * 0x400 + (uCode - 0xDC00); + leadSurrogate = -1; + } else { + // Incomplete surrogate pair - only trail surrogate found. + uCode = UNASSIGNED; + } + + } } - if (!options.host) { - options.host = "127.0.0.1"; + else if (leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + nextChar = uCode; uCode = UNASSIGNED; // Write an error, then current char. + leadSurrogate = -1; } - return options; - }); -} -exports.normalizeNodeOptions = normalizeNodeOptions; -function getUniqueHostnamesFromOptions(nodes) { - const uniqueHostsMap = {}; - nodes.forEach((node) => { - uniqueHostsMap[node.host] = true; - }); - return Object.keys(uniqueHostsMap).filter((host) => !net_1.isIP(host)); -} -exports.getUniqueHostnamesFromOptions = getUniqueHostnamesFromOptions; + // 2. Convert uCode character. + var dbcsCode = UNASSIGNED; + if (seqObj !== undefined && uCode != UNASSIGNED) { // We are in the middle of the sequence + var resCode = seqObj[uCode]; + if (typeof resCode === 'object') { // Sequence continues. + seqObj = resCode; + continue; -/***/ }), + } else if (typeof resCode == 'number') { // Sequence finished. Write it. + dbcsCode = resCode; -/***/ 90803: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + } else if (resCode == undefined) { // Current character is not part of the sequence. -"use strict"; + // Try default character for this sequence + resCode = seqObj[DEF_CHAR]; + if (resCode !== undefined) { + dbcsCode = resCode; // Found. Write it. + nextChar = uCode; // Current character will be written too in the next iteration. -Object.defineProperty(exports, "__esModule", ({ value: true })); -const commands = __nccwpck_require__(98020); -const calculateSlot = __nccwpck_require__(48481); -const standard_as_callback_1 = __nccwpck_require__(91543); -const utils_1 = __nccwpck_require__(94832); -const lodash_1 = __nccwpck_require__(20961); -const promiseContainer_1 = __nccwpck_require__(71475); -/** - * Command instance - * - * It's rare that you need to create a Command instance yourself. - * - * @export - * @class Command - * - * @example - * ```js - * var infoCommand = new Command('info', null, function (err, result) { - * console.log('result', result); - * }); - * - * redis.sendCommand(infoCommand); - * - * // When no callback provided, Command instance will have a `promise` property, - * // which will resolve/reject with the result of the command. - * var getCommand = new Command('get', ['foo']); - * getCommand.promise.then(function (result) { - * console.log('result', result); - * }); - * ``` - * @see {@link Redis#sendCommand} which can send a Command instance to Redis - */ -class Command { - /** - * Creates an instance of Command. - * @param {string} name Command name - * @param {(Array)} [args=[]] An array of command arguments - * @param {ICommandOptions} [options={}] - * @param {CallbackFunction} [callback] The callback that handles the response. - * If omit, the response will be handled via Promise - * @memberof Command - */ - constructor(name, args = [], options = {}, callback) { - this.name = name; - this.transformed = false; - this.isCustomCommand = false; - this.inTransaction = false; - this.replyEncoding = options.replyEncoding; - this.errorStack = options.errorStack; - this.args = lodash_1.flatten(args); - this.callback = callback; - this.initPromise(); - if (options.keyPrefix) { - this._iterateKeys((key) => options.keyPrefix + key); - } - if (options.readOnly) { - this.isReadOnly = true; - } - } - static getFlagMap() { - if (!this.flagMap) { - this.flagMap = Object.keys(Command.FLAGS).reduce((map, flagName) => { - map[flagName] = {}; - Command.FLAGS[flagName].forEach((commandName) => { - map[flagName][commandName] = true; - }); - return map; - }, {}); - } - return this.flagMap; - } - /** - * Check whether the command has the flag - * - * @param {string} flagName - * @param {string} commandName - * @return {boolean} - */ - static checkFlag(flagName, commandName) { - return !!this.getFlagMap()[flagName][commandName]; - } - static setArgumentTransformer(name, func) { - this._transformer.argument[name] = func; - } - static setReplyTransformer(name, func) { - this._transformer.reply[name] = func; - } - initPromise() { - const Promise = promiseContainer_1.get(); - const promise = new Promise((resolve, reject) => { - if (!this.transformed) { - this.transformed = true; - const transformer = Command._transformer.argument[this.name]; - if (transformer) { - this.args = transformer(this.args); + } else { + // TODO: What if we have no default? (resCode == undefined) + // Then, we should write first char of the sequence as-is and try the rest recursively. + // Didn't do it for now because no encoding has this situation yet. + // Currently, just skip the sequence and write current char. } - this.stringifyArguments(); - } - this.resolve = this._convertValue(resolve); - if (this.errorStack) { - this.reject = (err) => { - reject(utils_1.optimizeErrorStack(err, this.errorStack, __dirname)); - }; - } - else { - this.reject = reject; } - }); - this.promise = standard_as_callback_1.default(promise, this.callback); - } - getSlot() { - if (typeof this.slot === "undefined") { - const key = this.getKeys()[0]; - this.slot = key == null ? null : calculateSlot(key); + seqObj = undefined; } - return this.slot; - } - getKeys() { - return this._iterateKeys(); - } - /** - * Iterate through the command arguments that are considered keys. - * - * @param {Function} [transform=(key) => key] The transformation that should be applied to - * each key. The transformations will persist. - * @returns {string[]} The keys of the command. - * @memberof Command - */ - _iterateKeys(transform = (key) => key) { - if (typeof this.keys === "undefined") { - this.keys = []; - if (commands.exists(this.name)) { - const keyIndexes = commands.getKeyIndexes(this.name, this.args); - for (const index of keyIndexes) { - this.args[index] = transform(this.args[index]); - this.keys.push(this.args[index]); + else if (uCode >= 0) { // Regular character + var subtable = this.encodeTable[uCode >> 8]; + if (subtable !== undefined) + dbcsCode = subtable[uCode & 0xFF]; + + if (dbcsCode <= SEQ_START) { // Sequence start + seqObj = this.encodeTableSeq[SEQ_START-dbcsCode]; + continue; + } + + if (dbcsCode == UNASSIGNED && this.gb18030) { + // Use GB18030 algorithm to find character(s) to write. + var idx = findIdx(this.gb18030.uChars, uCode); + if (idx != -1) { + var dbcsCode = this.gb18030.gbChars[idx] + (uCode - this.gb18030.uChars[idx]); + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 12600); dbcsCode = dbcsCode % 12600; + newBuf[j++] = 0x30 + Math.floor(dbcsCode / 1260); dbcsCode = dbcsCode % 1260; + newBuf[j++] = 0x81 + Math.floor(dbcsCode / 10); dbcsCode = dbcsCode % 10; + newBuf[j++] = 0x30 + dbcsCode; + continue; } } } - return this.keys; - } - /** - * Convert command to writable buffer or string - * - * @return {string|Buffer} - * @see {@link Redis#sendCommand} - * @public - */ - toWritable() { - let bufferMode = false; - for (const arg of this.args) { - if (arg instanceof Buffer) { - bufferMode = true; - break; - } + + // 3. Write dbcsCode character. + if (dbcsCode === UNASSIGNED) + dbcsCode = this.defaultCharSingleByte; + + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; } - let result; - const commandStr = "*" + - (this.args.length + 1) + - "\r\n$" + - Buffer.byteLength(this.name) + - "\r\n" + - this.name + - "\r\n"; - if (bufferMode) { - const buffers = new MixedBuffers(); - buffers.push(commandStr); - for (const arg of this.args) { - if (arg instanceof Buffer) { - if (arg.length === 0) { - buffers.push("$0\r\n\r\n"); - } - else { - buffers.push("$" + arg.length + "\r\n"); - buffers.push(arg); - buffers.push("\r\n"); - } - } - else { - buffers.push("$" + - Buffer.byteLength(arg) + - "\r\n" + - arg + - "\r\n"); - } - } - result = buffers.toBuffer(); + else if (dbcsCode < 0x10000) { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte } else { - result = commandStr; - for (const arg of this.args) { - result += - "$" + - Buffer.byteLength(arg) + - "\r\n" + - arg + - "\r\n"; - } - } - return result; - } - stringifyArguments() { - for (let i = 0; i < this.args.length; ++i) { - const arg = this.args[i]; - if (!(arg instanceof Buffer) && typeof arg !== "string") { - this.args[i] = utils_1.toArg(arg); - } + newBuf[j++] = dbcsCode >> 16; + newBuf[j++] = (dbcsCode >> 8) & 0xFF; + newBuf[j++] = dbcsCode & 0xFF; } } - /** - * Convert the value from buffer to the target encoding. - * - * @private - * @param {Function} resolve The resolve function of the Promise - * @returns {Function} A function to transform and resolve a value - * @memberof Command - */ - _convertValue(resolve) { - return (value) => { - try { - resolve(this.transformReply(value)); + + this.seqObj = seqObj; + this.leadSurrogate = leadSurrogate; + return newBuf.slice(0, j); +} + +DBCSEncoder.prototype.end = function() { + if (this.leadSurrogate === -1 && this.seqObj === undefined) + return; // All clean. Most often case. + + var newBuf = Buffer.alloc(10), j = 0; + + if (this.seqObj) { // We're in the sequence. + var dbcsCode = this.seqObj[DEF_CHAR]; + if (dbcsCode !== undefined) { // Write beginning of the sequence. + if (dbcsCode < 0x100) { + newBuf[j++] = dbcsCode; } - catch (err) { - this.reject(err); + else { + newBuf[j++] = dbcsCode >> 8; // high byte + newBuf[j++] = dbcsCode & 0xFF; // low byte } - return this.promise; - }; - } - /** - * Convert buffer/buffer[] to string/string[], - * and apply reply transformer. - * - * @memberof Command - */ - transformReply(result) { - if (this.replyEncoding) { - result = utils_1.convertBufferToString(result, this.replyEncoding); - } - const transformer = Command._transformer.reply[this.name]; - if (transformer) { - result = transformer(result); + } else { + // See todo above. } - return result; + this.seqObj = undefined; + } + + if (this.leadSurrogate !== -1) { + // Incomplete surrogate pair - only lead surrogate found. + newBuf[j++] = this.defaultCharSingleByte; + this.leadSurrogate = -1; } + + return newBuf.slice(0, j); } -exports.default = Command; -Command.FLAGS = { - VALID_IN_SUBSCRIBER_MODE: [ - "subscribe", - "psubscribe", - "unsubscribe", - "punsubscribe", - "ping", - "quit", - ], - VALID_IN_MONITOR_MODE: ["monitor", "auth"], - ENTER_SUBSCRIBER_MODE: ["subscribe", "psubscribe"], - EXIT_SUBSCRIBER_MODE: ["unsubscribe", "punsubscribe"], - WILL_DISCONNECT: ["quit"], -}; -Command._transformer = { - argument: {}, - reply: {}, -}; -const msetArgumentTransformer = function (args) { - if (args.length === 1) { - if (typeof Map !== "undefined" && args[0] instanceof Map) { - return utils_1.convertMapToArray(args[0]); - } - if (typeof args[0] === "object" && args[0] !== null) { - return utils_1.convertObjectToArray(args[0]); + +// Export for testing +DBCSEncoder.prototype.findIdx = findIdx; + + +// == Decoder ================================================================== + +function DBCSDecoder(options, codec) { + // Decoder state + this.nodeIdx = 0; + this.prevBuf = Buffer.alloc(0); + + // Static data + this.decodeTables = codec.decodeTables; + this.decodeTableSeq = codec.decodeTableSeq; + this.defaultCharUnicode = codec.defaultCharUnicode; + this.gb18030 = codec.gb18030; +} + +DBCSDecoder.prototype.write = function(buf) { + var newBuf = Buffer.alloc(buf.length*2), + nodeIdx = this.nodeIdx, + prevBuf = this.prevBuf, prevBufOffset = this.prevBuf.length, + seqStart = -this.prevBuf.length, // idx of the start of current parsed sequence. + uCode; + + if (prevBufOffset > 0) // Make prev buf overlap a little to make it easier to slice later. + prevBuf = Buffer.concat([prevBuf, buf.slice(0, 10)]); + + for (var i = 0, j = 0; i < buf.length; i++) { + var curByte = (i >= 0) ? buf[i] : prevBuf[i + prevBufOffset]; + + // Lookup in current trie node. + var uCode = this.decodeTables[nodeIdx][curByte]; + + if (uCode >= 0) { + // Normal character, just use it. } - } - return args; -}; -Command.setArgumentTransformer("mset", msetArgumentTransformer); -Command.setArgumentTransformer("msetnx", msetArgumentTransformer); -Command.setArgumentTransformer("hmset", function (args) { - if (args.length === 2) { - if (typeof Map !== "undefined" && args[1] instanceof Map) { - return [args[0]].concat(utils_1.convertMapToArray(args[1])); + else if (uCode === UNASSIGNED) { // Unknown char. + // TODO: Callback with seq. + //var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + i = seqStart; // Try to parse again, after skipping first byte of the sequence ('i' will be incremented by 'for' cycle). + uCode = this.defaultCharUnicode.charCodeAt(0); } - if (typeof args[1] === "object" && args[1] !== null) { - return [args[0]].concat(utils_1.convertObjectToArray(args[1])); + else if (uCode === GB18030_CODE) { + var curSeq = (seqStart >= 0) ? buf.slice(seqStart, i+1) : prevBuf.slice(seqStart + prevBufOffset, i+1 + prevBufOffset); + var ptr = (curSeq[0]-0x81)*12600 + (curSeq[1]-0x30)*1260 + (curSeq[2]-0x81)*10 + (curSeq[3]-0x30); + var idx = findIdx(this.gb18030.gbChars, ptr); + uCode = this.gb18030.uChars[idx] + ptr - this.gb18030.gbChars[idx]; } - } - return args; -}); -Command.setReplyTransformer("hgetall", function (result) { - if (Array.isArray(result)) { - const obj = {}; - for (let i = 0; i < result.length; i += 2) { - obj[result[i]] = result[i + 1]; + else if (uCode <= NODE_START) { // Go to next trie node. + nodeIdx = NODE_START - uCode; + continue; } - return obj; - } - return result; -}); -Command.setArgumentTransformer("hset", function (args) { - if (args.length === 2) { - if (typeof Map !== "undefined" && args[1] instanceof Map) { - return [args[0]].concat(utils_1.convertMapToArray(args[1])); + else if (uCode <= SEQ_START) { // Output a sequence of chars. + var seq = this.decodeTableSeq[SEQ_START - uCode]; + for (var k = 0; k < seq.length - 1; k++) { + uCode = seq[k]; + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + } + uCode = seq[seq.length-1]; } - if (typeof args[1] === "object" && args[1] !== null) { - return [args[0]].concat(utils_1.convertObjectToArray(args[1])); + else + throw new Error("iconv-lite internal error: invalid decoding table value " + uCode + " at " + nodeIdx + "/" + curByte); + + // Write the character to buffer, handling higher planes using surrogate pair. + if (uCode > 0xFFFF) { + uCode -= 0x10000; + var uCodeLead = 0xD800 + Math.floor(uCode / 0x400); + newBuf[j++] = uCodeLead & 0xFF; + newBuf[j++] = uCodeLead >> 8; + + uCode = 0xDC00 + uCode % 0x400; } + newBuf[j++] = uCode & 0xFF; + newBuf[j++] = uCode >> 8; + + // Reset trie node. + nodeIdx = 0; seqStart = i+1; } - return args; -}); -class MixedBuffers { - constructor() { - this.length = 0; - this.items = []; - } - push(x) { - this.length += Buffer.byteLength(x); - this.items.push(x); + + this.nodeIdx = nodeIdx; + this.prevBuf = (seqStart >= 0) ? buf.slice(seqStart) : prevBuf.slice(seqStart + prevBufOffset); + return newBuf.slice(0, j).toString('ucs2'); +} + +DBCSDecoder.prototype.end = function() { + var ret = ''; + + // Try to parse all remaining chars. + while (this.prevBuf.length > 0) { + // Skip 1 character in the buffer. + ret += this.defaultCharUnicode; + var buf = this.prevBuf.slice(1); + + // Parse remaining as usual. + this.prevBuf = Buffer.alloc(0); + this.nodeIdx = 0; + if (buf.length > 0) + ret += this.write(buf); } - toBuffer() { - const result = Buffer.allocUnsafe(this.length); - let offset = 0; - for (const item of this.items) { - const length = Buffer.byteLength(item); - Buffer.isBuffer(item) - ? item.copy(result, offset) - : result.write(item, offset, length); - offset += length; - } - return result; + + this.nodeIdx = 0; + return ret; +} + +// Binary search for GB18030. Returns largest i such that table[i] <= val. +function findIdx(table, val) { + if (table[0] > val) + return -1; + + var l = 0, r = table.length; + while (l < r-1) { // always table[l] <= val < table[r] + var mid = l + Math.floor((r-l+1)/2); + if (table[mid] <= val) + l = mid; + else + r = mid; } + return l; } + /***/ }), -/***/ 33642: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 91386: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const lodash_1 = __nccwpck_require__(20961); -const command_1 = __nccwpck_require__(90803); -const script_1 = __nccwpck_require__(88540); -const PromiseContainer = __nccwpck_require__(71475); -const standard_as_callback_1 = __nccwpck_require__(91543); -const autoPipelining_1 = __nccwpck_require__(97873); -const DROP_BUFFER_SUPPORT_ERROR = "*Buffer methods are not available " + - 'because "dropBufferSupport" option is enabled.' + - "Refer to https://github.com/luin/ioredis/wiki/Improve-Performance for more details."; -/** - * Commander - * - * This is the base class of Redis, Redis.Cluster and Pipeline - * - * @param {boolean} [options.showFriendlyErrorStack=false] - Whether to show a friendly error stack. - * Will decrease the performance significantly. - * @constructor - */ -function Commander() { - this.options = lodash_1.defaults({}, this.options || {}, { - showFriendlyErrorStack: false, - }); - this.scriptsSet = {}; -} -exports.default = Commander; -const commands = __nccwpck_require__(98020).list.filter(function (command) { - return command !== "monitor"; -}); -commands.push("sentinel"); -/** - * Return supported builtin commands - * - * @return {string[]} command list - * @public - */ -Commander.prototype.getBuiltinCommands = function () { - return commands.slice(0); -}; -/** - * Create a builtin command - * - * @param {string} commandName - command name - * @return {object} functions - * @public - */ -Commander.prototype.createBuiltinCommand = function (commandName) { - return { - string: generateFunction(commandName, "utf8"), - buffer: generateFunction(commandName, null), - }; -}; -commands.forEach(function (commandName) { - Commander.prototype[commandName] = generateFunction(commandName, "utf8"); - Commander.prototype[commandName + "Buffer"] = generateFunction(commandName, null); -}); -Commander.prototype.call = generateFunction("utf8"); -Commander.prototype.callBuffer = generateFunction(null); -// eslint-disable-next-line @typescript-eslint/camelcase -Commander.prototype.send_command = Commander.prototype.call; -/** - * Define a custom command using lua script - * - * @param {string} name - the command name - * @param {object} definition - * @param {string} definition.lua - the lua code - * @param {number} [definition.numberOfKeys=null] - the number of keys. - * @param {boolean} [definition.readOnly=false] - force this script to be readonly so it executes on slaves as well. - * If omit, you have to pass the number of keys as the first argument every time you invoke the command - */ -Commander.prototype.defineCommand = function (name, definition) { - const script = new script_1.default(definition.lua, definition.numberOfKeys, this.options.keyPrefix, definition.readOnly); - this.scriptsSet[name] = script; - this[name] = generateScriptingFunction(name, script, "utf8"); - this[name + "Buffer"] = generateScriptingFunction(name, script, null); + +// Description of supported double byte encodings and aliases. +// Tables are not require()-d until they are needed to speed up library load. +// require()-s are direct to support Browserify. + +module.exports = { + + // == Japanese/ShiftJIS ==================================================== + // All japanese encodings are based on JIS X set of standards: + // JIS X 0201 - Single-byte encoding of ASCII + ¥ + Kana chars at 0xA1-0xDF. + // JIS X 0208 - Main set of 6879 characters, placed in 94x94 plane, to be encoded by 2 bytes. + // Has several variations in 1978, 1983, 1990 and 1997. + // JIS X 0212 - Supplementary plane of 6067 chars in 94x94 plane. 1990. Effectively dead. + // JIS X 0213 - Extension and modern replacement of 0208 and 0212. Total chars: 11233. + // 2 planes, first is superset of 0208, second - revised 0212. + // Introduced in 2000, revised 2004. Some characters are in Unicode Plane 2 (0x2xxxx) + + // Byte encodings are: + // * Shift_JIS: Compatible with 0201, uses not defined chars in top half as lead bytes for double-byte + // encoding of 0208. Lead byte ranges: 0x81-0x9F, 0xE0-0xEF; Trail byte ranges: 0x40-0x7E, 0x80-0x9E, 0x9F-0xFC. + // Windows CP932 is a superset of Shift_JIS. Some companies added more chars, notably KDDI. + // * EUC-JP: Up to 3 bytes per character. Used mostly on *nixes. + // 0x00-0x7F - lower part of 0201 + // 0x8E, 0xA1-0xDF - upper part of 0201 + // (0xA1-0xFE)x2 - 0208 plane (94x94). + // 0x8F, (0xA1-0xFE)x2 - 0212 plane (94x94). + // * JIS X 208: 7-bit, direct encoding of 0208. Byte ranges: 0x21-0x7E (94 values). Uncommon. + // Used as-is in ISO2022 family. + // * ISO2022-JP: Stateful encoding, with escape sequences to switch between ASCII, + // 0201-1976 Roman, 0208-1978, 0208-1983. + // * ISO2022-JP-1: Adds esc seq for 0212-1990. + // * ISO2022-JP-2: Adds esc seq for GB2313-1980, KSX1001-1992, ISO8859-1, ISO8859-7. + // * ISO2022-JP-3: Adds esc seq for 0201-1976 Kana set, 0213-2000 Planes 1, 2. + // * ISO2022-JP-2004: Adds 0213-2004 Plane 1. + // + // After JIS X 0213 appeared, Shift_JIS-2004, EUC-JISX0213 and ISO2022-JP-2004 followed, with just changing the planes. + // + // Overall, it seems that it's a mess :( http://www8.plala.or.jp/tkubota1/unicode-symbols-map2.html + + 'shiftjis': { + type: '_dbcs', + table: function() { return __nccwpck_require__(64108) }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + encodeSkipVals: [{from: 0xED40, to: 0xF940}], + }, + 'csshiftjis': 'shiftjis', + 'mskanji': 'shiftjis', + 'sjis': 'shiftjis', + 'windows31j': 'shiftjis', + 'ms31j': 'shiftjis', + 'xsjis': 'shiftjis', + 'windows932': 'shiftjis', + 'ms932': 'shiftjis', + '932': 'shiftjis', + 'cp932': 'shiftjis', + + 'eucjp': { + type: '_dbcs', + table: function() { return __nccwpck_require__(72417) }, + encodeAdd: {'\u00a5': 0x5C, '\u203E': 0x7E}, + }, + + // TODO: KDDI extension to Shift_JIS + // TODO: IBM CCSID 942 = CP932, but F0-F9 custom chars and other char changes. + // TODO: IBM CCSID 943 = Shift_JIS = CP932 with original Shift_JIS lower 128 chars. + + + // == Chinese/GBK ========================================================== + // http://en.wikipedia.org/wiki/GBK + // We mostly implement W3C recommendation: https://www.w3.org/TR/encoding/#gbk-encoder + + // Oldest GB2312 (1981, ~7600 chars) is a subset of CP936 + 'gb2312': 'cp936', + 'gb231280': 'cp936', + 'gb23121980': 'cp936', + 'csgb2312': 'cp936', + 'csiso58gb231280': 'cp936', + 'euccn': 'cp936', + + // Microsoft's CP936 is a subset and approximation of GBK. + 'windows936': 'cp936', + 'ms936': 'cp936', + '936': 'cp936', + 'cp936': { + type: '_dbcs', + table: function() { return __nccwpck_require__(97803) }, + }, + + // GBK (~22000 chars) is an extension of CP936 that added user-mapped chars and some other. + 'gbk': { + type: '_dbcs', + table: function() { return __nccwpck_require__(97803).concat(__nccwpck_require__(37419)) }, + }, + 'xgbk': 'gbk', + 'isoir58': 'gbk', + + // GB18030 is an algorithmic extension of GBK. + // Main source: https://www.w3.org/TR/encoding/#gbk-encoder + // http://icu-project.org/docs/papers/gb18030.html + // http://source.icu-project.org/repos/icu/data/trunk/charset/data/xml/gb-18030-2000.xml + // http://www.khngai.com/chinese/charmap/tblgbk.php?page=0 + 'gb18030': { + type: '_dbcs', + table: function() { return __nccwpck_require__(97803).concat(__nccwpck_require__(37419)) }, + gb18030: function() { return __nccwpck_require__(86351) }, + encodeSkipVals: [0x80], + encodeAdd: {'€': 0xA2E3}, + }, + + 'chinese': 'gb18030', + + + // == Korean =============================================================== + // EUC-KR, KS_C_5601 and KS X 1001 are exactly the same. + 'windows949': 'cp949', + 'ms949': 'cp949', + '949': 'cp949', + 'cp949': { + type: '_dbcs', + table: function() { return __nccwpck_require__(87013) }, + }, + + 'cseuckr': 'cp949', + 'csksc56011987': 'cp949', + 'euckr': 'cp949', + 'isoir149': 'cp949', + 'korean': 'cp949', + 'ksc56011987': 'cp949', + 'ksc56011989': 'cp949', + 'ksc5601': 'cp949', + + + // == Big5/Taiwan/Hong Kong ================================================ + // There are lots of tables for Big5 and cp950. Please see the following links for history: + // http://moztw.org/docs/big5/ http://www.haible.de/bruno/charsets/conversion-tables/Big5.html + // Variations, in roughly number of defined chars: + // * Windows CP 950: Microsoft variant of Big5. Canonical: http://www.unicode.org/Public/MAPPINGS/VENDORS/MICSFT/WINDOWS/CP950.TXT + // * Windows CP 951: Microsoft variant of Big5-HKSCS-2001. Seems to be never public. http://me.abelcheung.org/articles/research/what-is-cp951/ + // * Big5-2003 (Taiwan standard) almost superset of cp950. + // * Unicode-at-on (UAO) / Mozilla 1.8. Falling out of use on the Web. Not supported by other browsers. + // * Big5-HKSCS (-2001, -2004, -2008). Hong Kong standard. + // many unicode code points moved from PUA to Supplementary plane (U+2XXXX) over the years. + // Plus, it has 4 combining sequences. + // Seems that Mozilla refused to support it for 10 yrs. https://bugzilla.mozilla.org/show_bug.cgi?id=162431 https://bugzilla.mozilla.org/show_bug.cgi?id=310299 + // because big5-hkscs is the only encoding to include astral characters in non-algorithmic way. + // Implementations are not consistent within browsers; sometimes labeled as just big5. + // MS Internet Explorer switches from big5 to big5-hkscs when a patch applied. + // Great discussion & recap of what's going on https://bugzilla.mozilla.org/show_bug.cgi?id=912470#c31 + // In the encoder, it might make sense to support encoding old PUA mappings to Big5 bytes seq-s. + // Official spec: http://www.ogcio.gov.hk/en/business/tech_promotion/ccli/terms/doc/2003cmp_2008.txt + // http://www.ogcio.gov.hk/tc/business/tech_promotion/ccli/terms/doc/hkscs-2008-big5-iso.txt + // + // Current understanding of how to deal with Big5(-HKSCS) is in the Encoding Standard, http://encoding.spec.whatwg.org/#big5-encoder + // Unicode mapping (http://www.unicode.org/Public/MAPPINGS/OBSOLETE/EASTASIA/OTHER/BIG5.TXT) is said to be wrong. + + 'windows950': 'cp950', + 'ms950': 'cp950', + '950': 'cp950', + 'cp950': { + type: '_dbcs', + table: function() { return __nccwpck_require__(33104) }, + }, + + // Big5 has many variations and is an extension of cp950. We use Encoding Standard's as a consensus. + 'big5': 'big5hkscs', + 'big5hkscs': { + type: '_dbcs', + table: function() { return __nccwpck_require__(33104).concat(__nccwpck_require__(43612)) }, + encodeSkipVals: [0xa2cc], + }, + + 'cnbig5': 'big5hkscs', + 'csbig5': 'big5hkscs', + 'xxbig5': 'big5hkscs', }; -/** - * Send a command - * - * @abstract - * @public - */ -Commander.prototype.sendCommand = function () { }; -function generateFunction(_commandName, _encoding) { - if (typeof _encoding === "undefined") { - _encoding = _commandName; - _commandName = null; - } - return function (...args) { - const commandName = _commandName || args.shift(); - let callback = args[args.length - 1]; - if (typeof callback === "function") { - args.pop(); - } - else { - callback = undefined; - } - const options = { - errorStack: this.options.showFriendlyErrorStack - ? new Error().stack - : undefined, - keyPrefix: this.options.keyPrefix, - replyEncoding: _encoding, - }; - if (this.options.dropBufferSupport && !_encoding) { - return standard_as_callback_1.default(PromiseContainer.get().reject(new Error(DROP_BUFFER_SUPPORT_ERROR)), callback); - } - // No auto pipeline, use regular command sending - if (!autoPipelining_1.shouldUseAutoPipelining(this, commandName)) { - return this.sendCommand(new command_1.default(commandName, args, options, callback)); - } - // Create a new pipeline and make sure it's scheduled - return autoPipelining_1.executeWithAutoPipelining(this, commandName, args, callback); - }; -} -function generateScriptingFunction(name, script, encoding) { - return function () { - let length = arguments.length; - const lastArgIndex = length - 1; - let callback = arguments[lastArgIndex]; - if (typeof callback !== "function") { - callback = undefined; - } - else { - length = lastArgIndex; - } - const args = new Array(length); - for (let i = 0; i < length; i++) { - args[i] = arguments[i]; - } - let options; - if (this.options.dropBufferSupport) { - if (!encoding) { - return standard_as_callback_1.default(PromiseContainer.get().reject(new Error(DROP_BUFFER_SUPPORT_ERROR)), callback); - } - options = { replyEncoding: null }; - } - else { - options = { replyEncoding: encoding }; - } - if (this.options.showFriendlyErrorStack) { - options.errorStack = new Error().stack; - } - // No auto pipeline, use regular command sending - if (!autoPipelining_1.shouldUseAutoPipelining(this, name)) { - return script.execute(this, args, options, callback); - } - // Create a new pipeline and make sure it's scheduled - return autoPipelining_1.executeWithAutoPipelining(this, name, args, callback); - }; + + +/***/ }), + +/***/ 82733: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + + +// Update this array if you add/rename/remove files in this directory. +// We support Browserify by skipping automatic module discovery and requiring modules directly. +var modules = [ + __nccwpck_require__(12376), + __nccwpck_require__(11155), + __nccwpck_require__(51644), + __nccwpck_require__(26657), + __nccwpck_require__(41080), + __nccwpck_require__(21012), + __nccwpck_require__(39695), + __nccwpck_require__(91386), +]; + +// Put all encoding/alias/codec definitions to single object and export it. +for (var i = 0; i < modules.length; i++) { + var module = modules[i]; + for (var enc in module) + if (Object.prototype.hasOwnProperty.call(module, enc)) + exports[enc] = module[enc]; } -/***/ }), +/***/ }), + +/***/ 12376: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + +var Buffer = __nccwpck_require__(15118).Buffer; + +// Export Node.js internal encodings. + +module.exports = { + // Encodings + utf8: { type: "_internal", bomAware: true}, + cesu8: { type: "_internal", bomAware: true}, + unicode11utf8: "utf8", + + ucs2: { type: "_internal", bomAware: true}, + utf16le: "ucs2", + + binary: { type: "_internal" }, + base64: { type: "_internal" }, + hex: { type: "_internal" }, -/***/ 72712: -/***/ ((__unused_webpack_module, exports) => { + // Codec. + _internal: InternalCodec, +}; -"use strict"; +//------------------------------------------------------------------------------ -Object.defineProperty(exports, "__esModule", ({ value: true })); -class AbstractConnector { - constructor() { - this.connecting = false; - } - check(info) { - return true; - } - disconnect() { - this.connecting = false; - if (this.stream) { - this.stream.end(); +function InternalCodec(codecOptions, iconv) { + this.enc = codecOptions.encodingName; + this.bomAware = codecOptions.bomAware; + + if (this.enc === "base64") + this.encoder = InternalEncoderBase64; + else if (this.enc === "cesu8") { + this.enc = "utf8"; // Use utf8 for decoding. + this.encoder = InternalEncoderCesu8; + + // Add decoder for versions of Node not supporting CESU-8 + if (Buffer.from('eda0bdedb2a9', 'hex').toString() !== '💩') { + this.decoder = InternalDecoderCesu8; + this.defaultCharUnicode = iconv.defaultCharUnicode; } } } -exports.default = AbstractConnector; +InternalCodec.prototype.encoder = InternalEncoder; +InternalCodec.prototype.decoder = InternalDecoder; -/***/ }), +//------------------------------------------------------------------------------ -/***/ 72225: -/***/ ((__unused_webpack_module, exports) => { +// We use node.js internal decoder. Its signature is the same as ours. +var StringDecoder = __nccwpck_require__(24304).StringDecoder; -"use strict"; +if (!StringDecoder.prototype.end) // Node v0.8 doesn't have this method. + StringDecoder.prototype.end = function() {}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -function isSentinelEql(a, b) { - return ((a.host || "127.0.0.1") === (b.host || "127.0.0.1") && - (a.port || 26379) === (b.port || 26379)); + +function InternalDecoder(options, codec) { + StringDecoder.call(this, codec.enc); } -class SentinelIterator { - constructor(sentinels) { - this.cursor = 0; - this.sentinels = sentinels.slice(0); - } - next() { - const done = this.cursor >= this.sentinels.length; - return { done, value: done ? undefined : this.sentinels[this.cursor++] }; - } - reset(moveCurrentEndpointToFirst) { - if (moveCurrentEndpointToFirst && - this.sentinels.length > 1 && - this.cursor !== 1) { - this.sentinels.unshift(...this.sentinels.splice(this.cursor - 1)); - } - this.cursor = 0; - } - add(sentinel) { - for (let i = 0; i < this.sentinels.length; i++) { - if (isSentinelEql(sentinel, this.sentinels[i])) { - return false; - } - } - this.sentinels.push(sentinel); - return true; - } - toString() { - return `${JSON.stringify(this.sentinels)} @${this.cursor}`; - } + +InternalDecoder.prototype = StringDecoder.prototype; + + +//------------------------------------------------------------------------------ +// Encoder is mostly trivial + +function InternalEncoder(options, codec) { + this.enc = codec.enc; } -exports.default = SentinelIterator; +InternalEncoder.prototype.write = function(str) { + return Buffer.from(str, this.enc); +} -/***/ }), +InternalEncoder.prototype.end = function() { +} -/***/ 10379: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -"use strict"; +//------------------------------------------------------------------------------ +// Except base64 encoder, which must keep its state. -Object.defineProperty(exports, "__esModule", ({ value: true })); -const net_1 = __nccwpck_require__(11631); -const utils_1 = __nccwpck_require__(94832); -const tls_1 = __nccwpck_require__(4016); -const StandaloneConnector_1 = __nccwpck_require__(8774); -const SentinelIterator_1 = __nccwpck_require__(72225); -exports.SentinelIterator = SentinelIterator_1.default; -const AbstractConnector_1 = __nccwpck_require__(72712); -const redis_1 = __nccwpck_require__(83609); -const debug = utils_1.Debug("SentinelConnector"); -class SentinelConnector extends AbstractConnector_1.default { - constructor(options) { - super(); - this.options = options; - if (!this.options.sentinels.length) { - throw new Error("Requires at least one sentinel to connect to."); - } - if (!this.options.name) { - throw new Error("Requires the name of master."); - } - this.sentinelIterator = new SentinelIterator_1.default(this.options.sentinels); - } - check(info) { - const roleMatches = !info.role || this.options.role === info.role; - if (!roleMatches) { - debug("role invalid, expected %s, but got %s", this.options.role, info.role); - // Start from the next item. - // Note that `reset` will move the cursor to the previous element, - // so we advance two steps here. - this.sentinelIterator.next(); - this.sentinelIterator.next(); - this.sentinelIterator.reset(true); - } - return roleMatches; - } - connect(eventEmitter) { - this.connecting = true; - this.retryAttempts = 0; - let lastError; - const connectToNext = () => new Promise((resolve, reject) => { - const endpoint = this.sentinelIterator.next(); - if (endpoint.done) { - this.sentinelIterator.reset(false); - const retryDelay = typeof this.options.sentinelRetryStrategy === "function" - ? this.options.sentinelRetryStrategy(++this.retryAttempts) - : null; - let errorMsg = typeof retryDelay !== "number" - ? "All sentinels are unreachable and retry is disabled." - : `All sentinels are unreachable. Retrying from scratch after ${retryDelay}ms.`; - if (lastError) { - errorMsg += ` Last error: ${lastError.message}`; - } - debug(errorMsg); - const error = new Error(errorMsg); - if (typeof retryDelay === "number") { - setTimeout(() => { - resolve(connectToNext()); - }, retryDelay); - eventEmitter("error", error); - } - else { - reject(error); - } - return; - } - this.resolve(endpoint.value, (err, resolved) => { - if (!this.connecting) { - reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); - return; - } - if (resolved) { - debug("resolved: %s:%s", resolved.host, resolved.port); - if (this.options.enableTLSForSentinelMode && this.options.tls) { - Object.assign(resolved, this.options.tls); - this.stream = tls_1.connect(resolved); - } - else { - this.stream = net_1.createConnection(resolved); - } - this.sentinelIterator.reset(true); - resolve(this.stream); - } - else { - const endpointAddress = endpoint.value.host + ":" + endpoint.value.port; - const errorMsg = err - ? "failed to connect to sentinel " + - endpointAddress + - " because " + - err.message - : "connected to sentinel " + - endpointAddress + - " successfully, but got an invalid reply: " + - resolved; - debug(errorMsg); - eventEmitter("sentinelError", new Error(errorMsg)); - if (err) { - lastError = err; - } - resolve(connectToNext()); - } - }); - }); - return connectToNext(); - } - updateSentinels(client, callback) { - if (!this.options.updateSentinels) { - return callback(null); - } - client.sentinel("sentinels", this.options.name, (err, result) => { - if (err) { - client.disconnect(); - return callback(err); - } - if (!Array.isArray(result)) { - return callback(null); - } - result - .map(utils_1.packObject) - .forEach((sentinel) => { - const flags = sentinel.flags ? sentinel.flags.split(",") : []; - if (flags.indexOf("disconnected") === -1 && - sentinel.ip && - sentinel.port) { - const endpoint = this.sentinelNatResolve(addressResponseToAddress(sentinel)); - if (this.sentinelIterator.add(endpoint)) { - debug("adding sentinel %s:%s", endpoint.host, endpoint.port); - } - } - }); - debug("Updated internal sentinels: %s", this.sentinelIterator); - callback(null); - }); - } - resolveMaster(client, callback) { - client.sentinel("get-master-addr-by-name", this.options.name, (err, result) => { - if (err) { - client.disconnect(); - return callback(err); - } - this.updateSentinels(client, (err) => { - client.disconnect(); - if (err) { - return callback(err); - } - callback(null, this.sentinelNatResolve(Array.isArray(result) - ? { host: result[0], port: Number(result[1]) } - : null)); - }); - }); - } - resolveSlave(client, callback) { - client.sentinel("slaves", this.options.name, (err, result) => { - client.disconnect(); - if (err) { - return callback(err); - } - if (!Array.isArray(result)) { - return callback(null, null); - } - const availableSlaves = result - .map(utils_1.packObject) - .filter((slave) => slave.flags && !slave.flags.match(/(disconnected|s_down|o_down)/)); - callback(null, this.sentinelNatResolve(selectPreferredSentinel(availableSlaves, this.options.preferredSlaves))); - }); - } - sentinelNatResolve(item) { - if (!item || !this.options.natMap) - return item; - return this.options.natMap[`${item.host}:${item.port}`] || item; - } - resolve(endpoint, callback) { - const client = new redis_1.default({ - port: endpoint.port || 26379, - host: endpoint.host, - username: this.options.sentinelUsername || null, - password: this.options.sentinelPassword || null, - family: endpoint.family || - (StandaloneConnector_1.isIIpcConnectionOptions(this.options) - ? undefined - : this.options.family), - tls: this.options.sentinelTLS, - retryStrategy: null, - enableReadyCheck: false, - connectTimeout: this.options.connectTimeout, - dropBufferSupport: true, - }); - // ignore the errors since resolve* methods will handle them - client.on("error", noop); - if (this.options.role === "slave") { - this.resolveSlave(client, callback); +function InternalEncoderBase64(options, codec) { + this.prevStr = ''; +} + +InternalEncoderBase64.prototype.write = function(str) { + str = this.prevStr + str; + var completeQuads = str.length - (str.length % 4); + this.prevStr = str.slice(completeQuads); + str = str.slice(0, completeQuads); + + return Buffer.from(str, "base64"); +} + +InternalEncoderBase64.prototype.end = function() { + return Buffer.from(this.prevStr, "base64"); +} + + +//------------------------------------------------------------------------------ +// CESU-8 encoder is also special. + +function InternalEncoderCesu8(options, codec) { +} + +InternalEncoderCesu8.prototype.write = function(str) { + var buf = Buffer.alloc(str.length * 3), bufIdx = 0; + for (var i = 0; i < str.length; i++) { + var charCode = str.charCodeAt(i); + // Naive implementation, but it works because CESU-8 is especially easy + // to convert from UTF-16 (which all JS strings are encoded in). + if (charCode < 0x80) + buf[bufIdx++] = charCode; + else if (charCode < 0x800) { + buf[bufIdx++] = 0xC0 + (charCode >>> 6); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); } - else { - this.resolveMaster(client, callback); + else { // charCode will always be < 0x10000 in javascript. + buf[bufIdx++] = 0xE0 + (charCode >>> 12); + buf[bufIdx++] = 0x80 + ((charCode >>> 6) & 0x3f); + buf[bufIdx++] = 0x80 + (charCode & 0x3f); } } + return buf.slice(0, bufIdx); } -exports.default = SentinelConnector; -function selectPreferredSentinel(availableSlaves, preferredSlaves) { - if (availableSlaves.length === 0) { - return null; - } - let selectedSlave; - if (typeof preferredSlaves === "function") { - selectedSlave = preferredSlaves(availableSlaves); - } - else if (preferredSlaves !== null && typeof preferredSlaves === "object") { - const preferredSlavesArray = Array.isArray(preferredSlaves) - ? preferredSlaves - : [preferredSlaves]; - // sort by priority - preferredSlavesArray.sort((a, b) => { - // default the priority to 1 - if (!a.prio) { - a.prio = 1; - } - if (!b.prio) { - b.prio = 1; - } - // lowest priority first - if (a.prio < b.prio) { - return -1; + +InternalEncoderCesu8.prototype.end = function() { +} + +//------------------------------------------------------------------------------ +// CESU-8 decoder is not implemented in Node v4.0+ + +function InternalDecoderCesu8(options, codec) { + this.acc = 0; + this.contBytes = 0; + this.accBytes = 0; + this.defaultCharUnicode = codec.defaultCharUnicode; +} + +InternalDecoderCesu8.prototype.write = function(buf) { + var acc = this.acc, contBytes = this.contBytes, accBytes = this.accBytes, + res = ''; + for (var i = 0; i < buf.length; i++) { + var curByte = buf[i]; + if ((curByte & 0xC0) !== 0x80) { // Leading byte + if (contBytes > 0) { // Previous code is invalid + res += this.defaultCharUnicode; + contBytes = 0; } - if (a.prio > b.prio) { - return 1; + + if (curByte < 0x80) { // Single-byte code + res += String.fromCharCode(curByte); + } else if (curByte < 0xE0) { // Two-byte code + acc = curByte & 0x1F; + contBytes = 1; accBytes = 1; + } else if (curByte < 0xF0) { // Three-byte code + acc = curByte & 0x0F; + contBytes = 2; accBytes = 1; + } else { // Four or more are not supported for CESU-8. + res += this.defaultCharUnicode; } - return 0; - }); - // loop over preferred slaves and return the first match - for (let p = 0; p < preferredSlavesArray.length; p++) { - for (let a = 0; a < availableSlaves.length; a++) { - const slave = availableSlaves[a]; - if (slave.ip === preferredSlavesArray[p].ip) { - if (slave.port === preferredSlavesArray[p].port) { - selectedSlave = slave; - break; - } + } else { // Continuation byte + if (contBytes > 0) { // We're waiting for it. + acc = (acc << 6) | (curByte & 0x3f); + contBytes--; accBytes++; + if (contBytes === 0) { + // Check for overlong encoding, but support Modified UTF-8 (encoding NULL as C0 80) + if (accBytes === 2 && acc < 0x80 && acc > 0) + res += this.defaultCharUnicode; + else if (accBytes === 3 && acc < 0x800) + res += this.defaultCharUnicode; + else + // Actually add character. + res += String.fromCharCode(acc); } - } - if (selectedSlave) { - break; + } else { // Unexpected continuation byte + res += this.defaultCharUnicode; } } } - // if none of the preferred slaves are available, a random available slave is returned - if (!selectedSlave) { - selectedSlave = utils_1.sample(availableSlaves); - } - return addressResponseToAddress(selectedSlave); + this.acc = acc; this.contBytes = contBytes; this.accBytes = accBytes; + return res; } -function addressResponseToAddress(input) { - return { host: input.ip, port: Number(input.port) }; + +InternalDecoderCesu8.prototype.end = function() { + var res = 0; + if (this.contBytes > 0) + res += this.defaultCharUnicode; + return res; } -function noop() { } /***/ }), -/***/ 8774: +/***/ 26657: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const net_1 = __nccwpck_require__(11631); -const tls_1 = __nccwpck_require__(4016); -const utils_1 = __nccwpck_require__(94832); -const AbstractConnector_1 = __nccwpck_require__(72712); -function isIIpcConnectionOptions(value) { - return value.path; -} -exports.isIIpcConnectionOptions = isIIpcConnectionOptions; -class StandaloneConnector extends AbstractConnector_1.default { - constructor(options) { - super(); - this.options = options; +var Buffer = __nccwpck_require__(15118).Buffer; + +// Single-byte codec. Needs a 'chars' string parameter that contains 256 or 128 chars that +// correspond to encoded bytes (if 128 - then lower half is ASCII). + +exports._sbcs = SBCSCodec; +function SBCSCodec(codecOptions, iconv) { + if (!codecOptions) + throw new Error("SBCS codec is called without the data.") + + // Prepare char buffer for decoding. + if (!codecOptions.chars || (codecOptions.chars.length !== 128 && codecOptions.chars.length !== 256)) + throw new Error("Encoding '"+codecOptions.type+"' has incorrect 'chars' (must be of len 128 or 256)"); + + if (codecOptions.chars.length === 128) { + var asciiString = ""; + for (var i = 0; i < 128; i++) + asciiString += String.fromCharCode(i); + codecOptions.chars = asciiString + codecOptions.chars; } - connect(_) { - const { options } = this; - this.connecting = true; - let connectionOptions; - if (isIIpcConnectionOptions(options)) { - connectionOptions = { - path: options.path, - }; - } - else { - connectionOptions = {}; - if (options.port != null) { - connectionOptions.port = options.port; - } - if (options.host != null) { - connectionOptions.host = options.host; - } - if (options.family != null) { - connectionOptions.family = options.family; - } - } - if (options.tls) { - Object.assign(connectionOptions, options.tls); - } - // TODO: - // We use native Promise here since other Promise - // implementation may use different schedulers that - // cause issue when the stream is resolved in the - // next tick. - // Should use the provided promise in the next major - // version and do not connect before resolved. - return new Promise((resolve, reject) => { - process.nextTick(() => { - if (!this.connecting) { - reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); - return; - } - try { - if (options.tls) { - this.stream = tls_1.connect(connectionOptions); - } - else { - this.stream = net_1.createConnection(connectionOptions); - } - } - catch (err) { - reject(err); - return; - } - resolve(this.stream); - }); - }); + + this.decodeBuf = Buffer.from(codecOptions.chars, 'ucs2'); + + // Encoding buffer. + var encodeBuf = Buffer.alloc(65536, iconv.defaultCharSingleByte.charCodeAt(0)); + + for (var i = 0; i < codecOptions.chars.length; i++) + encodeBuf[codecOptions.chars.charCodeAt(i)] = i; + + this.encodeBuf = encodeBuf; +} + +SBCSCodec.prototype.encoder = SBCSEncoder; +SBCSCodec.prototype.decoder = SBCSDecoder; + + +function SBCSEncoder(options, codec) { + this.encodeBuf = codec.encodeBuf; +} + +SBCSEncoder.prototype.write = function(str) { + var buf = Buffer.alloc(str.length); + for (var i = 0; i < str.length; i++) + buf[i] = this.encodeBuf[str.charCodeAt(i)]; + + return buf; +} + +SBCSEncoder.prototype.end = function() { +} + + +function SBCSDecoder(options, codec) { + this.decodeBuf = codec.decodeBuf; +} + +SBCSDecoder.prototype.write = function(buf) { + // Strings are immutable in JS -> we use ucs2 buffer to speed up computations. + var decodeBuf = this.decodeBuf; + var newBuf = Buffer.alloc(buf.length*2); + var idx1 = 0, idx2 = 0; + for (var i = 0; i < buf.length; i++) { + idx1 = buf[i]*2; idx2 = i*2; + newBuf[idx2] = decodeBuf[idx1]; + newBuf[idx2+1] = decodeBuf[idx1+1]; } + return newBuf.toString('ucs2'); +} + +SBCSDecoder.prototype.end = function() { } -exports.default = StandaloneConnector; /***/ }), -/***/ 72340: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 21012: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const StandaloneConnector_1 = __nccwpck_require__(8774); -exports.StandaloneConnector = StandaloneConnector_1.default; -const SentinelConnector_1 = __nccwpck_require__(10379); -exports.SentinelConnector = SentinelConnector_1.default; +// Generated data for sbcs codec. Don't edit manually. Regenerate using generation/gen-sbcs.js script. +module.exports = { + "437": "cp437", + "737": "cp737", + "775": "cp775", + "850": "cp850", + "852": "cp852", + "855": "cp855", + "856": "cp856", + "857": "cp857", + "858": "cp858", + "860": "cp860", + "861": "cp861", + "862": "cp862", + "863": "cp863", + "864": "cp864", + "865": "cp865", + "866": "cp866", + "869": "cp869", + "874": "windows874", + "922": "cp922", + "1046": "cp1046", + "1124": "cp1124", + "1125": "cp1125", + "1129": "cp1129", + "1133": "cp1133", + "1161": "cp1161", + "1162": "cp1162", + "1163": "cp1163", + "1250": "windows1250", + "1251": "windows1251", + "1252": "windows1252", + "1253": "windows1253", + "1254": "windows1254", + "1255": "windows1255", + "1256": "windows1256", + "1257": "windows1257", + "1258": "windows1258", + "28591": "iso88591", + "28592": "iso88592", + "28593": "iso88593", + "28594": "iso88594", + "28595": "iso88595", + "28596": "iso88596", + "28597": "iso88597", + "28598": "iso88598", + "28599": "iso88599", + "28600": "iso885910", + "28601": "iso885911", + "28603": "iso885913", + "28604": "iso885914", + "28605": "iso885915", + "28606": "iso885916", + "windows874": { + "type": "_sbcs", + "chars": "€����…�����������‘’“”•–—�������� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "win874": "windows874", + "cp874": "windows874", + "windows1250": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰Š‹ŚŤŽŹ�‘’“”•–—�™š›śťžź ˇ˘Ł¤Ą¦§¨©Ş«¬­®Ż°±˛ł´µ¶·¸ąş»Ľ˝ľżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "win1250": "windows1250", + "cp1250": "windows1250", + "windows1251": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊЌЋЏђ‘’“”•–—�™љ›њќћџ ЎўЈ¤Ґ¦§Ё©Є«¬­®Ї°±Ііґµ¶·ё№є»јЅѕїАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "win1251": "windows1251", + "cp1251": "windows1251", + "windows1252": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ�Ž��‘’“”•–—˜™š›œ�žŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "win1252": "windows1252", + "cp1252": "windows1252", + "windows1253": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡�‰�‹�����‘’“”•–—�™�›���� ΅Ά£¤¥¦§¨©�«¬­®―°±²³΄µ¶·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "win1253": "windows1253", + "cp1253": "windows1253", + "windows1254": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰Š‹Œ����‘’“”•–—˜™š›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "win1254": "windows1254", + "cp1254": "windows1254", + "windows1255": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹�����‘’“”•–—˜™�›���� ¡¢£₪¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾¿ְֱֲֳִֵֶַָֹֺֻּֽ־ֿ׀ׁׂ׃װױײ׳״�������אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "win1255": "windows1255", + "cp1255": "windows1255", + "windows1256": { + "type": "_sbcs", + "chars": "€پ‚ƒ„…†‡ˆ‰ٹ‹Œچژڈگ‘’“”•–—ک™ڑ›œ‌‍ں ،¢£¤¥¦§¨©ھ«¬­®¯°±²³´µ¶·¸¹؛»¼½¾؟ہءآأؤإئابةتثجحخدذرزسشصض×طظعغـفقكàلâمنهوçèéêëىيîïًٌٍَôُِ÷ّùْûü‎‏ے" + }, + "win1256": "windows1256", + "cp1256": "windows1256", + "windows1257": { + "type": "_sbcs", + "chars": "€�‚�„…†‡�‰�‹�¨ˇ¸�‘’“”•–—�™�›�¯˛� �¢£¤�¦§Ø©Ŗ«¬­®Æ°±²³´µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž˙" + }, + "win1257": "windows1257", + "cp1257": "windows1257", + "windows1258": { + "type": "_sbcs", + "chars": "€�‚ƒ„…†‡ˆ‰�‹Œ����‘’“”•–—˜™�›œ��Ÿ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "win1258": "windows1258", + "cp1258": "windows1258", + "iso88591": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28591": "iso88591", + "iso88592": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ą˘Ł¤ĽŚ§¨ŠŞŤŹ­ŽŻ°ą˛ł´ľśˇ¸šşťź˝žżŔÁÂĂÄĹĆÇČÉĘËĚÍÎĎĐŃŇÓÔŐÖ×ŘŮÚŰÜÝŢßŕáâăäĺćçčéęëěíîďđńňóôőö÷řůúűüýţ˙" + }, + "cp28592": "iso88592", + "iso88593": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ħ˘£¤�Ĥ§¨İŞĞĴ­�Ż°ħ²³´µĥ·¸ışğĵ½�żÀÁÂ�ÄĊĈÇÈÉÊËÌÍÎÏ�ÑÒÓÔĠÖ×ĜÙÚÛÜŬŜßàáâ�äċĉçèéêëìíîï�ñòóôġö÷ĝùúûüŭŝ˙" + }, + "cp28593": "iso88593", + "iso88594": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĸŖ¤ĨĻ§¨ŠĒĢŦ­Ž¯°ą˛ŗ´ĩļˇ¸šēģŧŊžŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎĪĐŅŌĶÔÕÖ×ØŲÚÛÜŨŪßāáâãäåæįčéęëėíîīđņōķôõö÷øųúûüũū˙" + }, + "cp28594": "iso88594", + "iso88595": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂЃЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђѓєѕіїјљњћќ§ўџ" + }, + "cp28595": "iso88595", + "iso88596": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ���¤�������،­�������������؛���؟�ءآأؤإئابةتثجحخدذرزسشصضطظعغ�����ـفقكلمنهوىيًٌٍَُِّْ�������������" + }, + "cp28596": "iso88596", + "iso88597": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ‘’£€₯¦§¨©ͺ«¬­�―°±²³΄΅Ά·ΈΉΊ»Ό½ΎΏΐΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡ�ΣΤΥΦΧΨΩΪΫάέήίΰαβγδεζηθικλμνξοπρςστυφχψωϊϋόύώ�" + }, + "cp28597": "iso88597", + "iso88598": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �¢£¤¥¦§¨©×«¬­®¯°±²³´µ¶·¸¹÷»¼½¾��������������������������������‗אבגדהוזחטיךכלםמןנסעףפץצקרשת��‎‏�" + }, + "cp28598": "iso88598", + "iso88599": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏĞÑÒÓÔÕÖ×ØÙÚÛÜİŞßàáâãäåæçèéêëìíîïğñòóôõö÷øùúûüışÿ" + }, + "cp28599": "iso88599", + "iso885910": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄĒĢĪĨĶ§ĻĐŠŦŽ­ŪŊ°ąēģīĩķ·ļđšŧž―ūŋĀÁÂÃÄÅÆĮČÉĘËĖÍÎÏÐŅŌÓÔÕÖŨØŲÚÛÜÝÞßāáâãäåæįčéęëėíîïðņōóôõöũøųúûüýþĸ" + }, + "cp28600": "iso885910", + "iso885911": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "cp28601": "iso885911", + "iso885913": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ”¢£¤„¦§Ø©Ŗ«¬­®Æ°±²³“µ¶·ø¹ŗ»¼½¾æĄĮĀĆÄÅĘĒČÉŹĖĢĶĪĻŠŃŅÓŌÕÖ×ŲŁŚŪÜŻŽßąįāćäåęēčéźėģķīļšńņóōõö÷ųłśūüżž’" + }, + "cp28603": "iso885913", + "iso885914": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ Ḃḃ£ĊċḊ§Ẁ©ẂḋỲ­®ŸḞḟĠġṀṁ¶ṖẁṗẃṠỳẄẅṡÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŴÑÒÓÔÕÖṪØÙÚÛÜÝŶßàáâãäåæçèéêëìíîïŵñòóôõöṫøùúûüýŷÿ" + }, + "cp28604": "iso885914", + "iso885915": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥Š§š©ª«¬­®¯°±²³Žµ¶·ž¹º»ŒœŸ¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏÐÑÒÓÔÕÖ×ØÙÚÛÜÝÞßàáâãäåæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "cp28605": "iso885915", + "iso885916": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ĄąŁ€„Š§š©Ș«Ź­źŻ°±ČłŽ”¶·žčș»ŒœŸżÀÁÂĂÄĆÆÇÈÉÊËÌÍÎÏĐŃÒÓÔŐÖŚŰÙÚÛÜĘȚßàáâăäćæçèéêëìíîïđńòóôőöśűùúûüęțÿ" + }, + "cp28606": "iso885916", + "cp437": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜ¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm437": "cp437", + "csibm437": "cp437", + "cp737": { + "type": "_sbcs", + "chars": "ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρσςτυφχψ░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀ωάέήϊίόύϋώΆΈΉΊΌΎΏ±≥≤ΪΫ÷≈°∙·√ⁿ²■ " + }, + "ibm737": "cp737", + "csibm737": "cp737", + "cp775": { + "type": "_sbcs", + "chars": "ĆüéāäģåćłēŖŗīŹÄÅÉæÆōöĢ¢ŚśÖÜø£ØפĀĪóŻżź”¦©®¬½¼Ł«»░▒▓│┤ĄČĘĖ╣║╗╝ĮŠ┐└┴┬├─┼ŲŪ╚╔╩╦╠═╬Žąčęėįšųūž┘┌█▄▌▐▀ÓßŌŃõÕµńĶķĻļņĒŅ’­±“¾¶§÷„°∙·¹³²■ " + }, + "ibm775": "cp775", + "csibm775": "cp775", + "cp850": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈıÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm850": "cp850", + "csibm850": "cp850", + "cp852": { + "type": "_sbcs", + "chars": "ÇüéâäůćçłëŐőîŹÄĆÉĹĺôöĽľŚśÖÜŤťŁ×čáíóúĄąŽžĘ꬟Ⱥ«»░▒▓│┤ÁÂĚŞ╣║╗╝Żż┐└┴┬├─┼Ăă╚╔╩╦╠═╬¤đĐĎËďŇÍÎě┘┌█▄ŢŮ▀ÓßÔŃńňŠšŔÚŕŰýÝţ´­˝˛ˇ˘§÷¸°¨˙űŘř■ " + }, + "ibm852": "cp852", + "csibm852": "cp852", + "cp855": { + "type": "_sbcs", + "chars": "ђЂѓЃёЁєЄѕЅіІїЇјЈљЉњЊћЋќЌўЎџЏюЮъЪаАбБцЦдДеЕфФгГ«»░▒▓│┤хХиИ╣║╗╝йЙ┐└┴┬├─┼кК╚╔╩╦╠═╬¤лЛмМнНоОп┘┌█▄Пя▀ЯрРсСтТуУжЖвВьЬ№­ыЫзЗшШэЭщЩчЧ§■ " + }, + "ibm855": "cp855", + "csibm855": "cp855", + "cp856": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת�£�×����������®¬½¼�«»░▒▓│┤���©╣║╗╝¢¥┐└┴┬├─┼��╚╔╩╦╠═╬¤���������┘┌█▄¦�▀������µ�������¯´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm856": "cp856", + "csibm856": "cp856", + "cp857": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîıÄÅÉæÆôöòûùİÖÜø£ØŞşáíóúñÑĞ𿮬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ºªÊËÈ�ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµ�×ÚÛÙìÿ¯´­±�¾¶§÷¸°¨·¹³²■ " + }, + "ibm857": "cp857", + "csibm857": "cp857", + "cp858": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø׃áíóúñѪº¿®¬½¼¡«»░▒▓│┤ÁÂÀ©╣║╗╝¢¥┐└┴┬├─┼ãÃ╚╔╩╦╠═╬¤ðÐÊËÈ€ÍÎÏ┘┌█▄¦Ì▀ÓßÔÒõÕµþÞÚÛÙýݯ´­±‗¾¶§÷¸°¨·¹³²■ " + }, + "ibm858": "cp858", + "csibm858": "cp858", + "cp860": { + "type": "_sbcs", + "chars": "ÇüéâãàÁçêÊèÍÔìÃÂÉÀÈôõòÚùÌÕÜ¢£Ù₧ÓáíóúñѪº¿Ò¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm860": "cp860", + "csibm860": "cp860", + "cp861": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèÐðÞÄÅÉæÆôöþûÝýÖÜø£Ø₧ƒáíóúÁÍÓÚ¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm861": "cp861", + "csibm861": "cp861", + "cp862": { + "type": "_sbcs", + "chars": "אבגדהוזחטיךכלםמןנסעףפץצקרשת¢£¥₧ƒáíóúñѪº¿⌐¬½¼¡«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm862": "cp862", + "csibm862": "cp862", + "cp863": { + "type": "_sbcs", + "chars": "ÇüéâÂà¶çêëèïî‗À§ÉÈÊôËÏûù¤ÔÜ¢£ÙÛƒ¦´óú¨¸³¯Î⌐¬½¼¾«»░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm863": "cp863", + "csibm863": "cp863", + "cp864": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$٪&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~°·∙√▒─│┼┤┬├┴┐┌└┘β∞φ±½¼≈«»ﻷﻸ��ﻻﻼ� ­ﺂ£¤ﺄ��ﺎﺏﺕﺙ،ﺝﺡﺥ٠١٢٣٤٥٦٧٨٩ﻑ؛ﺱﺵﺹ؟¢ﺀﺁﺃﺅﻊﺋﺍﺑﺓﺗﺛﺟﺣﺧﺩﺫﺭﺯﺳﺷﺻﺿﻁﻅﻋﻏ¦¬÷×ﻉـﻓﻗﻛﻟﻣﻧﻫﻭﻯﻳﺽﻌﻎﻍﻡﹽّﻥﻩﻬﻰﻲﻐﻕﻵﻶﻝﻙﻱ■�" + }, + "ibm864": "cp864", + "csibm864": "cp864", + "cp865": { + "type": "_sbcs", + "chars": "ÇüéâäàåçêëèïîìÄÅÉæÆôöòûùÿÖÜø£Ø₧ƒáíóúñѪº¿⌐¬½¼¡«¤░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + "ibm865": "cp865", + "csibm865": "cp865", + "cp866": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№¤■ " + }, + "ibm866": "cp866", + "csibm866": "cp866", + "cp869": { + "type": "_sbcs", + "chars": "������Ά�·¬¦‘’Έ―ΉΊΪΌ��ΎΫ©Ώ²³ά£έήίϊΐόύΑΒΓΔΕΖΗ½ΘΙ«»░▒▓│┤ΚΛΜΝ╣║╗╝ΞΟ┐└┴┬├─┼ΠΡ╚╔╩╦╠═╬ΣΤΥΦΧΨΩαβγ┘┌█▄δε▀ζηθικλμνξοπρσςτ΄­±υφχ§ψ΅°¨ωϋΰώ■ " + }, + "ibm869": "cp869", + "csibm869": "cp869", + "cp922": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®‾°±²³´µ¶·¸¹º»¼½¾¿ÀÁÂÃÄÅÆÇÈÉÊËÌÍÎÏŠÑÒÓÔÕÖ×ØÙÚÛÜÝŽßàáâãäåæçèéêëìíîïšñòóôõö÷øùúûüýžÿ" + }, + "ibm922": "cp922", + "csibm922": "cp922", + "cp1046": { + "type": "_sbcs", + "chars": "ﺈ×÷ﹱˆ■│─┐┌└┘ﹹﹻﹽﹿﹷﺊﻰﻳﻲﻎﻏﻐﻶﻸﻺﻼ ¤ﺋﺑﺗﺛﺟﺣ،­ﺧﺳ٠١٢٣٤٥٦٧٨٩ﺷ؛ﺻﺿﻊ؟ﻋءآأؤإئابةتثجحخدذرزسشصضطﻇعغﻌﺂﺄﺎﻓـفقكلمنهوىيًٌٍَُِّْﻗﻛﻟﻵﻷﻹﻻﻣﻧﻬﻩ�" + }, + "ibm1046": "cp1046", + "csibm1046": "cp1046", + "cp1124": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ЁЂҐЄЅІЇЈЉЊЋЌ­ЎЏАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя№ёђґєѕіїјљњћќ§ўџ" + }, + "ibm1124": "cp1124", + "csibm1124": "cp1124", + "cp1125": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёҐґЄєІіЇї·√№¤■ " + }, + "ibm1125": "cp1125", + "csibm1125": "cp1125", + "cp1129": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1129": "cp1129", + "csibm1129": "cp1129", + "cp1133": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ກຂຄງຈສຊຍດຕຖທນບປຜຝພຟມຢຣລວຫອຮ���ຯະາຳິີຶືຸູຼັົຽ���ເແໂໃໄ່້໊໋໌ໍໆ�ໜໝ₭����������������໐໑໒໓໔໕໖໗໘໙��¢¬¦�" + }, + "ibm1133": "cp1133", + "csibm1133": "cp1133", + "cp1161": { + "type": "_sbcs", + "chars": "��������������������������������่กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู้๊๋€฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛¢¬¦ " + }, + "ibm1161": "cp1161", + "csibm1161": "cp1161", + "cp1162": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + }, + "ibm1162": "cp1162", + "csibm1162": "cp1162", + "cp1163": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£€¥¦§œ©ª«¬­®¯°±²³Ÿµ¶·Œ¹º»¼½¾¿ÀÁÂĂÄÅÆÇÈÉÊË̀ÍÎÏĐÑ̉ÓÔƠÖ×ØÙÚÛÜỮßàáâăäåæçèéêë́íîïđṇ̃óôơö÷øùúûüư₫ÿ" + }, + "ibm1163": "cp1163", + "csibm1163": "cp1163", + "maccroatian": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®Š™´¨≠ŽØ∞±≤≥∆µ∂∑∏š∫ªºΩžø¿¡¬√ƒ≈Ć«Č… ÀÃÕŒœĐ—“”‘’÷◊�©⁄¤‹›Æ»–·‚„‰ÂćÁčÈÍÎÏÌÓÔđÒÚÛÙıˆ˜¯πË˚¸Êæˇ" + }, + "maccyrillic": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°¢£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµ∂ЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "macgreek": { + "type": "_sbcs", + "chars": "Ĺ²É³ÖÜ΅àâä΄¨çéèê룙î‰ôö¦­ùûü†ΓΔΘΛΞΠß®©ΣΪ§≠°·Α±≤≥¥ΒΕΖΗΙΚΜΦΫΨΩάΝ¬ΟΡ≈Τ«»… ΥΧΆΈœ–―“”‘’÷ΉΊΌΎέήίόΏύαβψδεφγηιξκλμνοπώρστθωςχυζϊϋΐΰ�" + }, + "maciceland": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûüÝ°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤ÐðÞþý·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macroman": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macromania": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ĂŞ∞±≤≥¥µ∂∑∏π∫ªºΩăş¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›Ţţ‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macthai": { + "type": "_sbcs", + "chars": "«»…“”�•‘’� กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู​–—฿เแโใไๅๆ็่้๊๋์ํ™๏๐๑๒๓๔๕๖๗๘๙®©����" + }, + "macturkish": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸĞğİıŞş‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙ�ˆ˜¯˘˙˚¸˝˛ˇ" + }, + "macukraine": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯ†°Ґ£§•¶І®©™Ђђ≠Ѓѓ∞±≤≥іµґЈЄєЇїЉљЊњјЅ¬√ƒ≈∆«»… ЋћЌќѕ–—“”‘’÷„ЎўЏџ№Ёёяабвгдежзийклмнопрстуфхцчшщъыьэю¤" + }, + "koi8r": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ё╓╔╕╖╗╘╙╚╛╜╝╞╟╠╡Ё╢╣╤╥╦╧╨╩╪╫╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8u": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґ╝╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪Ґ╬©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8ru": { + "type": "_sbcs", + "chars": "─│┌┐└┘├┤┬┴┼▀▄█▌▐░▒▓⌠■∙√≈≤≥ ⌡°²·÷═║╒ёє╔ії╗╘╙╚╛ґў╞╟╠╡ЁЄ╣ІЇ╦╧╨╩╪ҐЎ©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "koi8t": { + "type": "_sbcs", + "chars": "қғ‚Ғ„…†‡�‰ҳ‹ҲҷҶ�Қ‘’“”•–—�™�›�����ӯӮё¤ӣ¦§���«¬­®�°±²Ё�Ӣ¶·�№�»���©юабцдефгхийклмнопярстужвьызшэщчъЮАБЦДЕФГХИЙКЛМНОПЯРСТУЖВЬЫЗШЭЩЧЪ" + }, + "armscii8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ �և։)(»«—.՝,-֊…՜՛՞ԱաԲբԳգԴդԵեԶզԷէԸըԹթԺժԻիԼլԽխԾծԿկՀհՁձՂղՃճՄմՅյՆնՇշՈոՉչՊպՋջՌռՍսՎվՏտՐրՑցՒւՓփՔքՕօՖֆ՚�" + }, + "rk1048": { + "type": "_sbcs", + "chars": "ЂЃ‚ѓ„…†‡€‰Љ‹ЊҚҺЏђ‘’“”•–—�™љ›њқһџ ҰұӘ¤Ө¦§Ё©Ғ«¬­®Ү°±Ііөµ¶·ё№ғ»әҢңүАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "tcvn": { + "type": "_sbcs", + "chars": "\u0000ÚỤ\u0003ỪỬỮ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010ỨỰỲỶỸÝỴ\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ÀẢÃÁẠẶẬÈẺẼÉẸỆÌỈĨÍỊÒỎÕÓỌỘỜỞỠỚỢÙỦŨ ĂÂÊÔƠƯĐăâêôơưđẶ̀̀̉̃́àảãáạẲằẳẵắẴẮẦẨẪẤỀặầẩẫấậèỂẻẽéẹềểễếệìỉỄẾỒĩíịòỔỏõóọồổỗốộờởỡớợùỖủũúụừửữứựỳỷỹýỵỐ" + }, + "georgianacademy": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზთიკლმნოპჟრსტუფქღყშჩცძწჭხჯჰჱჲჳჴჵჶçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "georgianps": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ¡¢£¤¥¦§¨©ª«¬­®¯°±²³´µ¶·¸¹º»¼½¾¿აბგდევზჱთიკლმნჲოპჟრსტჳუფქღყშჩცძწჭხჴჯჰჵæçèéêëìíîïðñòóôõö÷øùúûüýþÿ" + }, + "pt154": { + "type": "_sbcs", + "chars": "ҖҒӮғ„…ҶҮҲүҠӢҢҚҺҸҗ‘’“”•–—ҳҷҡӣңқһҹ ЎўЈӨҘҰ§Ё©Ә«¬ӯ®Ҝ°ұІіҙө¶·ё№ә»јҪҫҝАБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя" + }, + "viscii": { + "type": "_sbcs", + "chars": "\u0000\u0001Ẳ\u0003\u0004ẴẪ\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013Ỷ\u0015\u0016\u0017\u0018Ỹ\u001a\u001b\u001c\u001dỴ\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~ẠẮẰẶẤẦẨẬẼẸẾỀỂỄỆỐỒỔỖỘỢỚỜỞỊỎỌỈỦŨỤỲÕắằặấầẩậẽẹếềểễệốồổỗỠƠộờởịỰỨỪỬơớƯÀÁÂÃẢĂẳẵÈÉÊẺÌÍĨỳĐứÒÓÔạỷừửÙÚỹỵÝỡưàáâãảăữẫèéêẻìíĩỉđựòóôõỏọụùúũủýợỮ" + }, + "iso646cn": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#¥%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "iso646jp": { + "type": "_sbcs", + "chars": "\u0000\u0001\u0002\u0003\u0004\u0005\u0006\u0007\b\t\n\u000b\f\r\u000e\u000f\u0010\u0011\u0012\u0013\u0014\u0015\u0016\u0017\u0018\u0019\u001a\u001b\u001c\u001d\u001e\u001f !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[¥]^_`abcdefghijklmnopqrstuvwxyz{|}‾��������������������������������������������������������������������������������������������������������������������������������" + }, + "hproman8": { + "type": "_sbcs", + "chars": "€‚ƒ„…†‡ˆ‰Š‹ŒŽ‘’“”•–—˜™š›œžŸ ÀÂÈÊËÎÏ´ˋˆ¨˜ÙÛ₤¯Ýý°ÇçÑñ¡¿¤£¥§ƒ¢âêôûáéóúàèòùäëöüÅîØÆåíøæÄìÖÜÉïßÔÁÃãÐðÍÌÓÒÕõŠšÚŸÿÞþ·µ¶¾—¼½ªº«■»±�" + }, + "macintosh": { + "type": "_sbcs", + "chars": "ÄÅÇÉÑÖÜáàâäãåçéèêëíìîïñóòôöõúùûü†°¢£§•¶ß®©™´¨≠ÆØ∞±≤≥¥µ∂∑∏π∫ªºΩæø¿¡¬√ƒ≈∆«»… ÀÃÕŒœ–—“”‘’÷◊ÿŸ⁄¤‹›fifl‡·‚„‰ÂÊÁËÈÍÎÏÌÓÔ�ÒÚÛÙıˆ˜¯˘˙˚¸˝˛ˇ" + }, + "ascii": { + "type": "_sbcs", + "chars": "��������������������������������������������������������������������������������������������������������������������������������" + }, + "tis620": { + "type": "_sbcs", + "chars": "���������������������������������กขฃคฅฆงจฉชซฌญฎฏฐฑฒณดตถทธนบปผฝพฟภมยรฤลฦวศษสหฬอฮฯะัาำิีึืฺุู����฿เแโใไๅๆ็่้๊๋์ํ๎๏๐๑๒๓๔๕๖๗๘๙๚๛����" + } +} /***/ }), -/***/ 97282: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 41080: +/***/ ((module) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const redis_errors_1 = __nccwpck_require__(81879); -class ClusterAllFailedError extends redis_errors_1.RedisError { - constructor(message, lastNodeError) { - super(message); - this.lastNodeError = lastNodeError; - Error.captureStackTrace(this, this.constructor); - } - get name() { - return this.constructor.name; - } -} -exports.default = ClusterAllFailedError; +// Manually added data to be used by sbcs codec in addition to generated one. -/***/ }), +module.exports = { + // Not supported by iconv, not sure why. + "10029": "maccenteuro", + "maccenteuro": { + "type": "_sbcs", + "chars": "ÄĀāÉĄÖÜáąČäčĆć鏟ĎíďĒēĖóėôöõúĚěü†°Ę£§•¶ß®©™ę¨≠ģĮįĪ≤≥īĶ∂∑łĻļĽľĹĺŅņѬ√ńŇ∆«»… ňŐÕőŌ–—“”‘’÷◊ōŔŕŘ‹›řŖŗŠ‚„šŚśÁŤťÍŽžŪÓÔūŮÚůŰűŲųÝýķŻŁżĢˇ" + }, -/***/ 90735: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + "808": "cp808", + "ibm808": "cp808", + "cp808": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмноп░▒▓│┤╡╢╖╕╣║╗╝╜╛┐└┴┬├─┼╞╟╚╔╩╦╠═╬╧╨╤╥╙╘╒╓╫╪┘┌█▄▌▐▀рстуфхцчшщъыьэюяЁёЄєЇїЎў°∙·√№€■ " + }, -"use strict"; + "mik": { + "type": "_sbcs", + "chars": "АБВГДЕЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдежзийклмнопрстуфхцчшщъыьэюя└┴┬├─┼╣║╚╔╩╦╠═╬┐░▒▓│┤№§╗╝┘┌█▄▌▐▀αßΓπΣσµτΦΘΩδ∞φε∩≡±≥≤⌠⌡÷≈°∙·√ⁿ²■ " + }, + + // Aliases of generated encodings. + "ascii8bit": "ascii", + "usascii": "ascii", + "ansix34": "ascii", + "ansix341968": "ascii", + "ansix341986": "ascii", + "csascii": "ascii", + "cp367": "ascii", + "ibm367": "ascii", + "isoir6": "ascii", + "iso646us": "ascii", + "iso646irv": "ascii", + "us": "ascii", -Object.defineProperty(exports, "__esModule", ({ value: true })); -const redis_errors_1 = __nccwpck_require__(81879); -class MaxRetriesPerRequestError extends redis_errors_1.AbortError { - constructor(maxRetriesPerRequest) { - const message = `Reached the max retries per request limit (which is ${maxRetriesPerRequest}). Refer to "maxRetriesPerRequest" option for details.`; - super(message); - Error.captureStackTrace(this, this.constructor); - } - get name() { - return this.constructor.name; - } -} -exports.default = MaxRetriesPerRequestError; + "latin1": "iso88591", + "latin2": "iso88592", + "latin3": "iso88593", + "latin4": "iso88594", + "latin5": "iso88599", + "latin6": "iso885910", + "latin7": "iso885913", + "latin8": "iso885914", + "latin9": "iso885915", + "latin10": "iso885916", + "csisolatin1": "iso88591", + "csisolatin2": "iso88592", + "csisolatin3": "iso88593", + "csisolatin4": "iso88594", + "csisolatincyrillic": "iso88595", + "csisolatinarabic": "iso88596", + "csisolatingreek" : "iso88597", + "csisolatinhebrew": "iso88598", + "csisolatin5": "iso88599", + "csisolatin6": "iso885910", -/***/ }), + "l1": "iso88591", + "l2": "iso88592", + "l3": "iso88593", + "l4": "iso88594", + "l5": "iso88599", + "l6": "iso885910", + "l7": "iso885913", + "l8": "iso885914", + "l9": "iso885915", + "l10": "iso885916", -/***/ 23961: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + "isoir14": "iso646jp", + "isoir57": "iso646cn", + "isoir100": "iso88591", + "isoir101": "iso88592", + "isoir109": "iso88593", + "isoir110": "iso88594", + "isoir144": "iso88595", + "isoir127": "iso88596", + "isoir126": "iso88597", + "isoir138": "iso88598", + "isoir148": "iso88599", + "isoir157": "iso885910", + "isoir166": "tis620", + "isoir179": "iso885913", + "isoir199": "iso885914", + "isoir203": "iso885915", + "isoir226": "iso885916", -"use strict"; + "cp819": "iso88591", + "ibm819": "iso88591", -Object.defineProperty(exports, "__esModule", ({ value: true })); -const MaxRetriesPerRequestError_1 = __nccwpck_require__(90735); -exports.MaxRetriesPerRequestError = MaxRetriesPerRequestError_1.default; + "cyrillic": "iso88595", + "arabic": "iso88596", + "arabic8": "iso88596", + "ecma114": "iso88596", + "asmo708": "iso88596", -/***/ }), + "greek" : "iso88597", + "greek8" : "iso88597", + "ecma118" : "iso88597", + "elot928" : "iso88597", -/***/ 45069: -/***/ ((module, exports, __nccwpck_require__) => { + "hebrew": "iso88598", + "hebrew8": "iso88598", -"use strict"; + "turkish": "iso88599", + "turkish8": "iso88599", -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports = module.exports = __nccwpck_require__(83609).default; -var redis_1 = __nccwpck_require__(83609); -exports.default = redis_1.default; -var cluster_1 = __nccwpck_require__(17208); -exports.Cluster = cluster_1.default; -var command_1 = __nccwpck_require__(90803); -exports.Command = command_1.default; -var ScanStream_1 = __nccwpck_require__(6134); -exports.ScanStream = ScanStream_1.default; -var pipeline_1 = __nccwpck_require__(42803); -exports.Pipeline = pipeline_1.default; -var AbstractConnector_1 = __nccwpck_require__(72712); -exports.AbstractConnector = AbstractConnector_1.default; -var SentinelConnector_1 = __nccwpck_require__(10379); -exports.SentinelConnector = SentinelConnector_1.default; -exports.SentinelIterator = SentinelConnector_1.SentinelIterator; -// No TS typings -exports.ReplyError = __nccwpck_require__(81879).ReplyError; -const PromiseContainer = __nccwpck_require__(71475); -Object.defineProperty(exports, "Promise", ({ - get() { - return PromiseContainer.get(); - }, - set(lib) { - PromiseContainer.set(lib); - }, -})); -function print(err, reply) { - if (err) { - console.log("Error: " + err); - } - else { - console.log("Reply: " + reply); - } -} -exports.print = print; + "thai": "iso885911", + "thai8": "iso885911", + "celtic": "iso885914", + "celtic8": "iso885914", + "isoceltic": "iso885914", -/***/ }), + "tis6200": "tis620", + "tis62025291": "tis620", + "tis62025330": "tis620", -/***/ 42803: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + "10000": "macroman", + "10006": "macgreek", + "10007": "maccyrillic", + "10079": "maciceland", + "10081": "macturkish", -"use strict"; + "cspc8codepage437": "cp437", + "cspc775baltic": "cp775", + "cspc850multilingual": "cp850", + "cspcp852": "cp852", + "cspc862latinhebrew": "cp862", + "cpgr": "cp869", -Object.defineProperty(exports, "__esModule", ({ value: true })); -const command_1 = __nccwpck_require__(90803); -const util_1 = __nccwpck_require__(31669); -const standard_as_callback_1 = __nccwpck_require__(91543); -const redis_commands_1 = __nccwpck_require__(98020); -const calculateSlot = __nccwpck_require__(48481); -const pMap = __nccwpck_require__(91855); -const PromiseContainer = __nccwpck_require__(71475); -const commander_1 = __nccwpck_require__(33642); -/* - This function derives from the cluster-key-slot implementation. - Instead of checking that all keys have the same slot, it checks that all slots are served by the same set of nodes. - If this is satisfied, it returns the first key's slot. -*/ -function generateMultiWithNodes(redis, keys) { - const slot = calculateSlot(keys[0]); - const target = redis.slots[slot].join(","); - for (let i = 1; i < keys.length; i++) { - const currentTarget = redis.slots[calculateSlot(keys[i])].join(","); - if (currentTarget !== target) { - return -1; - } - } - return slot; -} -function Pipeline(redis) { - commander_1.default.call(this); - this.redis = redis; - this.isCluster = this.redis.constructor.name === "Cluster"; - this.isPipeline = true; - this.options = redis.options; - this._queue = []; - this._result = []; - this._transactions = 0; - this._shaToScript = {}; - Object.keys(redis.scriptsSet).forEach((name) => { - const script = redis.scriptsSet[name]; - this._shaToScript[script.sha] = script; - this[name] = redis[name]; - this[name + "Buffer"] = redis[name + "Buffer"]; - }); - const Promise = PromiseContainer.get(); - this.promise = new Promise((resolve, reject) => { - this.resolve = resolve; - this.reject = reject; - }); - const _this = this; - Object.defineProperty(this, "length", { - get: function () { - return _this._queue.length; - }, - }); -} -exports.default = Pipeline; -Object.assign(Pipeline.prototype, commander_1.default.prototype); -Pipeline.prototype.fillResult = function (value, position) { - if (this._queue[position].name === "exec" && Array.isArray(value[1])) { - const execLength = value[1].length; - for (let i = 0; i < execLength; i++) { - if (value[1][i] instanceof Error) { - continue; - } - const cmd = this._queue[position - (execLength - i)]; - try { - value[1][i] = cmd.transformReply(value[1][i]); - } - catch (err) { - value[1][i] = err; - } - } - } - this._result[position] = value; - if (--this.replyPending) { - return; - } - if (this.isCluster) { - let retriable = true; - let commonError; - for (let i = 0; i < this._result.length; ++i) { - const error = this._result[i][0]; - const command = this._queue[i]; - if (error) { - if (command.name === "exec" && - error.message === - "EXECABORT Transaction discarded because of previous errors.") { - continue; - } - if (!commonError) { - commonError = { - name: error.name, - message: error.message, - }; - } - else if (commonError.name !== error.name || - commonError.message !== error.message) { - retriable = false; - break; - } - } - else if (!command.inTransaction) { - const isReadOnly = redis_commands_1.exists(command.name) && redis_commands_1.hasFlag(command.name, "readonly"); - if (!isReadOnly) { - retriable = false; - break; - } - } - } - if (commonError && retriable) { - const _this = this; - const errv = commonError.message.split(" "); - const queue = this._queue; - let inTransaction = false; - this._queue = []; - for (let i = 0; i < queue.length; ++i) { - if (errv[0] === "ASK" && - !inTransaction && - queue[i].name !== "asking" && - (!queue[i - 1] || queue[i - 1].name !== "asking")) { - const asking = new command_1.default("asking"); - asking.ignore = true; - this.sendCommand(asking); - } - queue[i].initPromise(); - this.sendCommand(queue[i]); - inTransaction = queue[i].inTransaction; - } - let matched = true; - if (typeof this.leftRedirections === "undefined") { - this.leftRedirections = {}; - } - const exec = function () { - _this.exec(); - }; - this.redis.handleError(commonError, this.leftRedirections, { - moved: function (slot, key) { - _this.preferKey = key; - _this.redis.slots[errv[1]] = [key]; - _this.redis.refreshSlotsCache(); - _this.exec(); - }, - ask: function (slot, key) { - _this.preferKey = key; - _this.exec(); - }, - tryagain: exec, - clusterDown: exec, - connectionClosed: exec, - maxRedirections: () => { - matched = false; - }, - defaults: () => { - matched = false; - }, - }); - if (matched) { - return; - } - } - } - let ignoredCount = 0; - for (let i = 0; i < this._queue.length - ignoredCount; ++i) { - if (this._queue[i + ignoredCount].ignore) { - ignoredCount += 1; - } - this._result[i] = this._result[i + ignoredCount]; - } - this.resolve(this._result.slice(0, this._result.length - ignoredCount)); -}; -Pipeline.prototype.sendCommand = function (command) { - if (this._transactions > 0) { - command.inTransaction = true; - } - const position = this._queue.length; - command.pipelineIndex = position; - command.promise - .then((result) => { - this.fillResult([null, result], position); - }) - .catch((error) => { - this.fillResult([error], position); - }); - this._queue.push(command); - return this; -}; -Pipeline.prototype.addBatch = function (commands) { - let command, commandName, args; - for (let i = 0; i < commands.length; ++i) { - command = commands[i]; - commandName = command[0]; - args = command.slice(1); - this[commandName].apply(this, args); - } - return this; -}; -const multi = Pipeline.prototype.multi; -Pipeline.prototype.multi = function () { - this._transactions += 1; - return multi.apply(this, arguments); -}; -const execBuffer = Pipeline.prototype.execBuffer; -const exec = Pipeline.prototype.exec; -Pipeline.prototype.execBuffer = util_1.deprecate(function () { - if (this._transactions > 0) { - this._transactions -= 1; - } - return execBuffer.apply(this, arguments); -}, "Pipeline#execBuffer: Use Pipeline#exec instead"); -Pipeline.prototype.exec = function (callback) { - // Wait for the cluster to be connected, since we need nodes information before continuing - if (this.isCluster && !this.redis.slots.length) { - this.redis.delayUntilReady((err) => { - if (err) { - callback(err); - return; - } - this.exec(callback); - }); - return this.promise; - } - if (this._transactions > 0) { - this._transactions -= 1; - return (this.options.dropBufferSupport ? exec : execBuffer).apply(this, arguments); - } - if (!this.nodeifiedPromise) { - this.nodeifiedPromise = true; - standard_as_callback_1.default(this.promise, callback); - } - if (!this._queue.length) { - this.resolve([]); - } - let pipelineSlot; - if (this.isCluster) { - // List of the first key for each command - const sampleKeys = []; - for (let i = 0; i < this._queue.length; i++) { - const keys = this._queue[i].getKeys(); - if (keys.length) { - sampleKeys.push(keys[0]); - } - // For each command, check that the keys belong to the same slot - if (keys.length && calculateSlot.generateMulti(keys) < 0) { - this.reject(new Error("All the keys in a pipeline command should belong to the same slot")); - return this.promise; - } - } - if (sampleKeys.length) { - pipelineSlot = generateMultiWithNodes(this.redis, sampleKeys); - if (pipelineSlot < 0) { - this.reject(new Error("All keys in the pipeline should belong to the same slots allocation group")); - return this.promise; - } - } - else { - // Send the pipeline to a random node - pipelineSlot = (Math.random() * 16384) | 0; - } - } - // Check whether scripts exists - const scripts = []; - for (let i = 0; i < this._queue.length; ++i) { - const item = this._queue[i]; - if (item.name !== "evalsha") { - continue; - } - const script = this._shaToScript[item.args[0]]; - if (!script || this.redis._addedScriptHashes[script.sha]) { - continue; - } - scripts.push(script); - this.redis._addedScriptHashes[script.sha] = true; - } - const _this = this; - if (!scripts.length) { - return execPipeline(); - } - // In cluster mode, always load scripts before running the pipeline - if (this.isCluster) { - return pMap(scripts, (script) => _this.redis.script("load", script.lua), { - concurrency: 10, - }).then(execPipeline); - } - return this.redis - .script("exists", scripts.map(({ sha }) => sha)) - .then(function (results) { - const pending = []; - for (let i = 0; i < results.length; ++i) { - if (!results[i]) { - pending.push(scripts[i]); - } - } - const Promise = PromiseContainer.get(); - return Promise.all(pending.map(function (script) { - return _this.redis.script("load", script.lua); - })); - }) - .then(execPipeline); - function execPipeline() { - let data = ""; - let buffers; - let writePending = (_this.replyPending = _this._queue.length); - let node; - if (_this.isCluster) { - node = { - slot: pipelineSlot, - redis: _this.redis.connectionPool.nodes.all[_this.preferKey], - }; - } - let bufferMode = false; - const stream = { - write: function (writable) { - if (writable instanceof Buffer) { - bufferMode = true; - } - if (bufferMode) { - if (!buffers) { - buffers = []; - } - if (typeof data === "string") { - buffers.push(Buffer.from(data, "utf8")); - data = undefined; - } - buffers.push(typeof writable === "string" - ? Buffer.from(writable, "utf8") - : writable); - } - else { - data += writable; - } - if (!--writePending) { - let sendData; - if (buffers) { - sendData = Buffer.concat(buffers); - } - else { - sendData = data; - } - if (_this.isCluster) { - node.redis.stream.write(sendData); - } - else { - _this.redis.stream.write(sendData); - } - // Reset writePending for resending - writePending = _this._queue.length; - data = ""; - buffers = undefined; - bufferMode = false; - } - }, - }; - for (let i = 0; i < _this._queue.length; ++i) { - _this.redis.sendCommand(_this._queue[i], stream, node); - } - return _this.promise; - } + "msee": "cp1250", + "mscyrl": "cp1251", + "msansi": "cp1252", + "msgreek": "cp1253", + "msturk": "cp1254", + "mshebr": "cp1255", + "msarab": "cp1256", + "winbaltrim": "cp1257", + + "cp20866": "koi8r", + "20866": "koi8r", + "ibm878": "koi8r", + "cskoi8r": "koi8r", + + "cp21866": "koi8u", + "21866": "koi8u", + "ibm1168": "koi8u", + + "strk10482002": "rk1048", + + "tcvn5712": "tcvn", + "tcvn57121": "tcvn", + + "gb198880": "iso646cn", + "cn": "iso646cn", + + "csiso14jisc6220ro": "iso646jp", + "jisc62201969ro": "iso646jp", + "jp": "iso646jp", + + "cshproman8": "hproman8", + "r8": "hproman8", + "roman8": "hproman8", + "xroman8": "hproman8", + "ibm1051": "hproman8", + + "mac": "macintosh", + "csmacintosh": "macintosh", }; + /***/ }), -/***/ 71475: -/***/ ((__unused_webpack_module, exports) => { +/***/ 11155: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -function isPromise(obj) { - return (!!obj && - (typeof obj === "object" || typeof obj === "function") && - typeof obj.then === "function"); +var Buffer = __nccwpck_require__(15118).Buffer; + +// Note: UTF16-LE (or UCS2) codec is Node.js native. See encodings/internal.js + +// == UTF16-BE codec. ========================================================== + +exports.utf16be = Utf16BECodec; +function Utf16BECodec() { } -exports.isPromise = isPromise; -let promise = Promise; -function get() { - return promise; + +Utf16BECodec.prototype.encoder = Utf16BEEncoder; +Utf16BECodec.prototype.decoder = Utf16BEDecoder; +Utf16BECodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf16BEEncoder() { } -exports.get = get; -function set(lib) { - if (typeof lib !== "function") { - throw new Error(`Provided Promise must be a function, got ${lib}`); + +Utf16BEEncoder.prototype.write = function(str) { + var buf = Buffer.from(str, 'ucs2'); + for (var i = 0; i < buf.length; i += 2) { + var tmp = buf[i]; buf[i] = buf[i+1]; buf[i+1] = tmp; } - promise = lib; + return buf; } -exports.set = set; +Utf16BEEncoder.prototype.end = function() { +} -/***/ }), -/***/ 1422: -/***/ ((__unused_webpack_module, exports) => { +// -- Decoding -"use strict"; +function Utf16BEDecoder() { + this.overflowByte = -1; +} -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.DEFAULT_REDIS_OPTIONS = { - // Connection - port: 6379, - host: "localhost", - family: 4, - connectTimeout: 10000, - retryStrategy: function (times) { - return Math.min(times * 50, 2000); - }, - keepAlive: 0, - noDelay: true, - connectionName: null, - // Sentinel - sentinels: null, - name: null, - role: "master", - sentinelRetryStrategy: function (times) { - return Math.min(times * 10, 1000); - }, - natMap: null, - enableTLSForSentinelMode: false, - updateSentinels: true, - // Status - username: null, - password: null, - db: 0, - // Others - dropBufferSupport: false, - enableOfflineQueue: true, - enableReadyCheck: true, - autoResubscribe: true, - autoResendUnfulfilledCommands: true, - lazyConnect: false, - keyPrefix: "", - reconnectOnError: null, - readOnly: false, - stringNumbers: false, - maxRetriesPerRequest: 20, - maxLoadingRetryTime: 10000, - enableAutoPipelining: false, - autoPipeliningIgnoredCommands: [], - maxScriptsCachingTime: 60000, -}; +Utf16BEDecoder.prototype.write = function(buf) { + if (buf.length == 0) + return ''; + var buf2 = Buffer.alloc(buf.length + 1), + i = 0, j = 0; -/***/ }), + if (this.overflowByte !== -1) { + buf2[0] = buf[0]; + buf2[1] = this.overflowByte; + i = 1; j = 2; + } -/***/ 74276: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + for (; i < buf.length-1; i += 2, j+= 2) { + buf2[j] = buf[i+1]; + buf2[j+1] = buf[i]; + } -"use strict"; + this.overflowByte = (i == buf.length-1) ? buf[buf.length-1] : -1; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const redis_errors_1 = __nccwpck_require__(81879); -const command_1 = __nccwpck_require__(90803); -const errors_1 = __nccwpck_require__(23961); -const utils_1 = __nccwpck_require__(94832); -const DataHandler_1 = __nccwpck_require__(30545); -const debug = utils_1.Debug("connection"); -function connectHandler(self) { - return function () { - self.setStatus("connect"); - self.resetCommandQueue(); - // AUTH command should be processed before any other commands - let flushed = false; - const { connectionEpoch } = self; - if (self.condition.auth) { - self.auth(self.condition.auth, function (err) { - if (connectionEpoch !== self.connectionEpoch) { - return; - } - if (err) { - if (err.message.indexOf("no password is set") !== -1) { - console.warn("[WARN] Redis server does not require a password, but a password was supplied."); - } - else if (err.message.indexOf("without any password configured for the default user") !== -1) { - console.warn("[WARN] This Redis server's `default` user does not require a password, but a password was supplied"); - } - else if (err.message.indexOf("wrong number of arguments for 'auth' command") !== -1) { - console.warn(`[ERROR] The server returned "wrong number of arguments for 'auth' command". You are probably passing both username and password to Redis version 5 or below. You should only pass the 'password' option for Redis version 5 and under.`); - } - else { - flushed = true; - self.recoverFromFatalError(err, err); - } - } - }); - } - if (self.condition.select) { - self.select(self.condition.select); - } - if (!self.options.enableReadyCheck) { - exports.readyHandler(self)(); - } - /* - No need to keep the reference of DataHandler here - because we don't need to do the cleanup. - `Stream#end()` will remove all listeners for us. - */ - new DataHandler_1.default(self, { - stringNumbers: self.options.stringNumbers, - dropBufferSupport: self.options.dropBufferSupport, - }); - if (self.options.enableReadyCheck) { - self._readyCheck(function (err, info) { - if (connectionEpoch !== self.connectionEpoch) { - return; - } - if (err) { - if (!flushed) { - self.recoverFromFatalError(new Error("Ready check failed: " + err.message), err); - } - } - else { - self.serverInfo = info; - if (self.connector.check(info)) { - exports.readyHandler(self)(); - } - else { - self.disconnect(true); - } - } - }); - } - }; + return buf2.slice(0, j).toString('ucs2'); } -exports.connectHandler = connectHandler; -function abortError(command) { - const err = new redis_errors_1.AbortError("Command aborted due to connection close"); - err.command = { - name: command.name, - args: command.args, - }; - return err; + +Utf16BEDecoder.prototype.end = function() { } -// If a contiguous set of pipeline commands starts from index zero then they -// can be safely reattempted. If however we have a chain of pipelined commands -// starting at index 1 or more it means we received a partial response before -// the connection close and those pipelined commands must be aborted. For -// example, if the queue looks like this: [2, 3, 4, 0, 1, 2] then after -// aborting and purging we'll have a queue that looks like this: [0, 1, 2] -function abortIncompletePipelines(commandQueue) { - let expectedIndex = 0; - for (let i = 0; i < commandQueue.length;) { - const command = commandQueue.peekAt(i).command; - const pipelineIndex = command.pipelineIndex; - if (pipelineIndex === undefined || pipelineIndex === 0) { - expectedIndex = 0; - } - if (pipelineIndex !== undefined && pipelineIndex !== expectedIndex++) { - commandQueue.remove(i, 1); - command.reject(abortError(command)); - continue; - } - i++; - } + + +// == UTF-16 codec ============================================================= +// Decoder chooses automatically from UTF-16LE and UTF-16BE using BOM and space-based heuristic. +// Defaults to UTF-16LE, as it's prevalent and default in Node. +// http://en.wikipedia.org/wiki/UTF-16 and http://encoding.spec.whatwg.org/#utf-16le +// Decoder default can be changed: iconv.decode(buf, 'utf16', {defaultEncoding: 'utf-16be'}); + +// Encoder uses UTF-16LE and prepends BOM (which can be overridden with addBOM: false). + +exports.utf16 = Utf16Codec; +function Utf16Codec(codecOptions, iconv) { + this.iconv = iconv; } -// If only a partial transaction result was received before connection close, -// we have to abort any transaction fragments that may have ended up in the -// offline queue -function abortTransactionFragments(commandQueue) { - for (let i = 0; i < commandQueue.length;) { - const command = commandQueue.peekAt(i).command; - if (command.name === "multi") { - break; - } - if (command.name === "exec") { - commandQueue.remove(i, 1); - command.reject(abortError(command)); - break; - } - if (command.inTransaction) { - commandQueue.remove(i, 1); - command.reject(abortError(command)); - } - else { - i++; - } - } + +Utf16Codec.prototype.encoder = Utf16Encoder; +Utf16Codec.prototype.decoder = Utf16Decoder; + + +// -- Encoding (pass-through) + +function Utf16Encoder(options, codec) { + options = options || {}; + if (options.addBOM === undefined) + options.addBOM = true; + this.encoder = codec.iconv.getEncoder('utf-16le', options); } -function closeHandler(self) { - return function () { - self.setStatus("close"); - if (!self.prevCondition) { - self.prevCondition = self.condition; - } - if (self.commandQueue.length) { - abortIncompletePipelines(self.commandQueue); - self.prevCommandQueue = self.commandQueue; - } - if (self.offlineQueue.length) { - abortTransactionFragments(self.offlineQueue); - } - if (self.manuallyClosing) { - self.manuallyClosing = false; - debug("skip reconnecting since the connection is manually closed."); - return close(); - } - if (typeof self.options.retryStrategy !== "function") { - debug("skip reconnecting because `retryStrategy` is not a function"); - return close(); - } - const retryDelay = self.options.retryStrategy(++self.retryAttempts); - if (typeof retryDelay !== "number") { - debug("skip reconnecting because `retryStrategy` doesn't return a number"); - return close(); - } - debug("reconnect in %sms", retryDelay); - self.setStatus("reconnecting", retryDelay); - self.reconnectTimeout = setTimeout(function () { - self.reconnectTimeout = null; - self.connect().catch(utils_1.noop); - }, retryDelay); - const { maxRetriesPerRequest } = self.options; - if (typeof maxRetriesPerRequest === "number") { - if (maxRetriesPerRequest < 0) { - debug("maxRetriesPerRequest is negative, ignoring..."); - } - else { - const remainder = self.retryAttempts % (maxRetriesPerRequest + 1); - if (remainder === 0) { - debug("reach maxRetriesPerRequest limitation, flushing command queue..."); - self.flushQueue(new errors_1.MaxRetriesPerRequestError(maxRetriesPerRequest)); - } - } - } - }; - function close() { - self.setStatus("end"); - self.flushQueue(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + +Utf16Encoder.prototype.write = function(str) { + return this.encoder.write(str); +} + +Utf16Encoder.prototype.end = function() { + return this.encoder.end(); +} + + +// -- Decoding + +function Utf16Decoder(options, codec) { + this.decoder = null; + this.initialBytes = []; + this.initialBytesLen = 0; + + this.options = options || {}; + this.iconv = codec.iconv; +} + +Utf16Decoder.prototype.write = function(buf) { + if (!this.decoder) { + // Codec is not chosen yet. Accumulate initial bytes. + this.initialBytes.push(buf); + this.initialBytesLen += buf.length; + + if (this.initialBytesLen < 16) // We need more bytes to use space heuristic (see below) + return ''; + + // We have enough bytes -> detect endianness. + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + this.initialBytes.length = this.initialBytesLen = 0; } + + return this.decoder.write(buf); } -exports.closeHandler = closeHandler; -function errorHandler(self) { - return function (error) { - debug("error: %s", error); - self.silentEmit("error", error); - }; + +Utf16Decoder.prototype.end = function() { + if (!this.decoder) { + var buf = Buffer.concat(this.initialBytes), + encoding = detectEncoding(buf, this.options.defaultEncoding); + this.decoder = this.iconv.getDecoder(encoding, this.options); + + var res = this.decoder.write(buf), + trail = this.decoder.end(); + + return trail ? (res + trail) : res; + } + return this.decoder.end(); } -exports.errorHandler = errorHandler; -function readyHandler(self) { - return function () { - self.setStatus("ready"); - self.retryAttempts = 0; - if (self.options.monitor) { - self.call("monitor"); - const { sendCommand } = self; - self.sendCommand = function (command) { - if (command_1.default.checkFlag("VALID_IN_MONITOR_MODE", command.name)) { - return sendCommand.call(self, command); - } - command.reject(new Error("Connection is in monitoring mode, can't process commands.")); - return command.promise; - }; - self.once("close", function () { - delete self.sendCommand; - }); - self.setStatus("monitoring"); - return; - } - const finalSelect = self.prevCondition - ? self.prevCondition.select - : self.condition.select; - if (self.options.connectionName) { - debug("set the connection name [%s]", self.options.connectionName); - self.client("setname", self.options.connectionName).catch(utils_1.noop); - } - if (self.options.readOnly) { - debug("set the connection to readonly mode"); - self.readonly().catch(utils_1.noop); - } - if (self.prevCondition) { - const condition = self.prevCondition; - self.prevCondition = null; - if (condition.subscriber && self.options.autoResubscribe) { - // We re-select the previous db first since - // `SELECT` command is not valid in sub mode. - if (self.condition.select !== finalSelect) { - debug("connect to db [%d]", finalSelect); - self.select(finalSelect); - } - const subscribeChannels = condition.subscriber.channels("subscribe"); - if (subscribeChannels.length) { - debug("subscribe %d channels", subscribeChannels.length); - self.subscribe(subscribeChannels); - } - const psubscribeChannels = condition.subscriber.channels("psubscribe"); - if (psubscribeChannels.length) { - debug("psubscribe %d channels", psubscribeChannels.length); - self.psubscribe(psubscribeChannels); - } - } - } - if (self.prevCommandQueue) { - if (self.options.autoResendUnfulfilledCommands) { - debug("resend %d unfulfilled commands", self.prevCommandQueue.length); - while (self.prevCommandQueue.length > 0) { - const item = self.prevCommandQueue.shift(); - if (item.select !== self.condition.select && - item.command.name !== "select") { - self.select(item.select); - } - self.sendCommand(item.command, item.stream); - } - } - else { - self.prevCommandQueue = null; - } - } - if (self.offlineQueue.length) { - debug("send %d commands in offline queue", self.offlineQueue.length); - const offlineQueue = self.offlineQueue; - self.resetOfflineQueue(); - while (offlineQueue.length > 0) { - const item = offlineQueue.shift(); - if (item.select !== self.condition.select && - item.command.name !== "select") { - self.select(item.select); - } - self.sendCommand(item.command, item.stream); + +function detectEncoding(buf, defaultEncoding) { + var enc = defaultEncoding || 'utf-16le'; + + if (buf.length >= 2) { + // Check BOM. + if (buf[0] == 0xFE && buf[1] == 0xFF) // UTF-16BE BOM + enc = 'utf-16be'; + else if (buf[0] == 0xFF && buf[1] == 0xFE) // UTF-16LE BOM + enc = 'utf-16le'; + else { + // No BOM found. Try to deduce encoding from initial content. + // Most of the time, the content has ASCII chars (U+00**), but the opposite (U+**00) is uncommon. + // So, we count ASCII as if it was LE or BE, and decide from that. + var asciiCharsLE = 0, asciiCharsBE = 0, // Counts of chars in both positions + _len = Math.min(buf.length - (buf.length % 2), 64); // Len is always even. + + for (var i = 0; i < _len; i += 2) { + if (buf[i] === 0 && buf[i+1] !== 0) asciiCharsBE++; + if (buf[i] !== 0 && buf[i+1] === 0) asciiCharsLE++; } + + if (asciiCharsBE > asciiCharsLE) + enc = 'utf-16be'; + else if (asciiCharsBE < asciiCharsLE) + enc = 'utf-16le'; } - if (self.condition.select !== finalSelect) { - debug("connect to db [%d]", finalSelect); - self.select(finalSelect); - } - }; + } + + return enc; } -exports.readyHandler = readyHandler; + + /***/ }), -/***/ 83609: +/***/ 51644: /***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const lodash_1 = __nccwpck_require__(20961); -const util_1 = __nccwpck_require__(31669); -const events_1 = __nccwpck_require__(28614); -const Deque = __nccwpck_require__(42342); -const command_1 = __nccwpck_require__(90803); -const commander_1 = __nccwpck_require__(33642); -const utils_1 = __nccwpck_require__(94832); -const standard_as_callback_1 = __nccwpck_require__(91543); -const eventHandler = __nccwpck_require__(74276); -const connectors_1 = __nccwpck_require__(72340); -const ScanStream_1 = __nccwpck_require__(6134); -const commands = __nccwpck_require__(98020); -const PromiseContainer = __nccwpck_require__(71475); -const transaction_1 = __nccwpck_require__(14645); -const RedisOptions_1 = __nccwpck_require__(1422); -const debug = utils_1.Debug("redis"); -/** - * Creates a Redis instance - * - * @constructor - * @param {(number|string|Object)} [port=6379] - Port of the Redis server, - * or a URL string(see the examples below), - * or the `options` object(see the third argument). - * @param {string|Object} [host=localhost] - Host of the Redis server, - * when the first argument is a URL string, - * this argument is an object represents the options. - * @param {Object} [options] - Other options. - * @param {number} [options.port=6379] - Port of the Redis server. - * @param {string} [options.host=localhost] - Host of the Redis server. - * @param {string} [options.family=4] - Version of IP stack. Defaults to 4. - * @param {string} [options.path=null] - Local domain socket path. If set the `port`, - * `host` and `family` will be ignored. - * @param {number} [options.keepAlive=0] - TCP KeepAlive on the socket with a X ms delay before start. - * Set to a non-number value to disable keepAlive. - * @param {boolean} [options.noDelay=true] - Whether to disable the Nagle's Algorithm. By default we disable - * it to reduce the latency. - * @param {string} [options.connectionName=null] - Connection name. - * @param {number} [options.db=0] - Database index to use. - * @param {string} [options.username=null] - If set, client will send AUTH command with this user and password when connected. - * @param {string} [options.password=null] - If set, client will send AUTH command - * with the value of this option when connected. - * @param {boolean} [options.dropBufferSupport=false] - Drop the buffer support for better performance. - * This option is recommended to be enabled when - * handling large array response and you don't need the buffer support. - * @param {boolean} [options.enableReadyCheck=true] - When a connection is established to - * the Redis server, the server might still be loading the database from disk. - * While loading, the server not respond to any commands. - * To work around this, when this option is `true`, - * ioredis will check the status of the Redis server, - * and when the Redis server is able to process commands, - * a `ready` event will be emitted. - * @param {boolean} [options.enableOfflineQueue=true] - By default, - * if there is no active connection to the Redis server, - * commands are added to a queue and are executed once the connection is "ready" - * (when `enableReadyCheck` is `true`, - * "ready" means the Redis server has loaded the database from disk, otherwise means the connection - * to the Redis server has been established). If this option is false, - * when execute the command when the connection isn't ready, an error will be returned. - * @param {number} [options.connectTimeout=10000] - The milliseconds before a timeout occurs during the initial - * connection to the Redis server. - * @param {boolean} [options.autoResubscribe=true] - After reconnected, if the previous connection was in the - * subscriber mode, client will auto re-subscribe these channels. - * @param {boolean} [options.autoResendUnfulfilledCommands=true] - If true, client will resend unfulfilled - * commands(e.g. block commands) in the previous connection when reconnected. - * @param {boolean} [options.lazyConnect=false] - By default, - * When a new `Redis` instance is created, it will connect to Redis server automatically. - * If you want to keep the instance disconnected until a command is called, you can pass the `lazyConnect` option to - * the constructor: - * - * ```javascript - * var redis = new Redis({ lazyConnect: true }); - * // No attempting to connect to the Redis server here. +var Buffer = __nccwpck_require__(15118).Buffer; - * // Now let's connect to the Redis server - * redis.get('foo', function () { - * }); - * ``` - * @param {Object} [options.tls] - TLS connection support. See https://github.com/luin/ioredis#tls-options - * @param {string} [options.keyPrefix=''] - The prefix to prepend to all keys in a command. - * @param {function} [options.retryStrategy] - See "Quick Start" section - * @param {number} [options.maxRetriesPerRequest] - See "Quick Start" section - * @param {number} [options.maxLoadingRetryTime=10000] - when redis server is not ready, we will wait for - * `loading_eta_seconds` from `info` command or maxLoadingRetryTime (milliseconds), whichever is smaller. - * @param {function} [options.reconnectOnError] - See "Quick Start" section - * @param {boolean} [options.readOnly=false] - Enable READONLY mode for the connection. - * Only available for cluster mode. - * @param {boolean} [options.stringNumbers=false] - Force numbers to be always returned as JavaScript - * strings. This option is necessary when dealing with big numbers (exceed the [-2^53, +2^53] range). - * @param {boolean} [options.enableTLSForSentinelMode=false] - Whether to support the `tls` option - * when connecting to Redis via sentinel mode. - * @param {NatMap} [options.natMap=null] NAT map for sentinel connector. - * @param {boolean} [options.updateSentinels=true] - Update the given `sentinels` list with new IP - * addresses when communicating with existing sentinels. -* @param {boolean} [options.enableAutoPipelining=false] - When enabled, all commands issued during an event loop - * iteration are automatically wrapped in a pipeline and sent to the server at the same time. - * This can dramatically improve performance. - * @param {string[]} [options.autoPipeliningIgnoredCommands=[]] - The list of commands which must not be automatically wrapped in pipelines. - * @param {number} [options.maxScriptsCachingTime=60000] Default script definition caching time. - * @extends [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter) - * @extends Commander - * @example - * ```js - * var Redis = require('ioredis'); - * - * var redis = new Redis(); - * - * var redisOnPort6380 = new Redis(6380); - * var anotherRedis = new Redis(6380, '192.168.100.1'); - * var unixSocketRedis = new Redis({ path: '/tmp/echo.sock' }); - * var unixSocketRedis2 = new Redis('/tmp/echo.sock'); - * var urlRedis = new Redis('redis://user:password@redis-service.com:6379/'); - * var urlRedis2 = new Redis('//localhost:6379'); - * var urlRedisTls = new Redis('rediss://user:password@redis-service.com:6379/'); - * var authedRedis = new Redis(6380, '192.168.100.1', { password: 'password' }); - * ``` - */ -exports.default = Redis; -function Redis() { - if (!(this instanceof Redis)) { - console.error(new Error("Calling `Redis()` like a function is deprecated. Using `new Redis()` instead.").stack.replace("Error", "Warning")); - return new Redis(arguments[0], arguments[1], arguments[2]); - } - this.parseOptions(arguments[0], arguments[1], arguments[2]); - events_1.EventEmitter.call(this); - commander_1.default.call(this); - this.resetCommandQueue(); - this.resetOfflineQueue(); - this.connectionEpoch = 0; - if (this.options.Connector) { - this.connector = new this.options.Connector(this.options); - } - else if (this.options.sentinels) { - this.connector = new connectors_1.SentinelConnector(this.options); - } - else { - this.connector = new connectors_1.StandaloneConnector(this.options); - } - this.retryAttempts = 0; - // Prepare a cache of scripts and setup a interval which regularly clears it - this._addedScriptHashes = {}; - // Prepare autopipelines structures - this._autoPipelines = new Map(); - this._runningAutoPipelines = new Set(); - Object.defineProperty(this, "autoPipelineQueueSize", { - get() { - let queued = 0; - for (const pipeline of this._autoPipelines.values()) { - queued += pipeline.length; - } - return queued; - }, - }); - // end(or wait) -> connecting -> connect -> ready -> end - if (this.options.lazyConnect) { - this.setStatus("wait"); - } - else { - this.connect().catch(lodash_1.noop); - } -} -util_1.inherits(Redis, events_1.EventEmitter); -Object.assign(Redis.prototype, commander_1.default.prototype); -/** - * Create a Redis instance - * - * @deprecated - */ -// @ts-ignore -Redis.createClient = function (...args) { - // @ts-ignore - return new Redis(...args); -}; -/** - * Default options - * - * @var defaultOptions - * @private - */ -Redis.defaultOptions = RedisOptions_1.DEFAULT_REDIS_OPTIONS; -Redis.prototype.resetCommandQueue = function () { - this.commandQueue = new Deque(); -}; -Redis.prototype.resetOfflineQueue = function () { - this.offlineQueue = new Deque(); -}; -Redis.prototype.parseOptions = function () { - this.options = {}; - let isTls = false; - for (let i = 0; i < arguments.length; ++i) { - const arg = arguments[i]; - if (arg === null || typeof arg === "undefined") { - continue; - } - if (typeof arg === "object") { - lodash_1.defaults(this.options, arg); - } - else if (typeof arg === "string") { - lodash_1.defaults(this.options, utils_1.parseURL(arg)); - if (arg.startsWith("rediss://")) { - isTls = true; - } - } - else if (typeof arg === "number") { - this.options.port = arg; - } - else { - throw new Error("Invalid argument " + arg); - } - } - if (isTls) { - lodash_1.defaults(this.options, { tls: true }); - } - lodash_1.defaults(this.options, Redis.defaultOptions); - if (typeof this.options.port === "string") { - this.options.port = parseInt(this.options.port, 10); - } - if (typeof this.options.db === "string") { - this.options.db = parseInt(this.options.db, 10); - } - if (this.options.parser === "hiredis") { - console.warn("Hiredis parser is abandoned since ioredis v3.0, and JavaScript parser will be used"); - } -}; -/** - * Change instance's status - * @private - */ -Redis.prototype.setStatus = function (status, arg) { - // @ts-ignore - if (debug.enabled) { - debug("status[%s]: %s -> %s", this._getDescription(), this.status || "[empty]", status); - } - this.status = status; - process.nextTick(this.emit.bind(this, status, arg)); -}; -/** - * Create a connection to Redis. - * This method will be invoked automatically when creating a new Redis instance - * unless `lazyConnect: true` is passed. - * - * When calling this method manually, a Promise is returned, which will - * be resolved when the connection status is ready. - * @param {function} [callback] - * @return {Promise} - * @public - */ -Redis.prototype.connect = function (callback) { - const _Promise = PromiseContainer.get(); - const promise = new _Promise((resolve, reject) => { - if (this.status === "connecting" || - this.status === "connect" || - this.status === "ready") { - reject(new Error("Redis is already connecting/connected")); - return; - } - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = setInterval(() => { - this._addedScriptHashes = {}; - }, this.options.maxScriptsCachingTime); - this.connectionEpoch += 1; - this.setStatus("connecting"); - const { options } = this; - this.condition = { - select: options.db, - auth: options.username - ? [options.username, options.password] - : options.password, - subscriber: false, - }; - const _this = this; - standard_as_callback_1.default(this.connector.connect(function (type, err) { - _this.silentEmit(type, err); - }), function (err, stream) { - if (err) { - _this.flushQueue(err); - _this.silentEmit("error", err); - reject(err); - _this.setStatus("end"); - return; - } - let CONNECT_EVENT = options.tls ? "secureConnect" : "connect"; - if (options.sentinels && !options.enableTLSForSentinelMode) { - CONNECT_EVENT = "connect"; - } - _this.stream = stream; - if (typeof options.keepAlive === "number") { - stream.setKeepAlive(true, options.keepAlive); - } - if (stream.connecting) { - stream.once(CONNECT_EVENT, eventHandler.connectHandler(_this)); - if (options.connectTimeout) { - /* - * Typically, Socket#setTimeout(0) will clear the timer - * set before. However, in some platforms (Electron 3.x~4.x), - * the timer will not be cleared. So we introduce a variable here. - * - * See https://github.com/electron/electron/issues/14915 - */ - let connectTimeoutCleared = false; - stream.setTimeout(options.connectTimeout, function () { - if (connectTimeoutCleared) { - return; - } - stream.setTimeout(0); - stream.destroy(); - const err = new Error("connect ETIMEDOUT"); - // @ts-ignore - err.errorno = "ETIMEDOUT"; - // @ts-ignore - err.code = "ETIMEDOUT"; - // @ts-ignore - err.syscall = "connect"; - eventHandler.errorHandler(_this)(err); - }); - stream.once(CONNECT_EVENT, function () { - connectTimeoutCleared = true; - stream.setTimeout(0); - }); - } - } - else { - process.nextTick(eventHandler.connectHandler(_this)); - } - stream.once("error", eventHandler.errorHandler(_this)); - stream.once("close", eventHandler.closeHandler(_this)); - if (options.noDelay) { - stream.setNoDelay(true); - } - const connectionReadyHandler = function () { - _this.removeListener("close", connectionCloseHandler); - resolve(); - }; - var connectionCloseHandler = function () { - _this.removeListener("ready", connectionReadyHandler); - reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); - }; - _this.once("ready", connectionReadyHandler); - _this.once("close", connectionCloseHandler); - }); - }); - return standard_as_callback_1.default(promise, callback); -}; -/** - * Disconnect from Redis. - * - * This method closes the connection immediately, - * and may lose some pending replies that haven't written to client. - * If you want to wait for the pending replies, use Redis#quit instead. - * @public - */ -Redis.prototype.disconnect = function (reconnect) { - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = null; - if (!reconnect) { - this.manuallyClosing = true; - } - if (this.reconnectTimeout && !reconnect) { - clearTimeout(this.reconnectTimeout); - this.reconnectTimeout = null; - } - if (this.status === "wait") { - eventHandler.closeHandler(this)(); - } - else { - this.connector.disconnect(); - } -}; -/** - * Disconnect from Redis. - * - * @deprecated - */ -Redis.prototype.end = function () { - this.disconnect(); -}; -/** - * Create a new instance with the same options as the current one. - * - * @example - * ```js - * var redis = new Redis(6380); - * var anotherRedis = redis.duplicate(); - * ``` - * - * @public - */ -Redis.prototype.duplicate = function (override) { - return new Redis(Object.assign({}, this.options, override || {})); -}; -Redis.prototype.recoverFromFatalError = function (commandError, err, options) { - this.flushQueue(err, options); - this.silentEmit("error", err); - this.disconnect(true); -}; -Redis.prototype.handleReconnection = function handleReconnection(err, item) { - let needReconnect = false; - if (this.options.reconnectOnError) { - needReconnect = this.options.reconnectOnError(err); - } - switch (needReconnect) { - case 1: - case true: - if (this.status !== "reconnecting") { - this.disconnect(true); - } - item.command.reject(err); - break; - case 2: - if (this.status !== "reconnecting") { - this.disconnect(true); - } - if (this.condition.select !== item.select && - item.command.name !== "select") { - this.select(item.select); - } - this.sendCommand(item.command); - break; - default: - item.command.reject(err); - } +// UTF-7 codec, according to https://tools.ietf.org/html/rfc2152 +// See also below a UTF-7-IMAP codec, according to http://tools.ietf.org/html/rfc3501#section-5.1.3 + +exports.utf7 = Utf7Codec; +exports.unicode11utf7 = 'utf7'; // Alias UNICODE-1-1-UTF-7 +function Utf7Codec(codecOptions, iconv) { + this.iconv = iconv; }; -/** - * Flush offline queue and command queue with error. - * - * @param {Error} error - The error object to send to the commands - * @param {object} options - * @private - */ -Redis.prototype.flushQueue = function (error, options) { - options = lodash_1.defaults({}, options, { - offlineQueue: true, - commandQueue: true, - }); - let item; - if (options.offlineQueue) { - while (this.offlineQueue.length > 0) { - item = this.offlineQueue.shift(); - item.command.reject(error); - } - } - if (options.commandQueue) { - if (this.commandQueue.length > 0) { - if (this.stream) { - this.stream.removeAllListeners("data"); + +Utf7Codec.prototype.encoder = Utf7Encoder; +Utf7Codec.prototype.decoder = Utf7Decoder; +Utf7Codec.prototype.bomAware = true; + + +// -- Encoding + +var nonDirectChars = /[^A-Za-z0-9'\(\),-\.\/:\? \n\r\t]+/g; + +function Utf7Encoder(options, codec) { + this.iconv = codec.iconv; +} + +Utf7Encoder.prototype.write = function(str) { + // Naive implementation. + // Non-direct chars are encoded as "+-"; single "+" char is encoded as "+-". + return Buffer.from(str.replace(nonDirectChars, function(chunk) { + return "+" + (chunk === '+' ? '' : + this.iconv.encode(chunk, 'utf16-be').toString('base64').replace(/=+$/, '')) + + "-"; + }.bind(this))); +} + +Utf7Encoder.prototype.end = function() { +} + + +// -- Decoding + +function Utf7Decoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64Regex = /[A-Za-z0-9\/+]/; +var base64Chars = []; +for (var i = 0; i < 256; i++) + base64Chars[i] = base64Regex.test(String.fromCharCode(i)); + +var plusChar = '+'.charCodeAt(0), + minusChar = '-'.charCodeAt(0), + andChar = '&'.charCodeAt(0); + +Utf7Decoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '+' + if (buf[i] == plusChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; } - while (this.commandQueue.length > 0) { - item = this.commandQueue.shift(); - item.command.reject(error); + } else { // We decode base64. + if (!base64Chars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) {// "+-" -> "+" + res += "+"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString(); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus is absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; } } } + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString(); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7Decoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + +// UTF-7-IMAP codec. +// RFC3501 Sec. 5.1.3 Modified UTF-7 (http://tools.ietf.org/html/rfc3501#section-5.1.3) +// Differences: +// * Base64 part is started by "&" instead of "+" +// * Direct characters are 0x20-0x7E, except "&" (0x26) +// * In Base64, "," is used instead of "/" +// * Base64 must not be used to represent direct characters. +// * No implicit shift back from Base64 (should always end with '-') +// * String must end in non-shifted position. +// * "-&" while in base64 is not allowed. + + +exports.utf7imap = Utf7IMAPCodec; +function Utf7IMAPCodec(codecOptions, iconv) { + this.iconv = iconv; }; -/** - * Check whether Redis has finished loading the persistent data and is able to - * process commands. - * - * @param {Function} callback - * @private - */ -Redis.prototype._readyCheck = function (callback) { - const _this = this; - this.info(function (err, res) { - if (err) { - return callback(err); - } - if (typeof res !== "string") { - return callback(null, res); - } - const info = {}; - const lines = res.split("\r\n"); - for (let i = 0; i < lines.length; ++i) { - const [fieldName, ...fieldValueParts] = lines[i].split(":"); - const fieldValue = fieldValueParts.join(":"); - if (fieldValue) { - info[fieldName] = fieldValue; + +Utf7IMAPCodec.prototype.encoder = Utf7IMAPEncoder; +Utf7IMAPCodec.prototype.decoder = Utf7IMAPDecoder; +Utf7IMAPCodec.prototype.bomAware = true; + + +// -- Encoding + +function Utf7IMAPEncoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = Buffer.alloc(6); + this.base64AccumIdx = 0; +} + +Utf7IMAPEncoder.prototype.write = function(str) { + var inBase64 = this.inBase64, + base64Accum = this.base64Accum, + base64AccumIdx = this.base64AccumIdx, + buf = Buffer.alloc(str.length*5 + 10), bufIdx = 0; + + for (var i = 0; i < str.length; i++) { + var uChar = str.charCodeAt(i); + if (0x20 <= uChar && uChar <= 0x7E) { // Direct character or '&'. + if (inBase64) { + if (base64AccumIdx > 0) { + bufIdx += buf.write(base64Accum.slice(0, base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + base64AccumIdx = 0; + } + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + inBase64 = false; } - } - if (!info.loading || info.loading === "0") { - callback(null, info); - } - else { - const loadingEtaMs = (info.loading_eta_seconds || 1) * 1000; - const retryTime = _this.options.maxLoadingRetryTime && - _this.options.maxLoadingRetryTime < loadingEtaMs - ? _this.options.maxLoadingRetryTime - : loadingEtaMs; - debug("Redis server still loading, trying again in " + retryTime + "ms"); - setTimeout(function () { - _this._readyCheck(callback); - }, retryTime); - } - }); -}; -/** - * Emit only when there's at least one listener. - * - * @param {string} eventName - Event to emit - * @param {...*} arguments - Arguments - * @return {boolean} Returns true if event had listeners, false otherwise. - * @private - */ -Redis.prototype.silentEmit = function (eventName) { - let error; - if (eventName === "error") { - error = arguments[1]; - if (this.status === "end") { - return; - } - if (this.manuallyClosing) { - // ignore connection related errors when manually disconnecting - if (error instanceof Error && - (error.message === utils_1.CONNECTION_CLOSED_ERROR_MSG || - // @ts-ignore - error.syscall === "connect" || - // @ts-ignore - error.syscall === "read")) { - return; + + if (!inBase64) { + buf[bufIdx++] = uChar; // Write direct character + + if (uChar === andChar) // Ampersand -> '&-' + buf[bufIdx++] = minusChar; + } + + } else { // Non-direct character + if (!inBase64) { + buf[bufIdx++] = andChar; // Write '&', then go to base64 mode. + inBase64 = true; + } + if (inBase64) { + base64Accum[base64AccumIdx++] = uChar >> 8; + base64Accum[base64AccumIdx++] = uChar & 0xFF; + + if (base64AccumIdx == base64Accum.length) { + bufIdx += buf.write(base64Accum.toString('base64').replace(/\//g, ','), bufIdx); + base64AccumIdx = 0; + } } } } - if (this.listeners(eventName).length > 0) { - return this.emit.apply(this, arguments); - } - if (error && error instanceof Error) { - console.error("[ioredis] Unhandled error event:", error.stack); - } - return false; -}; -/** - * Listen for all requests received by the server in real time. - * - * This command will create a new connection to Redis and send a - * MONITOR command via the new connection in order to avoid disturbing - * the current connection. - * - * @param {function} [callback] The callback function. If omit, a promise will be returned. - * @example - * ```js - * var redis = new Redis(); - * redis.monitor(function (err, monitor) { - * // Entering monitoring mode. - * monitor.on('monitor', function (time, args, source, database) { - * console.log(time + ": " + util.inspect(args)); - * }); - * }); - * - * // supports promise as well as other commands - * redis.monitor().then(function (monitor) { - * monitor.on('monitor', function (time, args, source, database) { - * console.log(time + ": " + util.inspect(args)); - * }); - * }); - * ``` - * @public - */ -Redis.prototype.monitor = function (callback) { - const monitorInstance = this.duplicate({ - monitor: true, - lazyConnect: false, - }); - const Promise = PromiseContainer.get(); - return standard_as_callback_1.default(new Promise(function (resolve) { - monitorInstance.once("monitoring", function () { - resolve(monitorInstance); - }); - }), callback); -}; -transaction_1.addTransactionSupport(Redis.prototype); -/** - * Send a command to Redis - * - * This method is used internally by the `Redis#set`, `Redis#lpush` etc. - * Most of the time you won't invoke this method directly. - * However when you want to send a command that is not supported by ioredis yet, - * this command will be useful. - * - * @method sendCommand - * @memberOf Redis# - * @param {Command} command - The Command instance to send. - * @see {@link Command} - * @example - * ```js - * var redis = new Redis(); - * - * // Use callback - * var get = new Command('get', ['foo'], 'utf8', function (err, result) { - * console.log(result); - * }); - * redis.sendCommand(get); - * - * // Use promise - * var set = new Command('set', ['foo', 'bar'], 'utf8'); - * set.promise.then(function (result) { - * console.log(result); - * }); - * redis.sendCommand(set); - * ``` - * @private - */ -Redis.prototype.sendCommand = function (command, stream) { - if (this.status === "wait") { - this.connect().catch(lodash_1.noop); - } - if (this.status === "end") { - command.reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); - return command.promise; - } - if (this.condition.subscriber && - !command_1.default.checkFlag("VALID_IN_SUBSCRIBER_MODE", command.name)) { - command.reject(new Error("Connection in subscriber mode, only subscriber commands may be used")); - return command.promise; - } - if (command.name === "quit") { - clearInterval(this._addedScriptHashesCleanInterval); - this._addedScriptHashesCleanInterval = null; - } - let writable = this.status === "ready" || - (!stream && - this.status === "connect" && - commands.exists(command.name) && - commands.hasFlag(command.name, "loading")); - if (!this.stream) { - writable = false; - } - else if (!this.stream.writable) { - writable = false; - } - else if (this.stream._writableState && this.stream._writableState.ended) { - // https://github.com/iojs/io.js/pull/1217 - writable = false; - } - if (!writable && !this.options.enableOfflineQueue) { - command.reject(new Error("Stream isn't writeable and enableOfflineQueue options is false")); - return command.promise; - } - if (!writable && command.name === "quit" && this.offlineQueue.length === 0) { - this.disconnect(); - command.resolve(Buffer.from("OK")); - return command.promise; - } - if (writable) { - // @ts-ignore - if (debug.enabled) { - debug("write command[%s]: %d -> %s(%o)", this._getDescription(), this.condition.select, command.name, command.args); - } - (stream || this.stream).write(command.toWritable()); - this.commandQueue.push({ - command: command, - stream: stream, - select: this.condition.select, - }); - if (command_1.default.checkFlag("WILL_DISCONNECT", command.name)) { - this.manuallyClosing = true; - } - } - else if (this.options.enableOfflineQueue) { - // @ts-ignore - if (debug.enabled) { - debug("queue command[%s]: %d -> %s(%o)", this._getDescription(), this.condition.select, command.name, command.args); + + this.inBase64 = inBase64; + this.base64AccumIdx = base64AccumIdx; + + return buf.slice(0, bufIdx); +} + +Utf7IMAPEncoder.prototype.end = function() { + var buf = Buffer.alloc(10), bufIdx = 0; + if (this.inBase64) { + if (this.base64AccumIdx > 0) { + bufIdx += buf.write(this.base64Accum.slice(0, this.base64AccumIdx).toString('base64').replace(/\//g, ',').replace(/=+$/, ''), bufIdx); + this.base64AccumIdx = 0; } - this.offlineQueue.push({ - command: command, - stream: stream, - select: this.condition.select, - }); + + buf[bufIdx++] = minusChar; // Write '-', then go to direct mode. + this.inBase64 = false; } - if (command.name === "select" && utils_1.isInt(command.args[0])) { - const db = parseInt(command.args[0], 10); - if (this.condition.select !== db) { - this.condition.select = db; - this.emit("select", db); - debug("switch to db [%d]", this.condition.select); + + return buf.slice(0, bufIdx); +} + + +// -- Decoding + +function Utf7IMAPDecoder(options, codec) { + this.iconv = codec.iconv; + this.inBase64 = false; + this.base64Accum = ''; +} + +var base64IMAPChars = base64Chars.slice(); +base64IMAPChars[','.charCodeAt(0)] = true; + +Utf7IMAPDecoder.prototype.write = function(buf) { + var res = "", lastI = 0, + inBase64 = this.inBase64, + base64Accum = this.base64Accum; + + // The decoder is more involved as we must handle chunks in stream. + // It is forgiving, closer to standard UTF-7 (for example, '-' is optional at the end). + + for (var i = 0; i < buf.length; i++) { + if (!inBase64) { // We're in direct mode. + // Write direct chars until '&' + if (buf[i] == andChar) { + res += this.iconv.decode(buf.slice(lastI, i), "ascii"); // Write direct chars. + lastI = i+1; + inBase64 = true; + } + } else { // We decode base64. + if (!base64IMAPChars[buf[i]]) { // Base64 ended. + if (i == lastI && buf[i] == minusChar) { // "&-" -> "&" + res += "&"; + } else { + var b64str = base64Accum + buf.slice(lastI, i).toString().replace(/,/g, '/'); + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); + } + + if (buf[i] != minusChar) // Minus may be absorbed after base64. + i--; + + lastI = i+1; + inBase64 = false; + base64Accum = ''; + } } } - return command.promise; -}; -/** - * Get description of the connection. Used for debugging. - * @private - */ -Redis.prototype._getDescription = function () { - let description; - if (this.options.path) { - description = this.options.path; - } - else if (this.stream && - this.stream.remoteAddress && - this.stream.remotePort) { - description = this.stream.remoteAddress + ":" + this.stream.remotePort; - } - else { - description = this.options.host + ":" + this.options.port; + + if (!inBase64) { + res += this.iconv.decode(buf.slice(lastI), "ascii"); // Write direct chars. + } else { + var b64str = base64Accum + buf.slice(lastI).toString().replace(/,/g, '/'); + + var canBeDecoded = b64str.length - (b64str.length % 8); // Minimal chunk: 2 quads -> 2x3 bytes -> 3 chars. + base64Accum = b64str.slice(canBeDecoded); // The rest will be decoded in future. + b64str = b64str.slice(0, canBeDecoded); + + res += this.iconv.decode(Buffer.from(b64str, 'base64'), "utf16-be"); } - if (this.options.connectionName) { - description += ` (${this.options.connectionName})`; + + this.inBase64 = inBase64; + this.base64Accum = base64Accum; + + return res; +} + +Utf7IMAPDecoder.prototype.end = function() { + var res = ""; + if (this.inBase64 && this.base64Accum.length > 0) + res = this.iconv.decode(Buffer.from(this.base64Accum, 'base64'), "utf16-be"); + + this.inBase64 = false; + this.base64Accum = ''; + return res; +} + + + + +/***/ }), + +/***/ 67961: +/***/ ((__unused_webpack_module, exports) => { + +"use strict"; + + +var BOMChar = '\uFEFF'; + +exports.PrependBOM = PrependBOMWrapper +function PrependBOMWrapper(encoder, options) { + this.encoder = encoder; + this.addBOM = true; +} + +PrependBOMWrapper.prototype.write = function(str) { + if (this.addBOM) { + str = BOMChar + str; + this.addBOM = false; } - return description; -}; -[ - "scan", - "sscan", - "hscan", - "zscan", - "scanBuffer", - "sscanBuffer", - "hscanBuffer", - "zscanBuffer", -].forEach(function (command) { - Redis.prototype[command + "Stream"] = function (key, options) { - if (command === "scan" || command === "scanBuffer") { - options = key; - key = null; - } - return new ScanStream_1.default(lodash_1.defaults({ - objectMode: true, - key: key, - redis: this, - command: command, - }, options)); - }; -}); + + return this.encoder.write(str); +} + +PrependBOMWrapper.prototype.end = function() { + return this.encoder.end(); +} + + +//------------------------------------------------------------------------------ + +exports.StripBOM = StripBOMWrapper; +function StripBOMWrapper(decoder, options) { + this.decoder = decoder; + this.pass = false; + this.options = options || {}; +} + +StripBOMWrapper.prototype.write = function(buf) { + var res = this.decoder.write(buf); + if (this.pass || !res) + return res; + + if (res[0] === BOMChar) { + res = res.slice(1); + if (typeof this.options.stripBOM === 'function') + this.options.stripBOM(); + } + + this.pass = true; + return res; +} + +StripBOMWrapper.prototype.end = function() { + return this.decoder.end(); +} + /***/ }), -/***/ 88540: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 30393: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const crypto_1 = __nccwpck_require__(76417); -const promiseContainer_1 = __nccwpck_require__(71475); -const command_1 = __nccwpck_require__(90803); -const standard_as_callback_1 = __nccwpck_require__(91543); -class Script { - constructor(lua, numberOfKeys = null, keyPrefix = "", readOnly = false) { - this.lua = lua; - this.numberOfKeys = numberOfKeys; - this.keyPrefix = keyPrefix; - this.readOnly = readOnly; - this.sha = crypto_1.createHash("sha1").update(lua).digest("hex"); - } - execute(container, args, options, callback) { - if (typeof this.numberOfKeys === "number") { - args.unshift(this.numberOfKeys); - } - if (this.keyPrefix) { - options.keyPrefix = this.keyPrefix; +var Buffer = __nccwpck_require__(64293).Buffer; +// Note: not polyfilled with safer-buffer on a purpose, as overrides Buffer + +// == Extend Node primitives to use iconv-lite ================================= + +module.exports = function (iconv) { + var original = undefined; // Place to keep original methods. + + // Node authors rewrote Buffer internals to make it compatible with + // Uint8Array and we cannot patch key functions since then. + // Note: this does use older Buffer API on a purpose + iconv.supportsNodeEncodingsExtension = !(Buffer.from || new Buffer(0) instanceof Uint8Array); + + iconv.extendNodeEncodings = function extendNodeEncodings() { + if (original) return; + original = {}; + + if (!iconv.supportsNodeEncodingsExtension) { + console.error("ACTION NEEDED: require('iconv-lite').extendNodeEncodings() is not supported in your version of Node"); + console.error("See more info at https://github.com/ashtuchkin/iconv-lite/wiki/Node-v4-compatibility"); + return; } - if (this.readOnly) { - options.readOnly = true; + + var nodeNativeEncodings = { + 'hex': true, 'utf8': true, 'utf-8': true, 'ascii': true, 'binary': true, + 'base64': true, 'ucs2': true, 'ucs-2': true, 'utf16le': true, 'utf-16le': true, + }; + + Buffer.isNativeEncoding = function(enc) { + return enc && nodeNativeEncodings[enc.toLowerCase()]; } - const evalsha = new command_1.default("evalsha", [this.sha].concat(args), options); - evalsha.isCustomCommand = true; - const result = container.sendCommand(evalsha); - if (promiseContainer_1.isPromise(result)) { - return standard_as_callback_1.default(result.catch((err) => { - if (err.toString().indexOf("NOSCRIPT") === -1) { - throw err; - } - return container.sendCommand(new command_1.default("eval", [this.lua].concat(args), options)); - }), callback); + + // -- SlowBuffer ----------------------------------------------------------- + var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; + + original.SlowBufferToString = SlowBuffer.prototype.toString; + SlowBuffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); } - // result is not a Promise--probably returned from a pipeline chain; however, - // we still need the callback to fire when the script is evaluated - standard_as_callback_1.default(evalsha.promise, callback); - return result; - } -} -exports.default = Script; + original.SlowBufferWrite = SlowBuffer.prototype.write; + SlowBuffer.prototype.write = function(string, offset, length, encoding) { + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; + } + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } -/***/ }), + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; + } + } + encoding = String(encoding || 'utf8').toLowerCase(); -/***/ 14645: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.SlowBufferWrite.call(this, string, offset, length, encoding); -"use strict"; + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); -Object.defineProperty(exports, "__esModule", ({ value: true })); -const utils_1 = __nccwpck_require__(94832); -const standard_as_callback_1 = __nccwpck_require__(91543); -const pipeline_1 = __nccwpck_require__(42803); -function addTransactionSupport(redis) { - redis.pipeline = function (commands) { - const pipeline = new pipeline_1.default(this); - if (Array.isArray(commands)) { - pipeline.addBatch(commands); + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; } - return pipeline; - }; - const { multi } = redis; - redis.multi = function (commands, options) { - if (typeof options === "undefined" && !Array.isArray(commands)) { - options = commands; - commands = null; + + // -- Buffer --------------------------------------------------------------- + + original.BufferIsEncoding = Buffer.isEncoding; + Buffer.isEncoding = function(encoding) { + return Buffer.isNativeEncoding(encoding) || iconv.encodingExists(encoding); } - if (options && options.pipeline === false) { - return multi.call(this); + + original.BufferByteLength = Buffer.byteLength; + Buffer.byteLength = SlowBuffer.byteLength = function(str, encoding) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferByteLength.call(this, str, encoding); + + // Slow, I know, but we don't have a better way yet. + return iconv.encode(str, encoding).length; } - const pipeline = new pipeline_1.default(this); - pipeline.multi(); - if (Array.isArray(commands)) { - pipeline.addBatch(commands); + + original.BufferToString = Buffer.prototype.toString; + Buffer.prototype.toString = function(encoding, start, end) { + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferToString.call(this, encoding, start, end); + + // Otherwise, use our decoding method. + if (typeof start == 'undefined') start = 0; + if (typeof end == 'undefined') end = this.length; + return iconv.decode(this.slice(start, end), encoding); } - const exec = pipeline.exec; - pipeline.exec = function (callback) { - // Wait for the cluster to be connected, since we need nodes information before continuing - if (this.isCluster && !this.redis.slots.length) { - return standard_as_callback_1.default(new Promise((resolve, reject) => { - this.redis.delayUntilReady((err) => { - if (err) { - reject(err); - return; - } - this.exec(pipeline).then(resolve, reject); - }); - }), callback); - } - if (this._transactions > 0) { - exec.call(pipeline); - } - // Returns directly when the pipeline - // has been called multiple times (retries). - if (this.nodeifiedPromise) { - return exec.call(pipeline); - } - const promise = exec.call(pipeline); - return standard_as_callback_1.default(promise.then(function (result) { - const execResult = result[result.length - 1]; - if (typeof execResult === "undefined") { - throw new Error("Pipeline cannot be used to send any commands when the `exec()` has been called on it."); + + original.BufferWrite = Buffer.prototype.write; + Buffer.prototype.write = function(string, offset, length, encoding) { + var _offset = offset, _length = length, _encoding = encoding; + // Support both (string, offset, length, encoding) + // and the legacy (string, encoding, offset, length) + if (isFinite(offset)) { + if (!isFinite(length)) { + encoding = length; + length = undefined; } - if (execResult[0]) { - execResult[0].previousErrors = []; - for (let i = 0; i < result.length - 1; ++i) { - if (result[i][0]) { - execResult[0].previousErrors.push(result[i][0]); - } - } - throw execResult[0]; + } else { // legacy + var swap = encoding; + encoding = offset; + offset = length; + length = swap; + } + + encoding = String(encoding || 'utf8').toLowerCase(); + + // Use native conversion when possible + if (Buffer.isNativeEncoding(encoding)) + return original.BufferWrite.call(this, string, _offset, _length, _encoding); + + offset = +offset || 0; + var remaining = this.length - offset; + if (!length) { + length = remaining; + } else { + length = +length; + if (length > remaining) { + length = remaining; } - return utils_1.wrapMultiResult(execResult[1]); - }), callback); - }; - const { execBuffer } = pipeline; - pipeline.execBuffer = function (callback) { - if (this._transactions > 0) { - execBuffer.call(pipeline); } - return pipeline.exec(callback); - }; - return pipeline; - }; - const { exec } = redis; - redis.exec = function (callback) { - return standard_as_callback_1.default(exec.call(this).then(function (results) { - if (Array.isArray(results)) { - results = utils_1.wrapMultiResult(results); + + if (string.length > 0 && (length < 0 || offset < 0)) + throw new RangeError('attempt to write beyond buffer bounds'); + + // Otherwise, use our encoding method. + var buf = iconv.encode(string, encoding); + if (buf.length < length) length = buf.length; + buf.copy(this, offset, 0, length); + return length; + + // TODO: Set _charsWritten. + } + + + // -- Readable ------------------------------------------------------------- + if (iconv.supportsStreams) { + var Readable = __nccwpck_require__(92413).Readable; + + original.ReadableSetEncoding = Readable.prototype.setEncoding; + Readable.prototype.setEncoding = function setEncoding(enc, options) { + // Use our own decoder, it has the same interface. + // We cannot use original function as it doesn't handle BOM-s. + this._readableState.decoder = iconv.getDecoder(enc, options); + this._readableState.encoding = enc; } - return results; - }), callback); - }; + + Readable.prototype.collect = iconv._collect; + } + } + + // Remove iconv-lite Node primitive extensions. + iconv.undoExtendNodeEncodings = function undoExtendNodeEncodings() { + if (!iconv.supportsNodeEncodingsExtension) + return; + if (!original) + throw new Error("require('iconv-lite').undoExtendNodeEncodings(): Nothing to undo; extendNodeEncodings() is not called.") + + delete Buffer.isNativeEncoding; + + var SlowBuffer = __nccwpck_require__(64293).SlowBuffer; + + SlowBuffer.prototype.toString = original.SlowBufferToString; + SlowBuffer.prototype.write = original.SlowBufferWrite; + + Buffer.isEncoding = original.BufferIsEncoding; + Buffer.byteLength = original.BufferByteLength; + Buffer.prototype.toString = original.BufferToString; + Buffer.prototype.write = original.BufferWrite; + + if (iconv.supportsStreams) { + var Readable = __nccwpck_require__(92413).Readable; + + Readable.prototype.setEncoding = original.ReadableSetEncoding; + delete Readable.prototype.collect; + } + + original = undefined; + } } -exports.addTransactionSupport = addTransactionSupport; /***/ }), -/***/ 85356: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 19032: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const debug_1 = __nccwpck_require__(38237); -const MAX_ARGUMENT_LENGTH = 200; -exports.MAX_ARGUMENT_LENGTH = MAX_ARGUMENT_LENGTH; -const NAMESPACE_PREFIX = "ioredis"; -/** - * helper function that tried to get a string value for - * arbitrary "debug" arg - */ -function getStringValue(v) { - if (v === null) { - return; + +// Some environments don't have global Buffer (e.g. React Native). +// Solution would be installing npm modules "buffer" and "stream" explicitly. +var Buffer = __nccwpck_require__(15118).Buffer; + +var bomHandling = __nccwpck_require__(67961), + iconv = module.exports; + +// All codecs and aliases are kept here, keyed by encoding name/alias. +// They are lazy loaded in `iconv.getCodec` from `encodings/index.js`. +iconv.encodings = null; + +// Characters emitted in case of error. +iconv.defaultCharUnicode = '�'; +iconv.defaultCharSingleByte = '?'; + +// Public API. +iconv.encode = function encode(str, encoding, options) { + str = "" + (str || ""); // Ensure string. + + var encoder = iconv.getEncoder(encoding, options); + + var res = encoder.write(str); + var trail = encoder.end(); + + return (trail && trail.length > 0) ? Buffer.concat([res, trail]) : res; +} + +iconv.decode = function decode(buf, encoding, options) { + if (typeof buf === 'string') { + if (!iconv.skipDecodeWarning) { + console.error('Iconv-lite warning: decode()-ing strings is deprecated. Refer to https://github.com/ashtuchkin/iconv-lite/wiki/Use-Buffers-when-decoding'); + iconv.skipDecodeWarning = true; + } + + buf = Buffer.from("" + (buf || ""), "binary"); // Ensure buffer. } - switch (typeof v) { - case "boolean": - return; - case "number": - return; - case "object": - if (Buffer.isBuffer(v)) { - return v.toString("hex"); - } - if (Array.isArray(v)) { - return v.join(","); - } - try { - return JSON.stringify(v); - } - catch (e) { - return; - } - case "string": - return v; + + var decoder = iconv.getDecoder(encoding, options); + + var res = decoder.write(buf); + var trail = decoder.end(); + + return trail ? (res + trail) : res; +} + +iconv.encodingExists = function encodingExists(enc) { + try { + iconv.getCodec(enc); + return true; + } catch (e) { + return false; } } -exports.getStringValue = getStringValue; -/** - * helper function that redacts a string representation of a "debug" arg - */ -function genRedactedString(str, maxLen) { - const { length } = str; - return length <= maxLen - ? str - : str.slice(0, maxLen) + ' ... '; + +// Legacy aliases to convert functions +iconv.toEncoding = iconv.encode; +iconv.fromEncoding = iconv.decode; + +// Search for a codec in iconv.encodings. Cache codec data in iconv._codecDataCache. +iconv._codecDataCache = {}; +iconv.getCodec = function getCodec(encoding) { + if (!iconv.encodings) + iconv.encodings = __nccwpck_require__(82733); // Lazy load all encoding definitions. + + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + var enc = iconv._canonicalizeEncoding(encoding); + + // Traverse iconv.encodings to find actual codec. + var codecOptions = {}; + while (true) { + var codec = iconv._codecDataCache[enc]; + if (codec) + return codec; + + var codecDef = iconv.encodings[enc]; + + switch (typeof codecDef) { + case "string": // Direct alias to other encoding. + enc = codecDef; + break; + + case "object": // Alias with options. Can be layered. + for (var key in codecDef) + codecOptions[key] = codecDef[key]; + + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + enc = codecDef.type; + break; + + case "function": // Codec itself. + if (!codecOptions.encodingName) + codecOptions.encodingName = enc; + + // The codec function must load all tables and return object with .encoder and .decoder methods. + // It'll be called only once (for each different options object). + codec = new codecDef(codecOptions, iconv); + + iconv._codecDataCache[codecOptions.encodingName] = codec; // Save it to be reused later. + return codec; + + default: + throw new Error("Encoding not recognized: '" + encoding + "' (searched as: '"+enc+"')"); + } + } +} + +iconv._canonicalizeEncoding = function(encoding) { + // Canonicalize encoding name: strip all non-alphanumeric chars and appended year. + return (''+encoding).toLowerCase().replace(/:\d{4}$|[^0-9a-z]/g, ""); +} + +iconv.getEncoder = function getEncoder(encoding, options) { + var codec = iconv.getCodec(encoding), + encoder = new codec.encoder(options, codec); + + if (codec.bomAware && options && options.addBOM) + encoder = new bomHandling.PrependBOM(encoder, options); + + return encoder; +} + +iconv.getDecoder = function getDecoder(encoding, options) { + var codec = iconv.getCodec(encoding), + decoder = new codec.decoder(options, codec); + + if (codec.bomAware && !(options && options.stripBOM === false)) + decoder = new bomHandling.StripBOM(decoder, options); + + return decoder; } -exports.genRedactedString = genRedactedString; -/** - * a wrapper for the `debug` module, used to generate - * "debug functions" that trim the values in their output - */ -function genDebugFunction(namespace) { - const fn = debug_1.default(`${NAMESPACE_PREFIX}:${namespace}`); - function wrappedDebug(...args) { - if (!fn.enabled) { - return; // no-op - } - // we skip the first arg because that is the message - for (let i = 1; i < args.length; i++) { - const str = getStringValue(args[i]); - if (typeof str === "string" && str.length > MAX_ARGUMENT_LENGTH) { - args[i] = genRedactedString(str, MAX_ARGUMENT_LENGTH); - } - } - return fn.apply(null, args); + + +// Load extensions in Node. All of them are omitted in Browserify build via 'browser' field in package.json. +var nodeVer = typeof process !== 'undefined' && process.versions && process.versions.node; +if (nodeVer) { + + // Load streaming support in Node v0.10+ + var nodeVerArr = nodeVer.split(".").map(Number); + if (nodeVerArr[0] > 0 || nodeVerArr[1] >= 10) { + __nccwpck_require__(76409)(iconv); } - Object.defineProperties(wrappedDebug, { - namespace: { - get() { - return fn.namespace; - }, - }, - enabled: { - get() { - return fn.enabled; - }, - }, - destroy: { - get() { - return fn.destroy; - }, - }, - log: { - get() { - return fn.log; - }, - set(l) { - fn.log = l; - }, - }, - }); - return wrappedDebug; + + // Load Node primitive extensions. + __nccwpck_require__(30393)(iconv); } -exports.default = genDebugFunction; + +if (false) {} /***/ }), -/***/ 94832: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +/***/ 76409: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -Object.defineProperty(exports, "__esModule", ({ value: true })); -const url_1 = __nccwpck_require__(78835); -const lodash_1 = __nccwpck_require__(20961); -exports.defaults = lodash_1.defaults; -exports.noop = lodash_1.noop; -exports.flatten = lodash_1.flatten; -const debug_1 = __nccwpck_require__(85356); -exports.Debug = debug_1.default; -/** - * Test if two buffers are equal - * - * @export - * @param {Buffer} a - * @param {Buffer} b - * @returns {boolean} Whether the two buffers are equal - */ -function bufferEqual(a, b) { - if (typeof a.equals === "function") { - return a.equals(b); - } - if (a.length !== b.length) { - return false; - } - for (let i = 0; i < a.length; ++i) { - if (a[i] !== b[i]) { - return false; - } - } - return true; -} -exports.bufferEqual = bufferEqual; -/** - * Convert a buffer to string, supports buffer array - * - * @param {*} value - The input value - * @param {string} encoding - string encoding - * @return {*} The result - * @example - * ```js - * var input = [Buffer.from('foo'), [Buffer.from('bar')]] - * var res = convertBufferToString(input, 'utf8') - * expect(res).to.eql(['foo', ['bar']]) - * ``` - * @private - */ -function convertBufferToString(value, encoding) { - if (value instanceof Buffer) { - return value.toString(encoding); + +var Buffer = __nccwpck_require__(64293).Buffer, + Transform = __nccwpck_require__(92413).Transform; + + +// == Exports ================================================================== +module.exports = function(iconv) { + + // Additional Public API. + iconv.encodeStream = function encodeStream(encoding, options) { + return new IconvLiteEncoderStream(iconv.getEncoder(encoding, options), options); } - if (Array.isArray(value)) { - const length = value.length; - const res = Array(length); - for (let i = 0; i < length; ++i) { - res[i] = - value[i] instanceof Buffer && encoding === "utf8" - ? value[i].toString() - : convertBufferToString(value[i], encoding); - } - return res; + + iconv.decodeStream = function decodeStream(encoding, options) { + return new IconvLiteDecoderStream(iconv.getDecoder(encoding, options), options); } - return value; + + iconv.supportsStreams = true; + + + // Not published yet. + iconv.IconvLiteEncoderStream = IconvLiteEncoderStream; + iconv.IconvLiteDecoderStream = IconvLiteDecoderStream; + iconv._collect = IconvLiteDecoderStream.prototype.collect; +}; + + +// == Encoder stream ======================================================= +function IconvLiteEncoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.decodeStrings = false; // We accept only strings, so we don't need to decode them. + Transform.call(this, options); } -exports.convertBufferToString = convertBufferToString; -/** - * Convert a list of results to node-style - * - * @param {Array} arr - The input value - * @return {Array} The output value - * @example - * ```js - * var input = ['a', 'b', new Error('c'), 'd'] - * var output = exports.wrapMultiResult(input) - * expect(output).to.eql([[null, 'a'], [null, 'b'], [new Error('c')], [null, 'd']) - * ``` - * @private - */ -function wrapMultiResult(arr) { - // When using WATCH/EXEC transactions, the EXEC will return - // a null instead of an array - if (!arr) { - return null; + +IconvLiteEncoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteEncoderStream } +}); + +IconvLiteEncoderStream.prototype._transform = function(chunk, encoding, done) { + if (typeof chunk != 'string') + return done(new Error("Iconv encoding stream needs strings as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res); + done(); } - const result = []; - const length = arr.length; - for (let i = 0; i < length; ++i) { - const item = arr[i]; - if (item instanceof Error) { - result.push([item]); - } - else { - result.push([null, item]); - } + catch (e) { + done(e); } - return result; -} -exports.wrapMultiResult = wrapMultiResult; -/** - * Detect the argument is a int - * - * @param {string} value - * @return {boolean} Whether the value is a int - * @example - * ```js - * > isInt('123') - * true - * > isInt('123.3') - * false - * > isInt('1x') - * false - * > isInt(123) - * true - * > isInt(true) - * false - * ``` - * @private - */ -function isInt(value) { - const x = parseFloat(value); - return !isNaN(value) && (x | 0) === x; } -exports.isInt = isInt; -/** - * Pack an array to an Object - * - * @param {array} array - * @return {object} - * @example - * ```js - * > packObject(['a', 'b', 'c', 'd']) - * { a: 'b', c: 'd' } - * ``` - */ -function packObject(array) { - const result = {}; - const length = array.length; - for (let i = 1; i < length; i += 2) { - result[array[i - 1]] = array[i]; + +IconvLiteEncoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res); + done(); } - return result; -} -exports.packObject = packObject; -/** - * Return a callback with timeout - * - * @param {function} callback - * @param {number} timeout - * @return {function} - */ -function timeout(callback, timeout) { - let timer; - const run = function () { - if (timer) { - clearTimeout(timer); - timer = null; - callback.apply(this, arguments); - } - }; - timer = setTimeout(run, timeout, new Error("timeout")); - return run; -} -exports.timeout = timeout; -/** - * Convert an object to an array - * - * @param {object} obj - * @return {array} - * @example - * ```js - * > convertObjectToArray({ a: '1' }) - * ['a', '1'] - * ``` - */ -function convertObjectToArray(obj) { - const result = []; - const keys = Object.keys(obj); - for (let i = 0, l = keys.length; i < l; i++) { - result.push(keys[i], obj[keys[i]]); + catch (e) { + done(e); } - return result; } -exports.convertObjectToArray = convertObjectToArray; -/** - * Convert a map to an array - * - * @param {Map} map - * @return {array} - * @example - * ```js - * > convertObjectToArray(new Map([[1, '2']])) - * [1, '2'] - * ``` - */ -function convertMapToArray(map) { - const result = []; - let pos = 0; - map.forEach(function (value, key) { - result[pos] = key; - result[pos + 1] = value; - pos += 2; + +IconvLiteEncoderStream.prototype.collect = function(cb) { + var chunks = []; + this.on('error', cb); + this.on('data', function(chunk) { chunks.push(chunk); }); + this.on('end', function() { + cb(null, Buffer.concat(chunks)); }); - return result; + return this; } -exports.convertMapToArray = convertMapToArray; -/** - * Convert a non-string arg to a string - * - * @param {*} arg - * @return {string} - */ -function toArg(arg) { - if (arg === null || typeof arg === "undefined") { - return ""; - } - return String(arg); + + +// == Decoder stream ======================================================= +function IconvLiteDecoderStream(conv, options) { + this.conv = conv; + options = options || {}; + options.encoding = this.encoding = 'utf8'; // We output strings. + Transform.call(this, options); } -exports.toArg = toArg; -/** - * Optimize error stack - * - * @param {Error} error - actually error - * @param {string} friendlyStack - the stack that more meaningful - * @param {string} filterPath - only show stacks with the specified path - */ -function optimizeErrorStack(error, friendlyStack, filterPath) { - const stacks = friendlyStack.split("\n"); - let lines = ""; - let i; - for (i = 1; i < stacks.length; ++i) { - if (stacks[i].indexOf(filterPath) === -1) { - break; - } + +IconvLiteDecoderStream.prototype = Object.create(Transform.prototype, { + constructor: { value: IconvLiteDecoderStream } +}); + +IconvLiteDecoderStream.prototype._transform = function(chunk, encoding, done) { + if (!Buffer.isBuffer(chunk)) + return done(new Error("Iconv decoding stream needs buffers as its input.")); + try { + var res = this.conv.write(chunk); + if (res && res.length) this.push(res, this.encoding); + done(); } - for (let j = i; j < stacks.length; ++j) { - lines += "\n" + stacks[j]; + catch (e) { + done(e); } - const pos = error.stack.indexOf("\n"); - error.stack = error.stack.slice(0, pos) + lines; - return error; } -exports.optimizeErrorStack = optimizeErrorStack; -/** - * Parse the redis protocol url - * - * @param {string} url - the redis protocol url - * @return {Object} - */ -function parseURL(url) { - if (isInt(url)) { - return { port: url }; - } - let parsed = url_1.parse(url, true, true); - if (!parsed.slashes && url[0] !== "/") { - url = "//" + url; - parsed = url_1.parse(url, true, true); - } - const result = {}; - if (parsed.auth) { - const parsedAuth = parsed.auth.split(":"); - result.password = parsedAuth[1]; - } - if (parsed.pathname) { - if (parsed.protocol === "redis:" || parsed.protocol === "rediss:") { - if (parsed.pathname.length > 1) { - result.db = parsed.pathname.slice(1); - } - } - else { - result.path = parsed.pathname; - } - } - if (parsed.host) { - result.host = parsed.hostname; + +IconvLiteDecoderStream.prototype._flush = function(done) { + try { + var res = this.conv.end(); + if (res && res.length) this.push(res, this.encoding); + done(); } - if (parsed.port) { - result.port = parsed.port; + catch (e) { + done(e); } - lodash_1.defaults(result, parsed.query); - return result; } -exports.parseURL = parseURL; -/** - * Get a random element from `array` - * - * @export - * @template T - * @param {T[]} array the array - * @param {number} [from=0] start index - * @returns {T} - */ -function sample(array, from = 0) { - const length = array.length; - if (from >= length) { - return; - } - return array[from + Math.floor(Math.random() * (length - from))]; + +IconvLiteDecoderStream.prototype.collect = function(cb) { + var res = ''; + this.on('error', cb); + this.on('data', function(chunk) { res += chunk; }); + this.on('end', function() { + cb(null, res); + }); + return this; } -exports.sample = sample; -/** - * Shuffle the array using the Fisher-Yates Shuffle. - * This method will mutate the original array. - * - * @export - * @template T - * @param {T[]} array - * @returns {T[]} - */ -function shuffle(array) { - let counter = array.length; - // While there are elements in the array - while (counter > 0) { - // Pick a random index - const index = Math.floor(Math.random() * counter); - // Decrease counter by 1 - counter--; - // And swap the last element with it - [array[counter], array[index]] = [array[index], array[counter]]; - } - return array; + + + +/***/ }), + +/***/ 91230: +/***/ ((module) => { + +// A simple implementation of make-array +function makeArray (subject) { + return Array.isArray(subject) + ? subject + : [subject] } -exports.shuffle = shuffle; -/** - * Error message for connection being disconnected - */ -exports.CONNECTION_CLOSED_ERROR_MSG = "Connection is closed."; -function zipMap(keys, values) { - const map = new Map(); - keys.forEach((key, index) => { - map.set(key, values[index]); - }); - return map; + +const EMPTY = '' +const SPACE = ' ' +const ESCAPE = '\\' +const REGEX_TEST_BLANK_LINE = /^\s+$/ +const REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\!/ +const REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\#/ +const REGEX_SPLITALL_CRLF = /\r?\n/g +// /foo, +// ./foo, +// ../foo, +// . +// .. +const REGEX_TEST_INVALID_PATH = /^\.*\/|^\.+$/ + +const SLASH = '/' +const KEY_IGNORE = typeof Symbol !== 'undefined' + ? Symbol.for('node-ignore') + /* istanbul ignore next */ + : 'node-ignore' + +const define = (object, key, value) => + Object.defineProperty(object, key, {value}) + +const REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g + +// Sanitize the range of a regular expression +// The cases are complicated, see test cases for details +const sanitizeRange = range => range.replace( + REGEX_REGEXP_RANGE, + (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0) + ? match + // Invalid range (out of order) which is ok for gitignore rules but + // fatal for JavaScript regular expression, so eliminate it. + : EMPTY +) + +// See fixtures #59 +const cleanRangeBackSlash = slashes => { + const {length} = slashes + return slashes.slice(0, length - length % 2) } -exports.zipMap = zipMap; +// > If the pattern ends with a slash, +// > it is removed for the purpose of the following description, +// > but it would only find a match with a directory. +// > In other words, foo/ will match a directory foo and paths underneath it, +// > but will not match a regular file or a symbolic link foo +// > (this is consistent with the way how pathspec works in general in Git). +// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`' +// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call +// you could use option `mark: true` with `glob` -/***/ }), +// '`foo/`' should not continue with the '`..`' +const REPLACERS = [ -/***/ 20961: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + // > Trailing spaces are ignored unless they are quoted with backslash ("\") + [ + // (a\ ) -> (a ) + // (a ) -> (a) + // (a \ ) -> (a ) + /\\?\s+$/, + match => match.indexOf('\\') === 0 + ? SPACE + : EMPTY + ], -"use strict"; + // replace (\ ) with ' ' + [ + /\\\s/g, + () => SPACE + ], -Object.defineProperty(exports, "__esModule", ({ value: true })); -const defaults = __nccwpck_require__(11289); -exports.defaults = defaults; -const flatten = __nccwpck_require__(48919); -exports.flatten = flatten; -function noop() { } -exports.noop = noop; + // Escape metacharacters + // which is written down by users but means special for regular expressions. + // > There are 12 characters with special meanings: + // > - the backslash \, + // > - the caret ^, + // > - the dollar sign $, + // > - the period or dot ., + // > - the vertical bar or pipe symbol |, + // > - the question mark ?, + // > - the asterisk or star *, + // > - the plus sign +, + // > - the opening parenthesis (, + // > - the closing parenthesis ), + // > - and the opening square bracket [, + // > - the opening curly brace {, + // > These special characters are often called "metacharacters". + [ + /[\\$.|*+(){^]/g, + match => `\\${match}` + ], -/***/ }), + [ + // > a question mark (?) matches a single character + /(?!\\)\?/g, + () => '[^/]' + ], -/***/ 37263: -/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { + // leading slash + [ -/* module decorator */ module = __nccwpck_require__.nmd(module); -(function() { - var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; + // > A leading slash matches the beginning of the pathname. + // > For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c". + // A leading slash matches the beginning of the pathname + /^\//, + () => '^' + ], - ipaddr = {}; + // replace special metacharacter slash after the leading slash + [ + /\//g, + () => '\\/' + ], - root = this; + [ + // > A leading "**" followed by a slash means match in all directories. + // > For example, "**/foo" matches file or directory "foo" anywhere, + // > the same as pattern "foo". + // > "**/foo/bar" matches file or directory "bar" anywhere that is directly + // > under directory "foo". + // Notice that the '*'s have been replaced as '\\*' + /^\^*\\\*\\\*\\\//, - if (( true && module !== null) && module.exports) { - module.exports = ipaddr; - } else { - root['ipaddr'] = ipaddr; - } + // '**/foo' <-> 'foo' + () => '^(?:.*\\/)?' + ], - matchCIDR = function(first, second, partSize, cidrBits) { - var part, shift; - if (first.length !== second.length) { - throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); - } - part = 0; - while (cidrBits > 0) { - shift = partSize - cidrBits; - if (shift < 0) { - shift = 0; - } - if (first[part] >> shift !== second[part] >> shift) { - return false; - } - cidrBits -= partSize; - part += 1; - } - return true; - }; + // starting + [ + // there will be no leading '/' + // (which has been replaced by section "leading slash") + // If starts with '**', adding a '^' to the regular expression also works + /^(?=[^^])/, + function startingReplacer () { + // If has a slash `/` at the beginning or middle + return !/\/(?!$)/.test(this) + // > Prior to 2.22.1 + // > If the pattern does not contain a slash /, + // > Git treats it as a shell glob pattern + // Actually, if there is only a trailing slash, + // git also treats it as a shell glob pattern - ipaddr.subnetMatch = function(address, rangeList, defaultName) { - var k, len, rangeName, rangeSubnets, subnet; - if (defaultName == null) { - defaultName = 'unicast'; - } - for (rangeName in rangeList) { - rangeSubnets = rangeList[rangeName]; - if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { - rangeSubnets = [rangeSubnets]; - } - for (k = 0, len = rangeSubnets.length; k < len; k++) { - subnet = rangeSubnets[k]; - if (address.kind() === subnet[0].kind()) { - if (address.match.apply(address, subnet)) { - return rangeName; - } - } - } - } - return defaultName; - }; + // After 2.22.1 (compatible but clearer) + // > If there is a separator at the beginning or middle (or both) + // > of the pattern, then the pattern is relative to the directory + // > level of the particular .gitignore file itself. + // > Otherwise the pattern may also match at any level below + // > the .gitignore level. + ? '(?:^|\\/)' - ipaddr.IPv4 = (function() { - function IPv4(octets) { - var k, len, octet; - if (octets.length !== 4) { - throw new Error("ipaddr: ipv4 octet count should be 4"); - } - for (k = 0, len = octets.length; k < len; k++) { - octet = octets[k]; - if (!((0 <= octet && octet <= 255))) { - throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); - } - } - this.octets = octets; + // > Otherwise, Git treats the pattern as a shell glob suitable for + // > consumption by fnmatch(3) + : '^' } + ], - IPv4.prototype.kind = function() { - return 'ipv4'; - }; + // two globstars + [ + // Use lookahead assertions so that we could match more than one `'/**'` + /\\\/\\\*\\\*(?=\\\/|$)/g, - IPv4.prototype.toString = function() { - return this.octets.join("."); - }; + // Zero, one or several directories + // should not use '*', or it will be replaced by the next replacer - IPv4.prototype.toNormalizedString = function() { - return this.toString(); - }; + // Check if it is not the last `'/**'` + (_, index, str) => index + 6 < str.length - IPv4.prototype.toByteArray = function() { - return this.octets.slice(0); - }; + // case: /**/ + // > A slash followed by two consecutive asterisks then a slash matches + // > zero or more directories. + // > For example, "a/**/b" matches "a/b", "a/x/b", "a/x/y/b" and so on. + // '/**/' + ? '(?:\\/[^\\/]+)*' - IPv4.prototype.match = function(other, cidrRange) { - var ref; - if (cidrRange === void 0) { - ref = other, other = ref[0], cidrRange = ref[1]; - } - if (other.kind() !== 'ipv4') { - throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); - } - return matchCIDR(this.octets, other.octets, 8, cidrRange); - }; + // case: /** + // > A trailing `"/**"` matches everything inside. - IPv4.prototype.SpecialRanges = { - unspecified: [[new IPv4([0, 0, 0, 0]), 8]], - broadcast: [[new IPv4([255, 255, 255, 255]), 32]], - multicast: [[new IPv4([224, 0, 0, 0]), 4]], - linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], - loopback: [[new IPv4([127, 0, 0, 0]), 8]], - carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], - "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], - reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] - }; + // #21: everything inside but it should not include the current folder + : '\\/.+' + ], - IPv4.prototype.range = function() { - return ipaddr.subnetMatch(this, this.SpecialRanges); - }; + // intermediate wildcards + [ + // Never replace escaped '*' + // ignore rule '\*' will match the path '*' - IPv4.prototype.toIPv4MappedAddress = function() { - return ipaddr.IPv6.parse("::ffff:" + (this.toString())); - }; + // 'abc.*/' -> go + // 'abc.*' -> skip this rule + /(^|[^\\]+)\\\*(?=.+)/g, - IPv4.prototype.prefixLengthFromSubnetMask = function() { - var cidr, i, k, octet, stop, zeros, zerotable; - zerotable = { - 0: 8, - 128: 7, - 192: 6, - 224: 5, - 240: 4, - 248: 3, - 252: 2, - 254: 1, - 255: 0 - }; - cidr = 0; - stop = false; - for (i = k = 3; k >= 0; i = k += -1) { - octet = this.octets[i]; - if (octet in zerotable) { - zeros = zerotable[octet]; - if (stop && zeros !== 0) { - return null; - } - if (zeros !== 8) { - stop = true; - } - cidr += zeros; - } else { - return null; - } - } - return 32 - cidr; - }; + // '*.js' matches '.js' + // '*.js' doesn't match 'abc' + (_, p1) => `${p1}[^\\/]*` + ], - return IPv4; + [ + // unescape, revert step 3 except for back slash + // For example, if a user escape a '\\*', + // after step 3, the result will be '\\\\\\*' + /\\\\\\(?=[$.|*+(){^])/g, + () => ESCAPE + ], - })(); + [ + // '\\\\' -> '\\' + /\\\\/g, + () => ESCAPE + ], - ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + [ + // > The range notation, e.g. [a-zA-Z], + // > can be used to match one of the characters in a range. - ipv4Regexes = { - fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), - longValue: new RegExp("^" + ipv4Part + "$", 'i') - }; + // `\` is escaped by step 3 + /(\\)?\[([^\]/]*?)(\\*)($|\])/g, + (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE + // '\\[bar]' -> '\\\\[bar\\]' + ? `\\[${range}${cleanRangeBackSlash(endEscape)}${close}` + : close === ']' + ? endEscape.length % 2 === 0 + // A normal case, and it is a range notation + // '[bar]' + // '[bar\\\\]' + ? `[${sanitizeRange(range)}${endEscape}]` + // Invalid range notaton + // '[bar\\]' -> '[bar\\\\]' + : '[]' + : '[]' + ], - ipaddr.IPv4.parser = function(string) { - var match, parseIntAuto, part, shift, value; - parseIntAuto = function(string) { - if (string[0] === "0" && string[1] !== "x") { - return parseInt(string, 8); - } else { - return parseInt(string); - } - }; - if (match = string.match(ipv4Regexes.fourOctet)) { - return (function() { - var k, len, ref, results; - ref = match.slice(1, 6); - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(parseIntAuto(part)); - } - return results; - })(); - } else if (match = string.match(ipv4Regexes.longValue)) { - value = parseIntAuto(match[1]); - if (value > 0xffffffff || value < 0) { - throw new Error("ipaddr: address outside defined range"); - } - return ((function() { - var k, results; - results = []; - for (shift = k = 0; k <= 24; shift = k += 8) { - results.push((value >> shift) & 0xff); - } - return results; - })()).reverse(); - } else { - return null; - } - }; + // ending + [ + // 'js' will not match 'js.' + // 'ab' will not match 'abc' + /(?:[^*])$/, - ipaddr.IPv6 = (function() { - function IPv6(parts, zoneId) { - var i, k, l, len, part, ref; - if (parts.length === 16) { - this.parts = []; - for (i = k = 0; k <= 14; i = k += 2) { - this.parts.push((parts[i] << 8) | parts[i + 1]); - } - } else if (parts.length === 8) { - this.parts = parts; - } else { - throw new Error("ipaddr: ipv6 part count should be 8 or 16"); - } - ref = this.parts; - for (l = 0, len = ref.length; l < len; l++) { - part = ref[l]; - if (!((0 <= part && part <= 0xffff))) { - throw new Error("ipaddr: ipv6 part should fit in 16 bits"); - } - } - if (zoneId) { - this.zoneId = zoneId; - } + // WTF! + // https://git-scm.com/docs/gitignore + // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1) + // which re-fixes #24, #38 + + // > If there is a separator at the end of the pattern then the pattern + // > will only match directories, otherwise the pattern can match both + // > files and directories. + + // 'js*' will not match 'a.js' + // 'js/' will not match 'a.js' + // 'js' will match 'a.js' and 'a.js/' + match => /\/$/.test(match) + // foo/ will not match 'foo' + ? `${match}$` + // foo matches 'foo' and 'foo/' + : `${match}(?=$|\\/$)` + ], + + // trailing wildcard + [ + /(\^|\\\/)?\\\*$/, + (_, p1) => { + const prefix = p1 + // '\^': + // '/*' does not match EMPTY + // '/*' does not match everything + + // '\\\/': + // 'abc/*' does not match 'abc/' + ? `${p1}[^/]+` + + // 'a*' matches 'a' + // 'a*' matches 'aa' + : '[^/]*' + + return `${prefix}(?=$|\\/$)` } + ], +] - IPv6.prototype.kind = function() { - return 'ipv6'; - }; +// A simple cache, because an ignore rule only has only one certain meaning +const regexCache = Object.create(null) - IPv6.prototype.toString = function() { - return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); - }; +// @param {pattern} +const makeRegex = (pattern, negative, ignorecase) => { + const r = regexCache[pattern] + if (r) { + return r + } - IPv6.prototype.toRFC5952String = function() { - var bestMatchIndex, bestMatchLength, match, regex, string; - regex = /((^|:)(0(:|$)){2,})/g; - string = this.toNormalizedString(); - bestMatchIndex = 0; - bestMatchLength = -1; - while ((match = regex.exec(string))) { - if (match[0].length > bestMatchLength) { - bestMatchIndex = match.index; - bestMatchLength = match[0].length; - } - } - if (bestMatchLength < 0) { - return string; - } - return string.substring(0, bestMatchIndex) + '::' + string.substring(bestMatchIndex + bestMatchLength); - }; + // const replacers = negative + // ? NEGATIVE_REPLACERS + // : POSITIVE_REPLACERS - IPv6.prototype.toByteArray = function() { - var bytes, k, len, part, ref; - bytes = []; - ref = this.parts; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - bytes.push(part >> 8); - bytes.push(part & 0xff); - } - return bytes; - }; + const source = REPLACERS.reduce( + (prev, current) => prev.replace(current[0], current[1].bind(pattern)), + pattern + ) - IPv6.prototype.toNormalizedString = function() { - var addr, part, suffix; - addr = ((function() { - var k, len, ref, results; - ref = this.parts; - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(part.toString(16)); - } - return results; - }).call(this)).join(":"); - suffix = ''; - if (this.zoneId) { - suffix = '%' + this.zoneId; - } - return addr + suffix; - }; + return regexCache[pattern] = ignorecase + ? new RegExp(source, 'i') + : new RegExp(source) +} + +const isString = subject => typeof subject === 'string' + +// > A blank line matches no files, so it can serve as a separator for readability. +const checkPattern = pattern => pattern + && isString(pattern) + && !REGEX_TEST_BLANK_LINE.test(pattern) - IPv6.prototype.toFixedLengthString = function() { - var addr, part, suffix; - addr = ((function() { - var k, len, ref, results; - ref = this.parts; - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(part.toString(16).padStart(4, '0')); - } - return results; - }).call(this)).join(":"); - suffix = ''; - if (this.zoneId) { - suffix = '%' + this.zoneId; - } - return addr + suffix; - }; + // > A line starting with # serves as a comment. + && pattern.indexOf('#') !== 0 - IPv6.prototype.match = function(other, cidrRange) { - var ref; - if (cidrRange === void 0) { - ref = other, other = ref[0], cidrRange = ref[1]; - } - if (other.kind() !== 'ipv6') { - throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); - } - return matchCIDR(this.parts, other.parts, 16, cidrRange); - }; +const splitPattern = pattern => pattern.split(REGEX_SPLITALL_CRLF) - IPv6.prototype.SpecialRanges = { - unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], - linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], - multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], - loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], - uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], - ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], - rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], - rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], - '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], - teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], - reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] - }; +class IgnoreRule { + constructor ( + origin, + pattern, + negative, + regex + ) { + this.origin = origin + this.pattern = pattern + this.negative = negative + this.regex = regex + } +} - IPv6.prototype.range = function() { - return ipaddr.subnetMatch(this, this.SpecialRanges); - }; +const createRule = (pattern, ignorecase) => { + const origin = pattern + let negative = false - IPv6.prototype.isIPv4MappedAddress = function() { - return this.range() === 'ipv4Mapped'; - }; + // > An optional prefix "!" which negates the pattern; + if (pattern.indexOf('!') === 0) { + negative = true + pattern = pattern.substr(1) + } - IPv6.prototype.toIPv4Address = function() { - var high, low, ref; - if (!this.isIPv4MappedAddress()) { - throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); - } - ref = this.parts.slice(-2), high = ref[0], low = ref[1]; - return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); - }; + pattern = pattern + // > Put a backslash ("\") in front of the first "!" for patterns that + // > begin with a literal "!", for example, `"\!important!.txt"`. + .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!') + // > Put a backslash ("\") in front of the first hash for patterns that + // > begin with a hash. + .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#') - IPv6.prototype.prefixLengthFromSubnetMask = function() { - var cidr, i, k, part, stop, zeros, zerotable; - zerotable = { - 0: 16, - 32768: 15, - 49152: 14, - 57344: 13, - 61440: 12, - 63488: 11, - 64512: 10, - 65024: 9, - 65280: 8, - 65408: 7, - 65472: 6, - 65504: 5, - 65520: 4, - 65528: 3, - 65532: 2, - 65534: 1, - 65535: 0 - }; - cidr = 0; - stop = false; - for (i = k = 7; k >= 0; i = k += -1) { - part = this.parts[i]; - if (part in zerotable) { - zeros = zerotable[part]; - if (stop && zeros !== 0) { - return null; - } - if (zeros !== 16) { - stop = true; - } - cidr += zeros; - } else { - return null; - } - } - return 128 - cidr; - }; + const regex = makeRegex(pattern, negative, ignorecase) - return IPv6; + return new IgnoreRule( + origin, + pattern, + negative, + regex + ) +} - })(); +const throwError = (message, Ctor) => { + throw new Ctor(message) +} - ipv6Part = "(?:[0-9a-f]+::?)+"; +const checkPath = (path, originalPath, doThrow) => { + if (!isString(path)) { + return doThrow( + `path must be a string, but got \`${originalPath}\``, + TypeError + ) + } - zoneIndex = "%[0-9a-z]{1,}"; + // We don't know if we should ignore EMPTY, so throw + if (!path) { + return doThrow(`path must not be empty`, TypeError) + } - ipv6Regexes = { - zoneIndex: new RegExp(zoneIndex, 'i'), - "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'), - transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i') - }; + // Check if it is a relative path + if (checkPath.isNotRelative(path)) { + const r = '`path.relative()`d' + return doThrow( + `path should be a ${r} string, but got "${originalPath}"`, + RangeError + ) + } - expandIPv6 = function(string, parts) { - var colonCount, lastColon, part, replacement, replacementCount, zoneId; - if (string.indexOf('::') !== string.lastIndexOf('::')) { - return null; - } - zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; - if (zoneId) { - zoneId = zoneId.substring(1); - string = string.replace(/%.+$/, ''); - } - colonCount = 0; - lastColon = -1; - while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { - colonCount++; - } - if (string.substr(0, 2) === '::') { - colonCount--; - } - if (string.substr(-2, 2) === '::') { - colonCount--; - } - if (colonCount > parts) { - return null; - } - replacementCount = parts - colonCount; - replacement = ':'; - while (replacementCount--) { - replacement += '0:'; - } - string = string.replace('::', replacement); - if (string[0] === ':') { - string = string.slice(1); - } - if (string[string.length - 1] === ':') { - string = string.slice(0, -1); - } - parts = (function() { - var k, len, ref, results; - ref = string.split(":"); - results = []; - for (k = 0, len = ref.length; k < len; k++) { - part = ref[k]; - results.push(parseInt(part, 16)); - } - return results; - })(); - return { - parts: parts, - zoneId: zoneId - }; - }; + return true +} - ipaddr.IPv6.parser = function(string) { - var addr, k, len, match, octet, octets, zoneId; - if (ipv6Regexes['native'].test(string)) { - return expandIPv6(string, 8); - } else if (match = string.match(ipv6Regexes['transitional'])) { - zoneId = match[6] || ''; - addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6); - if (addr.parts) { - octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; - for (k = 0, len = octets.length; k < len; k++) { - octet = octets[k]; - if (!((0 <= octet && octet <= 255))) { - return null; - } - } - addr.parts.push(octets[0] << 8 | octets[1]); - addr.parts.push(octets[2] << 8 | octets[3]); - return { - parts: addr.parts, - zoneId: addr.zoneId - }; - } - } - return null; - }; +const isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path) - ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { - return this.parser(string) !== null; - }; +checkPath.isNotRelative = isNotRelative +checkPath.convert = p => p - ipaddr.IPv4.isValid = function(string) { - var e; - try { - new this(this.parser(string)); - return true; - } catch (error1) { - e = error1; - return false; - } - }; +class Ignore { + constructor ({ + ignorecase = true + } = {}) { + this._rules = [] + this._ignorecase = ignorecase + define(this, KEY_IGNORE, true) + this._initCache() + } - ipaddr.IPv4.isValidFourPartDecimal = function(string) { - if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { - return true; - } else { - return false; - } - }; + _initCache () { + this._ignoreCache = Object.create(null) + this._testCache = Object.create(null) + } - ipaddr.IPv6.isValid = function(string) { - var addr, e; - if (typeof string === "string" && string.indexOf(":") === -1) { - return false; - } - try { - addr = this.parser(string); - new this(addr.parts, addr.zoneId); - return true; - } catch (error1) { - e = error1; - return false; + _addPattern (pattern) { + // #32 + if (pattern && pattern[KEY_IGNORE]) { + this._rules = this._rules.concat(pattern._rules) + this._added = true + return } - }; - ipaddr.IPv4.parse = function(string) { - var parts; - parts = this.parser(string); - if (parts === null) { - throw new Error("ipaddr: string is not formatted like ip address"); + if (checkPattern(pattern)) { + const rule = createRule(pattern, this._ignorecase) + this._added = true + this._rules.push(rule) } - return new this(parts); - }; + } - ipaddr.IPv6.parse = function(string) { - var addr; - addr = this.parser(string); - if (addr.parts === null) { - throw new Error("ipaddr: string is not formatted like ip address"); - } - return new this(addr.parts, addr.zoneId); - }; + // @param {Array | string | Ignore} pattern + add (pattern) { + this._added = false - ipaddr.IPv4.parseCIDR = function(string) { - var maskLength, match, parsed; - if (match = string.match(/^(.+)\/(\d+)$/)) { - maskLength = parseInt(match[2]); - if (maskLength >= 0 && maskLength <= 32) { - parsed = [this.parse(match[1]), maskLength]; - Object.defineProperty(parsed, 'toString', { - value: function() { - return this.join('/'); - } - }); - return parsed; - } - } - throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); - }; + makeArray( + isString(pattern) + ? splitPattern(pattern) + : pattern + ).forEach(this._addPattern, this) - ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { - var filledOctetCount, j, octets; - prefix = parseInt(prefix); - if (prefix < 0 || prefix > 32) { - throw new Error('ipaddr: invalid IPv4 prefix length'); - } - octets = [0, 0, 0, 0]; - j = 0; - filledOctetCount = Math.floor(prefix / 8); - while (j < filledOctetCount) { - octets[j] = 255; - j++; - } - if (filledOctetCount < 4) { - octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8); + // Some rules have just added to the ignore, + // making the behavior changed. + if (this._added) { + this._initCache() } - return new this(octets); - }; - ipaddr.IPv4.broadcastAddressFromCIDR = function(string) { - var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; - try { - cidr = this.parseCIDR(string); - ipInterfaceOctets = cidr[0].toByteArray(); - subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); - octets = []; - i = 0; - while (i < 4) { - octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); - i++; - } - return new this(octets); - } catch (error1) { - error = error1; - throw new Error('ipaddr: the address does not have IPv4 CIDR format'); - } - }; + return this + } - ipaddr.IPv4.networkAddressFromCIDR = function(string) { - var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; - try { - cidr = this.parseCIDR(string); - ipInterfaceOctets = cidr[0].toByteArray(); - subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); - octets = []; - i = 0; - while (i < 4) { - octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); - i++; - } - return new this(octets); - } catch (error1) { - error = error1; - throw new Error('ipaddr: the address does not have IPv4 CIDR format'); - } - }; + // legacy + addPattern (pattern) { + return this.add(pattern) + } - ipaddr.IPv6.parseCIDR = function(string) { - var maskLength, match, parsed; - if (match = string.match(/^(.+)\/(\d+)$/)) { - maskLength = parseInt(match[2]); - if (maskLength >= 0 && maskLength <= 128) { - parsed = [this.parse(match[1]), maskLength]; - Object.defineProperty(parsed, 'toString', { - value: function() { - return this.join('/'); - } - }); - return parsed; - } - } - throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); - }; + // | ignored : unignored + // negative | 0:0 | 0:1 | 1:0 | 1:1 + // -------- | ------- | ------- | ------- | -------- + // 0 | TEST | TEST | SKIP | X + // 1 | TESTIF | SKIP | TEST | X - ipaddr.isValid = function(string) { - return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); - }; + // - SKIP: always skip + // - TEST: always test + // - TESTIF: only test if checkUnignored + // - X: that never happen - ipaddr.parse = function(string) { - if (ipaddr.IPv6.isValid(string)) { - return ipaddr.IPv6.parse(string); - } else if (ipaddr.IPv4.isValid(string)) { - return ipaddr.IPv4.parse(string); - } else { - throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); - } - }; + // @param {boolean} whether should check if the path is unignored, + // setting `checkUnignored` to `false` could reduce additional + // path matching. - ipaddr.parseCIDR = function(string) { - var e; - try { - return ipaddr.IPv6.parseCIDR(string); - } catch (error1) { - e = error1; - try { - return ipaddr.IPv4.parseCIDR(string); - } catch (error1) { - e = error1; - throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); + // @returns {TestResult} true if a file is ignored + _testOne (path, checkUnignored) { + let ignored = false + let unignored = false + + this._rules.forEach(rule => { + const {negative} = rule + if ( + unignored === negative && ignored !== unignored + || negative && !ignored && !unignored && !checkUnignored + ) { + return } - } - }; - ipaddr.fromByteArray = function(bytes) { - var length; - length = bytes.length; - if (length === 4) { - return new ipaddr.IPv4(bytes); - } else if (length === 16) { - return new ipaddr.IPv6(bytes); - } else { - throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); - } - }; + const matched = rule.regex.test(path) - ipaddr.process = function(string) { - var addr; - addr = this.parse(string); - if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { - return addr.toIPv4Address(); - } else { - return addr; + if (matched) { + ignored = !negative + unignored = negative + } + }) + + return { + ignored, + unignored } - }; + } -}).call(this); + // @returns {TestResult} + _test (originalPath, cache, checkUnignored, slices) { + const path = originalPath + // Supports nullable path + && checkPath.convert(originalPath) + + checkPath(path, originalPath, throwError) + + return this._t(path, cache, checkUnignored, slices) + } + _t (path, cache, checkUnignored, slices) { + if (path in cache) { + return cache[path] + } -/***/ }), + if (!slices) { + // path/to/a.js + // ['path', 'to', 'a.js'] + slices = path.split(SLASH) + } -/***/ 7604: -/***/ ((module) => { + slices.pop() -"use strict"; + // If the path has no parent directory, just test it + if (!slices.length) { + return cache[path] = this._testOne(path, checkUnignored) + } + const parent = this._t( + slices.join(SLASH) + SLASH, + cache, + checkUnignored, + slices + ) -module.exports = function isArrayish(obj) { - if (!obj) { - return false; - } + // If the path contains a parent directory, check the parent first + return cache[path] = parent.ignored + // > It is not possible to re-include a file if a parent directory of + // > that file is excluded. + ? parent + : this._testOne(path, checkUnignored) + } - return obj instanceof Array || Array.isArray(obj) || - (obj.length >= 0 && obj.splice instanceof Function); -}; + ignores (path) { + return this._test(path, this._ignoreCache, false).ignored + } + createFilter () { + return path => !this.ignores(path) + } -/***/ }), + filter (paths) { + return makeArray(paths).filter(this.createFilter()) + } -/***/ 31310: -/***/ (function(module, exports) { + // @returns {TestResult} + test (path) { + return this._test(path, this._testCache, true) + } +} -;(function(root) { - 'use strict'; +const factory = options => new Ignore(options) - function isBase64(v, opts) { - if (v instanceof Boolean || typeof v === 'boolean') { - return false - } +const returnFalse = () => false - if (!(opts instanceof Object)) { - opts = {} - } +const isPathValid = path => + checkPath(path && checkPath.convert(path), path, returnFalse) - if (opts.allowEmpty === false && v === '') { - return false - } +factory.isPathValid = isPathValid - var regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\/]{3}=)?' - var mimeRegex = '(data:\\w+\\/[a-zA-Z\\+\\-\\.]+;base64,)' +// Fixes typescript +factory.default = factory - if (opts.mimeRequired === true) { - regex = mimeRegex + regex - } else if (opts.allowMime === true) { - regex = mimeRegex + '?' + regex - } +module.exports = factory - if (opts.paddingRequired === false) { - regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}(==)?|[A-Za-z0-9+\\/]{3}=?)?' - } +// Windows +// -------------------------------------------------------------- +/* istanbul ignore if */ +if ( + // Detect `process` so that it can run in browsers. + typeof process !== 'undefined' + && ( + process.env && process.env.IGNORE_TEST_WIN32 + || process.platform === 'win32' + ) +) { + /* eslint no-control-regex: "off" */ + const makePosix = str => /^\\\\\?\\/.test(str) + || /["<>|\u0000-\u001F]+/u.test(str) + ? str + : str.replace(/\\/g, '/') - return (new RegExp('^' + regex + '$', 'gi')).test(v) - } + checkPath.convert = makePosix - if (true) { - if ( true && module.exports) { - exports = module.exports = isBase64 - } - exports.isBase64 = isBase64 - } else {} -})(this); + // 'C:\\foo' <- 'C:\\foo' has been converted to 'C:/' + // 'd:\\foo' + const REGIX_IS_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\//i + checkPath.isNotRelative = path => + REGIX_IS_WINDOWS_PATH_ABSOLUTE.test(path) + || isNotRelative(path) +} /***/ }), -/***/ 56873: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 98043: +/***/ ((module) => { "use strict"; -var has = __nccwpck_require__(76339); - -function specifierIncluded(current, specifier) { - var nodeParts = current.split('.'); - var parts = specifier.split(' '); - var op = parts.length > 1 ? parts[0] : '='; - var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); - - for (var i = 0; i < 3; ++i) { - var cur = parseInt(nodeParts[i] || 0, 10); - var ver = parseInt(versionParts[i] || 0, 10); - if (cur === ver) { - continue; // eslint-disable-line no-restricted-syntax, no-continue - } - if (op === '<') { - return cur < ver; - } - if (op === '>=') { - return cur >= ver; - } - return false; - } - return op === '>='; -} +module.exports = (string, count = 1, options) => { + options = { + indent: ' ', + includeEmptyLines: false, + ...options + }; -function matchesRange(current, range) { - var specifiers = range.split(/ ?&& ?/); - if (specifiers.length === 0) { - return false; - } - for (var i = 0; i < specifiers.length; ++i) { - if (!specifierIncluded(current, specifiers[i])) { - return false; - } + if (typeof string !== 'string') { + throw new TypeError( + `Expected \`input\` to be a \`string\`, got \`${typeof string}\`` + ); } - return true; -} -function versionIncluded(nodeVersion, specifierValue) { - if (typeof specifierValue === 'boolean') { - return specifierValue; + if (typeof count !== 'number') { + throw new TypeError( + `Expected \`count\` to be a \`number\`, got \`${typeof count}\`` + ); } - var current = typeof nodeVersion === 'undefined' - ? process.versions && process.versions.node && process.versions.node - : nodeVersion; - - if (typeof current !== 'string') { - throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); + if (typeof options.indent !== 'string') { + throw new TypeError( + `Expected \`options.indent\` to be a \`string\`, got \`${typeof options.indent}\`` + ); } - if (specifierValue && typeof specifierValue === 'object') { - for (var i = 0; i < specifierValue.length; ++i) { - if (matchesRange(current, specifierValue[i])) { - return true; - } - } - return false; + if (count === 0) { + return string; } - return matchesRange(current, specifierValue); -} -var data = __nccwpck_require__(93991); + const regex = options.includeEmptyLines ? /^/gm : /^(?!\s*$)/gm; -module.exports = function isCore(x, nodeVersion) { - return has(data, x) && versionIncluded(nodeVersion, data[x]); + return string.replace(regex, options.indent.repeat(count)); }; /***/ }), -/***/ 64882: -/***/ ((module) => { - -"use strict"; -/* eslint-disable yoda */ +/***/ 44124: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +try { + var util = __nccwpck_require__(31669); + /* istanbul ignore next */ + if (typeof util.inherits !== 'function') throw ''; + module.exports = util.inherits; +} catch (e) { + /* istanbul ignore next */ + module.exports = __nccwpck_require__(8544); +} -const isFullwidthCodePoint = codePoint => { - if (Number.isNaN(codePoint)) { - return false; - } - // Code points are derived from: - // http://www.unix.org/Public/UNIDATA/EastAsianWidth.txt - if ( - codePoint >= 0x1100 && ( - codePoint <= 0x115F || // Hangul Jamo - codePoint === 0x2329 || // LEFT-POINTING ANGLE BRACKET - codePoint === 0x232A || // RIGHT-POINTING ANGLE BRACKET - // CJK Radicals Supplement .. Enclosed CJK Letters and Months - (0x2E80 <= codePoint && codePoint <= 0x3247 && codePoint !== 0x303F) || - // Enclosed CJK Letters and Months .. CJK Unified Ideographs Extension A - (0x3250 <= codePoint && codePoint <= 0x4DBF) || - // CJK Unified Ideographs .. Yi Radicals - (0x4E00 <= codePoint && codePoint <= 0xA4C6) || - // Hangul Jamo Extended-A - (0xA960 <= codePoint && codePoint <= 0xA97C) || - // Hangul Syllables - (0xAC00 <= codePoint && codePoint <= 0xD7A3) || - // CJK Compatibility Ideographs - (0xF900 <= codePoint && codePoint <= 0xFAFF) || - // Vertical Forms - (0xFE10 <= codePoint && codePoint <= 0xFE19) || - // CJK Compatibility Forms .. Small Form Variants - (0xFE30 <= codePoint && codePoint <= 0xFE6B) || - // Halfwidth and Fullwidth Forms - (0xFF01 <= codePoint && codePoint <= 0xFF60) || - (0xFFE0 <= codePoint && codePoint <= 0xFFE6) || - // Kana Supplement - (0x1B000 <= codePoint && codePoint <= 0x1B001) || - // Enclosed Ideographic Supplement - (0x1F200 <= codePoint && codePoint <= 0x1F251) || - // CJK Unified Ideographs Extension B .. Tertiary Ideographic Plane - (0x20000 <= codePoint && codePoint <= 0x3FFFD) - ) - ) { - return true; - } +/***/ }), - return false; -}; +/***/ 8544: +/***/ ((module) => { -module.exports = isFullwidthCodePoint; -module.exports.default = isFullwidthCodePoint; +if (typeof Object.create === 'function') { + // implementation from standard node.js 'util' module + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true + } + }) + } + }; +} else { + // old school shim for old browsers + module.exports = function inherits(ctor, superCtor) { + if (superCtor) { + ctor.super_ = superCtor + var TempCtor = function () {} + TempCtor.prototype = superCtor.prototype + ctor.prototype = new TempCtor() + ctor.prototype.constructor = ctor + } + } +} /***/ }), -/***/ 87783: -/***/ ((__unused_webpack_module, exports) => { +/***/ 30545: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -(function(exports) { - "use strict"; +"use strict"; - function isArray(obj) { - if (obj !== null) { - return Object.prototype.toString.call(obj) === "[object Array]"; - } else { - return false; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const command_1 = __nccwpck_require__(90803); +const utils_1 = __nccwpck_require__(94832); +const RedisParser = __nccwpck_require__(53315); +const SubscriptionSet_1 = __nccwpck_require__(73527); +const debug = utils_1.Debug("dataHandler"); +class DataHandler { + constructor(redis, parserOptions) { + this.redis = redis; + const parser = new RedisParser({ + stringNumbers: parserOptions.stringNumbers, + returnBuffers: !parserOptions.dropBufferSupport, + returnError: (err) => { + this.returnError(err); + }, + returnFatalError: (err) => { + this.returnFatalError(err); + }, + returnReply: (reply) => { + this.returnReply(reply); + }, + }); + redis.stream.on("data", (data) => { + parser.execute(data); + }); } - } - - function isObject(obj) { - if (obj !== null) { - return Object.prototype.toString.call(obj) === "[object Object]"; - } else { - return false; + returnFatalError(err) { + err.message += ". Please report this."; + this.redis.recoverFromFatalError(err, err, { offlineQueue: false }); } - } - - function strictDeepEqual(first, second) { - // Check the scalar case first. - if (first === second) { - return true; + returnError(err) { + const item = this.shiftCommand(err); + if (!item) { + return; + } + err.command = { + name: item.command.name, + args: item.command.args, + }; + this.redis.handleReconnection(err, item); } - - // Check if they are the same type. - var firstType = Object.prototype.toString.call(first); - if (firstType !== Object.prototype.toString.call(second)) { - return false; + returnReply(reply) { + if (this.handleMonitorReply(reply)) { + return; + } + if (this.handleSubscriberReply(reply)) { + return; + } + const item = this.shiftCommand(reply); + if (!item) { + return; + } + if (command_1.default.checkFlag("ENTER_SUBSCRIBER_MODE", item.command.name)) { + this.redis.condition.subscriber = new SubscriptionSet_1.default(); + this.redis.condition.subscriber.add(item.command.name, reply[1].toString()); + if (!fillSubCommand(item.command, reply[2])) { + this.redis.commandQueue.unshift(item); + } + } + else if (command_1.default.checkFlag("EXIT_SUBSCRIBER_MODE", item.command.name)) { + if (!fillUnsubCommand(item.command, reply[2])) { + this.redis.commandQueue.unshift(item); + } + } + else { + item.command.resolve(reply); + } } - // We know that first and second have the same type so we can just check the - // first type from now on. - if (isArray(first) === true) { - // Short circuit if they're not the same length; - if (first.length !== second.length) { - return false; - } - for (var i = 0; i < first.length; i++) { - if (strictDeepEqual(first[i], second[i]) === false) { - return false; + handleSubscriberReply(reply) { + if (!this.redis.condition.subscriber) { + return false; } - } - return true; + const replyType = Array.isArray(reply) ? reply[0].toString() : null; + debug('receive reply "%s" in subscriber mode', replyType); + switch (replyType) { + case "message": + if (this.redis.listeners("message").length > 0) { + // Check if there're listeners to avoid unnecessary `toString()`. + this.redis.emit("message", reply[1].toString(), reply[2].toString()); + } + this.redis.emit("messageBuffer", reply[1], reply[2]); + break; + case "pmessage": { + const pattern = reply[1].toString(); + if (this.redis.listeners("pmessage").length > 0) { + this.redis.emit("pmessage", pattern, reply[2].toString(), reply[3].toString()); + } + this.redis.emit("pmessageBuffer", pattern, reply[2], reply[3]); + break; + } + case "subscribe": + case "psubscribe": { + const channel = reply[1].toString(); + this.redis.condition.subscriber.add(replyType, channel); + const item = this.shiftCommand(reply); + if (!item) { + return; + } + if (!fillSubCommand(item.command, reply[2])) { + this.redis.commandQueue.unshift(item); + } + break; + } + case "unsubscribe": + case "punsubscribe": { + const channel = reply[1] ? reply[1].toString() : null; + if (channel) { + this.redis.condition.subscriber.del(replyType, channel); + } + const count = reply[2]; + if (count === 0) { + this.redis.condition.subscriber = false; + } + const item = this.shiftCommand(reply); + if (!item) { + return; + } + if (!fillUnsubCommand(item.command, count)) { + this.redis.commandQueue.unshift(item); + } + break; + } + default: { + const item = this.shiftCommand(reply); + if (!item) { + return; + } + item.command.resolve(reply); + } + } + return true; } - if (isObject(first) === true) { - // An object is equal if it has the same key/value pairs. - var keysSeen = {}; - for (var key in first) { - if (hasOwnProperty.call(first, key)) { - if (strictDeepEqual(first[key], second[key]) === false) { + handleMonitorReply(reply) { + if (this.redis.status !== "monitoring") { return false; - } - keysSeen[key] = true; } - } - // Now check that there aren't any keys in second that weren't - // in first. - for (var key2 in second) { - if (hasOwnProperty.call(second, key2)) { - if (keysSeen[key2] !== true) { + const replyStr = reply.toString(); + if (replyStr === "OK") { + // Valid commands in the monitoring mode are AUTH and MONITOR, + // both of which always reply with 'OK'. + // So if we got an 'OK', we can make certain that + // the reply is made to AUTH & MONITO. return false; - } } - } - return true; - } - return false; - } - - function isFalse(obj) { - // From the spec: - // A false value corresponds to the following values: - // Empty list - // Empty object - // Empty string - // False boolean - // null value - - // First check the scalar values. - if (obj === "" || obj === false || obj === null) { - return true; - } else if (isArray(obj) && obj.length === 0) { - // Check for an empty array. + // Since commands sent in the monitoring mode will trigger an exception, + // any replies we received in the monitoring mode should consider to be + // realtime monitor data instead of result of commands. + const len = replyStr.indexOf(" "); + const timestamp = replyStr.slice(0, len); + const argindex = replyStr.indexOf('"'); + const args = replyStr + .slice(argindex + 1, -1) + .split('" "') + .map((elem) => elem.replace(/\\"/g, '"')); + const dbAndSource = replyStr.slice(len + 2, argindex - 2).split(" "); + this.redis.emit("monitor", timestamp, args, dbAndSource[1], dbAndSource[0]); return true; - } else if (isObject(obj)) { - // Check for an empty object. - for (var key in obj) { - // If there are any keys, then - // the object is not empty so the object - // is not false. - if (obj.hasOwnProperty(key)) { - return false; - } + } + shiftCommand(reply) { + const item = this.redis.commandQueue.shift(); + if (!item) { + const message = "Command queue state error. If you can reproduce this, please report it."; + const error = new Error(message + + (reply instanceof Error + ? ` Last error: ${reply.message}` + : ` Last reply: ${reply.toString()}`)); + this.redis.emit("error", error); + return null; } + return item; + } +} +exports.default = DataHandler; +function fillSubCommand(command, count) { + // TODO: use WeakMap here + if (typeof command.remainReplies === "undefined") { + command.remainReplies = command.args.length; + } + if (--command.remainReplies === 0) { + command.resolve(count); return true; - } else { + } + return false; +} +function fillUnsubCommand(command, count) { + if (typeof command.remainReplies === "undefined") { + command.remainReplies = command.args.length; + } + if (command.remainReplies === 0) { + if (count === 0) { + command.resolve(count); + return true; + } return false; } - } - - function objValues(obj) { - var keys = Object.keys(obj); - var values = []; - for (var i = 0; i < keys.length; i++) { - values.push(obj[keys[i]]); + if (--command.remainReplies === 0) { + command.resolve(count); + return true; } - return values; - } - - function merge(a, b) { - var merged = {}; - for (var key in a) { - merged[key] = a[key]; - } - for (var key2 in b) { - merged[key2] = b[key2]; - } - return merged; - } - - var trimLeft; - if (typeof String.prototype.trimLeft === "function") { - trimLeft = function(str) { - return str.trimLeft(); - }; - } else { - trimLeft = function(str) { - return str.match(/^\s*(.*)/)[1]; - }; - } - - // Type constants used to define functions. - var TYPE_NUMBER = 0; - var TYPE_ANY = 1; - var TYPE_STRING = 2; - var TYPE_ARRAY = 3; - var TYPE_OBJECT = 4; - var TYPE_BOOLEAN = 5; - var TYPE_EXPREF = 6; - var TYPE_NULL = 7; - var TYPE_ARRAY_NUMBER = 8; - var TYPE_ARRAY_STRING = 9; - - var TOK_EOF = "EOF"; - var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier"; - var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier"; - var TOK_RBRACKET = "Rbracket"; - var TOK_RPAREN = "Rparen"; - var TOK_COMMA = "Comma"; - var TOK_COLON = "Colon"; - var TOK_RBRACE = "Rbrace"; - var TOK_NUMBER = "Number"; - var TOK_CURRENT = "Current"; - var TOK_EXPREF = "Expref"; - var TOK_PIPE = "Pipe"; - var TOK_OR = "Or"; - var TOK_AND = "And"; - var TOK_EQ = "EQ"; - var TOK_GT = "GT"; - var TOK_LT = "LT"; - var TOK_GTE = "GTE"; - var TOK_LTE = "LTE"; - var TOK_NE = "NE"; - var TOK_FLATTEN = "Flatten"; - var TOK_STAR = "Star"; - var TOK_FILTER = "Filter"; - var TOK_DOT = "Dot"; - var TOK_NOT = "Not"; - var TOK_LBRACE = "Lbrace"; - var TOK_LBRACKET = "Lbracket"; - var TOK_LPAREN= "Lparen"; - var TOK_LITERAL= "Literal"; - - // The "&", "[", "<", ">" tokens - // are not in basicToken because - // there are two token variants - // ("&&", "[?", "<=", ">="). This is specially handled - // below. - - var basicTokens = { - ".": TOK_DOT, - "*": TOK_STAR, - ",": TOK_COMMA, - ":": TOK_COLON, - "{": TOK_LBRACE, - "}": TOK_RBRACE, - "]": TOK_RBRACKET, - "(": TOK_LPAREN, - ")": TOK_RPAREN, - "@": TOK_CURRENT - }; - - var operatorStartToken = { - "<": true, - ">": true, - "=": true, - "!": true - }; - - var skipChars = { - " ": true, - "\t": true, - "\n": true - }; - - - function isAlpha(ch) { - return (ch >= "a" && ch <= "z") || - (ch >= "A" && ch <= "Z") || - ch === "_"; - } - - function isNum(ch) { - return (ch >= "0" && ch <= "9") || - ch === "-"; - } - function isAlphaNum(ch) { - return (ch >= "a" && ch <= "z") || - (ch >= "A" && ch <= "Z") || - (ch >= "0" && ch <= "9") || - ch === "_"; - } - - function Lexer() { - } - Lexer.prototype = { - tokenize: function(stream) { - var tokens = []; - this._current = 0; - var start; - var identifier; - var token; - while (this._current < stream.length) { - if (isAlpha(stream[this._current])) { - start = this._current; - identifier = this._consumeUnquotedIdentifier(stream); - tokens.push({type: TOK_UNQUOTEDIDENTIFIER, - value: identifier, - start: start}); - } else if (basicTokens[stream[this._current]] !== undefined) { - tokens.push({type: basicTokens[stream[this._current]], - value: stream[this._current], - start: this._current}); - this._current++; - } else if (isNum(stream[this._current])) { - token = this._consumeNumber(stream); - tokens.push(token); - } else if (stream[this._current] === "[") { - // No need to increment this._current. This happens - // in _consumeLBracket - token = this._consumeLBracket(stream); - tokens.push(token); - } else if (stream[this._current] === "\"") { - start = this._current; - identifier = this._consumeQuotedIdentifier(stream); - tokens.push({type: TOK_QUOTEDIDENTIFIER, - value: identifier, - start: start}); - } else if (stream[this._current] === "'") { - start = this._current; - identifier = this._consumeRawStringLiteral(stream); - tokens.push({type: TOK_LITERAL, - value: identifier, - start: start}); - } else if (stream[this._current] === "`") { - start = this._current; - var literal = this._consumeLiteral(stream); - tokens.push({type: TOK_LITERAL, - value: literal, - start: start}); - } else if (operatorStartToken[stream[this._current]] !== undefined) { - tokens.push(this._consumeOperator(stream)); - } else if (skipChars[stream[this._current]] !== undefined) { - // Ignore whitespace. - this._current++; - } else if (stream[this._current] === "&") { - start = this._current; - this._current++; - if (stream[this._current] === "&") { - this._current++; - tokens.push({type: TOK_AND, value: "&&", start: start}); - } else { - tokens.push({type: TOK_EXPREF, value: "&", start: start}); - } - } else if (stream[this._current] === "|") { - start = this._current; - this._current++; - if (stream[this._current] === "|") { - this._current++; - tokens.push({type: TOK_OR, value: "||", start: start}); - } else { - tokens.push({type: TOK_PIPE, value: "|", start: start}); - } - } else { - var error = new Error("Unknown character:" + stream[this._current]); - error.name = "LexerError"; - throw error; - } - } - return tokens; - }, - - _consumeUnquotedIdentifier: function(stream) { - var start = this._current; - this._current++; - while (this._current < stream.length && isAlphaNum(stream[this._current])) { - this._current++; - } - return stream.slice(start, this._current); - }, - - _consumeQuotedIdentifier: function(stream) { - var start = this._current; - this._current++; - var maxLength = stream.length; - while (stream[this._current] !== "\"" && this._current < maxLength) { - // You can escape a double quote and you can escape an escape. - var current = this._current; - if (stream[current] === "\\" && (stream[current + 1] === "\\" || - stream[current + 1] === "\"")) { - current += 2; - } else { - current++; - } - this._current = current; - } - this._current++; - return JSON.parse(stream.slice(start, this._current)); - }, - - _consumeRawStringLiteral: function(stream) { - var start = this._current; - this._current++; - var maxLength = stream.length; - while (stream[this._current] !== "'" && this._current < maxLength) { - // You can escape a single quote and you can escape an escape. - var current = this._current; - if (stream[current] === "\\" && (stream[current + 1] === "\\" || - stream[current + 1] === "'")) { - current += 2; - } else { - current++; - } - this._current = current; - } - this._current++; - var literal = stream.slice(start + 1, this._current - 1); - return literal.replace("\\'", "'"); - }, - - _consumeNumber: function(stream) { - var start = this._current; - this._current++; - var maxLength = stream.length; - while (isNum(stream[this._current]) && this._current < maxLength) { - this._current++; - } - var value = parseInt(stream.slice(start, this._current)); - return {type: TOK_NUMBER, value: value, start: start}; - }, + return false; +} - _consumeLBracket: function(stream) { - var start = this._current; - this._current++; - if (stream[this._current] === "?") { - this._current++; - return {type: TOK_FILTER, value: "[?", start: start}; - } else if (stream[this._current] === "]") { - this._current++; - return {type: TOK_FLATTEN, value: "[]", start: start}; - } else { - return {type: TOK_LBRACKET, value: "[", start: start}; - } - }, - _consumeOperator: function(stream) { - var start = this._current; - var startingChar = stream[start]; - this._current++; - if (startingChar === "!") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_NE, value: "!=", start: start}; - } else { - return {type: TOK_NOT, value: "!", start: start}; - } - } else if (startingChar === "<") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_LTE, value: "<=", start: start}; - } else { - return {type: TOK_LT, value: "<", start: start}; - } - } else if (startingChar === ">") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_GTE, value: ">=", start: start}; - } else { - return {type: TOK_GT, value: ">", start: start}; - } - } else if (startingChar === "=") { - if (stream[this._current] === "=") { - this._current++; - return {type: TOK_EQ, value: "==", start: start}; - } - } - }, +/***/ }), - _consumeLiteral: function(stream) { - this._current++; - var start = this._current; - var maxLength = stream.length; - var literal; - while(stream[this._current] !== "`" && this._current < maxLength) { - // You can escape a literal char or you can escape the escape. - var current = this._current; - if (stream[current] === "\\" && (stream[current + 1] === "\\" || - stream[current + 1] === "`")) { - current += 2; - } else { - current++; - } - this._current = current; - } - var literalString = trimLeft(stream.slice(start, this._current)); - literalString = literalString.replace("\\`", "`"); - if (this._looksLikeJSON(literalString)) { - literal = JSON.parse(literalString); - } else { - // Try to JSON parse it as "" - literal = JSON.parse("\"" + literalString + "\""); - } - // +1 gets us to the ending "`", +1 to move on to the next char. - this._current++; - return literal; - }, +/***/ 6134: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _looksLikeJSON: function(literalString) { - var startingChars = "[{\""; - var jsonLiterals = ["true", "false", "null"]; - var numberLooking = "-0123456789"; +"use strict"; - if (literalString === "") { - return false; - } else if (startingChars.indexOf(literalString[0]) >= 0) { - return true; - } else if (jsonLiterals.indexOf(literalString) >= 0) { - return true; - } else if (numberLooking.indexOf(literalString[0]) >= 0) { - try { - JSON.parse(literalString); - return true; - } catch (ex) { - return false; - } - } else { - return false; - } - } - }; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const stream_1 = __nccwpck_require__(92413); +/** + * Convenient class to convert the process of scaning keys to a readable stream. + * + * @export + * @class ScanStream + * @extends {Readable} + */ +class ScanStream extends stream_1.Readable { + constructor(opt) { + super(opt); + this.opt = opt; + this._redisCursor = "0"; + this._redisDrained = false; + } + _read() { + if (this._redisDrained) { + this.push(null); + return; + } + const args = [this._redisCursor]; + if (this.opt.key) { + args.unshift(this.opt.key); + } + if (this.opt.match) { + args.push("MATCH", this.opt.match); + } + if (this.opt.type) { + args.push("TYPE", this.opt.type); + } + if (this.opt.count) { + args.push("COUNT", String(this.opt.count)); + } + this.opt.redis[this.opt.command](args, (err, res) => { + if (err) { + this.emit("error", err); + return; + } + this._redisCursor = res[0] instanceof Buffer ? res[0].toString() : res[0]; + if (this._redisCursor === "0") { + this._redisDrained = true; + } + this.push(res[1]); + }); + } + close() { + this._redisDrained = true; + } +} +exports.default = ScanStream; - var bindingPower = {}; - bindingPower[TOK_EOF] = 0; - bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0; - bindingPower[TOK_QUOTEDIDENTIFIER] = 0; - bindingPower[TOK_RBRACKET] = 0; - bindingPower[TOK_RPAREN] = 0; - bindingPower[TOK_COMMA] = 0; - bindingPower[TOK_RBRACE] = 0; - bindingPower[TOK_NUMBER] = 0; - bindingPower[TOK_CURRENT] = 0; - bindingPower[TOK_EXPREF] = 0; - bindingPower[TOK_PIPE] = 1; - bindingPower[TOK_OR] = 2; - bindingPower[TOK_AND] = 3; - bindingPower[TOK_EQ] = 5; - bindingPower[TOK_GT] = 5; - bindingPower[TOK_LT] = 5; - bindingPower[TOK_GTE] = 5; - bindingPower[TOK_LTE] = 5; - bindingPower[TOK_NE] = 5; - bindingPower[TOK_FLATTEN] = 9; - bindingPower[TOK_STAR] = 20; - bindingPower[TOK_FILTER] = 21; - bindingPower[TOK_DOT] = 40; - bindingPower[TOK_NOT] = 45; - bindingPower[TOK_LBRACE] = 50; - bindingPower[TOK_LBRACKET] = 55; - bindingPower[TOK_LPAREN] = 60; - function Parser() { - } +/***/ }), - Parser.prototype = { - parse: function(expression) { - this._loadTokens(expression); - this.index = 0; - var ast = this.expression(0); - if (this._lookahead(0) !== TOK_EOF) { - var t = this._lookaheadToken(0); - var error = new Error( - "Unexpected token type: " + t.type + ", value: " + t.value); - error.name = "ParserError"; - throw error; - } - return ast; - }, +/***/ 73527: +/***/ ((__unused_webpack_module, exports) => { - _loadTokens: function(expression) { - var lexer = new Lexer(); - var tokens = lexer.tokenize(expression); - tokens.push({type: TOK_EOF, value: "", start: expression.length}); - this.tokens = tokens; - }, +"use strict"; - expression: function(rbp) { - var leftToken = this._lookaheadToken(0); - this._advance(); - var left = this.nud(leftToken); - var currentToken = this._lookahead(0); - while (rbp < bindingPower[currentToken]) { - this._advance(); - left = this.led(currentToken, left); - currentToken = this._lookahead(0); - } - return left; - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +/** + * Tiny class to simplify dealing with subscription set + * + * @export + * @class SubscriptionSet + */ +class SubscriptionSet { + constructor() { + this.set = { + subscribe: {}, + psubscribe: {}, + }; + } + add(set, channel) { + this.set[mapSet(set)][channel] = true; + } + del(set, channel) { + delete this.set[mapSet(set)][channel]; + } + channels(set) { + return Object.keys(this.set[mapSet(set)]); + } + isEmpty() { + return (this.channels("subscribe").length === 0 && + this.channels("psubscribe").length === 0); + } +} +exports.default = SubscriptionSet; +function mapSet(set) { + if (set === "unsubscribe") { + return "subscribe"; + } + if (set === "punsubscribe") { + return "psubscribe"; + } + return set; +} - _lookahead: function(number) { - return this.tokens[this.index + number].type; - }, - _lookaheadToken: function(number) { - return this.tokens[this.index + number]; - }, +/***/ }), - _advance: function() { - this.index++; - }, +/***/ 97873: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - nud: function(token) { - var left; - var right; - var expression; - switch (token.type) { - case TOK_LITERAL: - return {type: "Literal", value: token.value}; - case TOK_UNQUOTEDIDENTIFIER: - return {type: "Field", name: token.value}; - case TOK_QUOTEDIDENTIFIER: - var node = {type: "Field", name: token.value}; - if (this._lookahead(0) === TOK_LPAREN) { - throw new Error("Quoted identifier not allowed for function names."); - } else { - return node; - } - break; - case TOK_NOT: - right = this.expression(bindingPower.Not); - return {type: "NotExpression", children: [right]}; - case TOK_STAR: - left = {type: "Identity"}; - right = null; - if (this._lookahead(0) === TOK_RBRACKET) { - // This can happen in a multiselect, - // [a, b, *] - right = {type: "Identity"}; - } else { - right = this._parseProjectionRHS(bindingPower.Star); - } - return {type: "ValueProjection", children: [left, right]}; - case TOK_FILTER: - return this.led(token.type, {type: "Identity"}); - case TOK_LBRACE: - return this._parseMultiselectHash(); - case TOK_FLATTEN: - left = {type: TOK_FLATTEN, children: [{type: "Identity"}]}; - right = this._parseProjectionRHS(bindingPower.Flatten); - return {type: "Projection", children: [left, right]}; - case TOK_LBRACKET: - if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) { - right = this._parseIndexExpression(); - return this._projectIfSlice({type: "Identity"}, right); - } else if (this._lookahead(0) === TOK_STAR && - this._lookahead(1) === TOK_RBRACKET) { - this._advance(); - this._advance(); - right = this._parseProjectionRHS(bindingPower.Star); - return {type: "Projection", - children: [{type: "Identity"}, right]}; - } else { - return this._parseMultiselectList(); - } - break; - case TOK_CURRENT: - return {type: TOK_CURRENT}; - case TOK_EXPREF: - expression = this.expression(bindingPower.Expref); - return {type: "ExpressionReference", children: [expression]}; - case TOK_LPAREN: - var args = []; - while (this._lookahead(0) !== TOK_RPAREN) { - if (this._lookahead(0) === TOK_CURRENT) { - expression = {type: TOK_CURRENT}; - this._advance(); - } else { - expression = this.expression(0); - } - args.push(expression); - } - this._match(TOK_RPAREN); - return args[0]; - default: - this._errorToken(token); - } - }, +"use strict"; - led: function(tokenName, left) { - var right; - switch(tokenName) { - case TOK_DOT: - var rbp = bindingPower.Dot; - if (this._lookahead(0) !== TOK_STAR) { - right = this._parseDotRHS(rbp); - return {type: "Subexpression", children: [left, right]}; - } else { - // Creating a projection. - this._advance(); - right = this._parseProjectionRHS(rbp); - return {type: "ValueProjection", children: [left, right]}; - } - break; - case TOK_PIPE: - right = this.expression(bindingPower.Pipe); - return {type: TOK_PIPE, children: [left, right]}; - case TOK_OR: - right = this.expression(bindingPower.Or); - return {type: "OrExpression", children: [left, right]}; - case TOK_AND: - right = this.expression(bindingPower.And); - return {type: "AndExpression", children: [left, right]}; - case TOK_LPAREN: - var name = left.name; - var args = []; - var expression, node; - while (this._lookahead(0) !== TOK_RPAREN) { - if (this._lookahead(0) === TOK_CURRENT) { - expression = {type: TOK_CURRENT}; - this._advance(); - } else { - expression = this.expression(0); - } - if (this._lookahead(0) === TOK_COMMA) { - this._match(TOK_COMMA); - } - args.push(expression); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const PromiseContainer = __nccwpck_require__(71475); +const lodash_1 = __nccwpck_require__(20961); +const calculateSlot = __nccwpck_require__(48481); +const standard_as_callback_1 = __nccwpck_require__(91543); +exports.kExec = Symbol("exec"); +exports.kCallbacks = Symbol("callbacks"); +exports.notAllowedAutoPipelineCommands = [ + "auth", + "info", + "script", + "quit", + "cluster", + "pipeline", + "multi", + "subscribe", + "psubscribe", + "unsubscribe", + "unpsubscribe", +]; +function executeAutoPipeline(client, slotKey) { + /* + If a pipeline is already executing, keep queueing up commands + since ioredis won't serve two pipelines at the same time + */ + if (client._runningAutoPipelines.has(slotKey)) { + return; + } + client._runningAutoPipelines.add(slotKey); + // Get the pipeline and immediately delete it so that new commands are queued on a new pipeline + const pipeline = client._autoPipelines.get(slotKey); + client._autoPipelines.delete(slotKey); + const callbacks = pipeline[exports.kCallbacks]; + // Perform the call + pipeline.exec(function (err, results) { + client._runningAutoPipelines.delete(slotKey); + /* + Invoke all callback in nextTick so the stack is cleared + and callbacks can throw errors without affecting other callbacks. + */ + if (err) { + for (let i = 0; i < callbacks.length; i++) { + process.nextTick(callbacks[i], err); } - this._match(TOK_RPAREN); - node = {type: "Function", name: name, children: args}; - return node; - case TOK_FILTER: - var condition = this.expression(0); - this._match(TOK_RBRACKET); - if (this._lookahead(0) === TOK_FLATTEN) { - right = {type: "Identity"}; - } else { - right = this._parseProjectionRHS(bindingPower.Filter); + } + else { + for (let i = 0; i < callbacks.length; i++) { + process.nextTick(callbacks[i], ...results[i]); } - return {type: "FilterProjection", children: [left, right, condition]}; - case TOK_FLATTEN: - var leftNode = {type: TOK_FLATTEN, children: [left]}; - var rightNode = this._parseProjectionRHS(bindingPower.Flatten); - return {type: "Projection", children: [leftNode, rightNode]}; - case TOK_EQ: - case TOK_NE: - case TOK_GT: - case TOK_GTE: - case TOK_LT: - case TOK_LTE: - return this._parseComparator(left, tokenName); - case TOK_LBRACKET: - var token = this._lookaheadToken(0); - if (token.type === TOK_NUMBER || token.type === TOK_COLON) { - right = this._parseIndexExpression(); - return this._projectIfSlice(left, right); - } else { - this._match(TOK_STAR); - this._match(TOK_RBRACKET); - right = this._parseProjectionRHS(bindingPower.Star); - return {type: "Projection", children: [left, right]}; + } + // If there is another pipeline on the same node, immediately execute it without waiting for nextTick + if (client._autoPipelines.has(slotKey)) { + executeAutoPipeline(client, slotKey); + } + }); +} +function shouldUseAutoPipelining(client, functionName, commandName) { + return (functionName && + client.options.enableAutoPipelining && + !client.isPipeline && + !exports.notAllowedAutoPipelineCommands.includes(commandName) && + !client.options.autoPipeliningIgnoredCommands.includes(commandName)); +} +exports.shouldUseAutoPipelining = shouldUseAutoPipelining; +/** + * @private + */ +function getFirstValueInFlattenedArray(args) { + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + if (typeof arg === "string") { + return arg; + } + else if (Array.isArray(arg) || lodash_1.isArguments(arg)) { + if (arg.length === 0) { + continue; } - break; - default: - this._errorToken(this._lookaheadToken(0)); + return arg[0]; } - }, + const flattened = lodash_1.flatten([arg]); + if (flattened.length > 0) { + return flattened[0]; + } + } + return undefined; +} +exports.getFirstValueInFlattenedArray = getFirstValueInFlattenedArray; +function executeWithAutoPipelining(client, functionName, commandName, args, callback) { + const CustomPromise = PromiseContainer.get(); + // On cluster mode let's wait for slots to be available + if (client.isCluster && !client.slots.length) { + return new CustomPromise(function (resolve, reject) { + client.delayUntilReady((err) => { + if (err) { + reject(err); + return; + } + executeWithAutoPipelining(client, functionName, commandName, args, callback).then(resolve, reject); + }); + }); + } + // If we have slot information, we can improve routing by grouping slots served by the same subset of nodes + // Note that the first value in args may be a (possibly empty) array. + // ioredis will only flatten one level of the array, in the Command constructor. + const prefix = client.options.keyPrefix || ""; + const slotKey = client.isCluster + ? client.slots[calculateSlot(`${prefix}${getFirstValueInFlattenedArray(args)}`)].join(",") + : "main"; + if (!client._autoPipelines.has(slotKey)) { + const pipeline = client.pipeline(); + pipeline[exports.kExec] = false; + pipeline[exports.kCallbacks] = []; + client._autoPipelines.set(slotKey, pipeline); + } + const pipeline = client._autoPipelines.get(slotKey); + /* + Mark the pipeline as scheduled. + The symbol will make sure that the pipeline is only scheduled once per tick. + New commands are appended to an already scheduled pipeline. + */ + if (!pipeline[exports.kExec]) { + pipeline[exports.kExec] = true; + /* + Deferring with setImmediate so we have a chance to capture multiple + commands that can be scheduled by I/O events already in the event loop queue. + */ + setImmediate(executeAutoPipeline, client, slotKey); + } + // Create the promise which will execute the + const autoPipelinePromise = new CustomPromise(function (resolve, reject) { + pipeline[exports.kCallbacks].push(function (err, value) { + if (err) { + reject(err); + return; + } + resolve(value); + }); + pipeline[functionName](...args); + }); + return standard_as_callback_1.default(autoPipelinePromise, callback); +} +exports.executeWithAutoPipelining = executeWithAutoPipelining; - _match: function(tokenType) { - if (this._lookahead(0) === tokenType) { - this._advance(); - } else { - var t = this._lookaheadToken(0); - var error = new Error("Expected " + tokenType + ", got: " + t.type); - error.name = "ParserError"; - throw error; - } - }, - _errorToken: function(token) { - var error = new Error("Invalid token (" + - token.type + "): \"" + - token.value + "\""); - error.name = "ParserError"; - throw error; - }, +/***/ }), +/***/ 35835: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _parseIndexExpression: function() { - if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) { - return this._parseSliceExpression(); - } else { - var node = { - type: "Index", - value: this._lookaheadToken(0).value}; - this._advance(); - this._match(TOK_RBRACKET); - return node; - } - }, +"use strict"; - _projectIfSlice: function(left, right) { - var indexExpr = {type: "IndexExpression", children: [left, right]}; - if (right.type === "Slice") { - return { - type: "Projection", - children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)] - }; - } else { - return indexExpr; - } - }, +Object.defineProperty(exports, "__esModule", ({ value: true })); +const dns_1 = __nccwpck_require__(40881); +exports.DEFAULT_CLUSTER_OPTIONS = { + clusterRetryStrategy: (times) => Math.min(100 + times * 2, 2000), + enableOfflineQueue: true, + enableReadyCheck: true, + scaleReads: "master", + maxRedirections: 16, + retryDelayOnMoved: 0, + retryDelayOnFailover: 100, + retryDelayOnClusterDown: 100, + retryDelayOnTryAgain: 100, + slotsRefreshTimeout: 1000, + slotsRefreshInterval: 5000, + useSRVRecords: false, + resolveSrv: dns_1.resolveSrv, + dnsLookup: dns_1.lookup, + enableAutoPipelining: false, + autoPipeliningIgnoredCommands: [], + maxScriptsCachingTime: 60000, +}; - _parseSliceExpression: function() { - // [start:end:step] where each part is optional, as well as the last - // colon. - var parts = [null, null, null]; - var index = 0; - var currentToken = this._lookahead(0); - while (currentToken !== TOK_RBRACKET && index < 3) { - if (currentToken === TOK_COLON) { - index++; - this._advance(); - } else if (currentToken === TOK_NUMBER) { - parts[index] = this._lookaheadToken(0).value; - this._advance(); - } else { - var t = this._lookahead(0); - var error = new Error("Syntax error, unexpected token: " + - t.value + "(" + t.type + ")"); - error.name = "Parsererror"; - throw error; - } - currentToken = this._lookahead(0); - } - this._match(TOK_RBRACKET); - return { - type: "Slice", - children: parts - }; - }, - _parseComparator: function(left, comparator) { - var right = this.expression(bindingPower[comparator]); - return {type: "Comparator", name: comparator, children: [left, right]}; - }, +/***/ }), + +/***/ 18394: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const util_1 = __nccwpck_require__(94582); +const utils_1 = __nccwpck_require__(94832); +const redis_1 = __nccwpck_require__(83609); +const debug = utils_1.Debug("cluster:subscriber"); +class ClusterSubscriber { + constructor(connectionPool, emitter) { + this.connectionPool = connectionPool; + this.emitter = emitter; + this.started = false; + this.subscriber = null; + this.connectionPool.on("-node", (_, key) => { + if (!this.started || !this.subscriber) { + return; + } + if (util_1.getNodeKey(this.subscriber.options) === key) { + debug("subscriber has left, selecting a new one..."); + this.selectSubscriber(); + } + }); + this.connectionPool.on("+node", () => { + if (!this.started || this.subscriber) { + return; + } + debug("a new node is discovered and there is no subscriber, selecting a new one..."); + this.selectSubscriber(); + }); + } + getInstance() { + return this.subscriber; + } + selectSubscriber() { + const lastActiveSubscriber = this.lastActiveSubscriber; + // Disconnect the previous subscriber even if there + // will not be a new one. + if (lastActiveSubscriber) { + lastActiveSubscriber.disconnect(); + } + if (this.subscriber) { + this.subscriber.disconnect(); + } + const sampleNode = utils_1.sample(this.connectionPool.getNodes()); + if (!sampleNode) { + debug("selecting subscriber failed since there is no node discovered in the cluster yet"); + this.subscriber = null; + return; + } + const { options } = sampleNode; + debug("selected a subscriber %s:%s", options.host, options.port); + /* + * Create a specialized Redis connection for the subscription. + * Note that auto reconnection is enabled here. + * + * `enableReadyCheck` is also enabled because although subscription is allowed + * while redis is loading data from the disk, we can check if the password + * provided for the subscriber is correct, and if not, the current subscriber + * will be disconnected and a new subscriber will be selected. + */ + this.subscriber = new redis_1.default({ + port: options.port, + host: options.host, + username: options.username, + password: options.password, + enableReadyCheck: true, + connectionName: util_1.getConnectionName("subscriber", options.connectionName), + lazyConnect: true, + tls: options.tls, + }); + // Ignore the errors since they're handled in the connection pool. + this.subscriber.on("error", utils_1.noop); + // Re-subscribe previous channels + const previousChannels = { subscribe: [], psubscribe: [] }; + if (lastActiveSubscriber) { + const condition = lastActiveSubscriber.condition || lastActiveSubscriber.prevCondition; + if (condition && condition.subscriber) { + previousChannels.subscribe = condition.subscriber.channels("subscribe"); + previousChannels.psubscribe = condition.subscriber.channels("psubscribe"); + } + } + if (previousChannels.subscribe.length || + previousChannels.psubscribe.length) { + let pending = 0; + for (const type of ["subscribe", "psubscribe"]) { + const channels = previousChannels[type]; + if (channels.length) { + pending += 1; + debug("%s %d channels", type, channels.length); + this.subscriber[type](channels) + .then(() => { + if (!--pending) { + this.lastActiveSubscriber = this.subscriber; + } + }) + .catch(() => { + // TODO: should probably disconnect the subscriber and try again. + debug("failed to %s %d channels", type, channels.length); + }); + } + } + } + else { + this.lastActiveSubscriber = this.subscriber; + } + for (const event of ["message", "messageBuffer"]) { + this.subscriber.on(event, (arg1, arg2) => { + this.emitter.emit(event, arg1, arg2); + }); + } + for (const event of ["pmessage", "pmessageBuffer"]) { + this.subscriber.on(event, (arg1, arg2, arg3) => { + this.emitter.emit(event, arg1, arg2, arg3); + }); + } + } + start() { + this.started = true; + this.selectSubscriber(); + debug("started"); + } + stop() { + this.started = false; + if (this.subscriber) { + this.subscriber.disconnect(); + this.subscriber = null; + } + debug("stopped"); + } +} +exports.default = ClusterSubscriber; + - _parseDotRHS: function(rbp) { - var lookahead = this._lookahead(0); - var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR]; - if (exprTokens.indexOf(lookahead) >= 0) { - return this.expression(rbp); - } else if (lookahead === TOK_LBRACKET) { - this._match(TOK_LBRACKET); - return this._parseMultiselectList(); - } else if (lookahead === TOK_LBRACE) { - this._match(TOK_LBRACE); - return this._parseMultiselectHash(); - } - }, +/***/ }), - _parseProjectionRHS: function(rbp) { - var right; - if (bindingPower[this._lookahead(0)] < 10) { - right = {type: "Identity"}; - } else if (this._lookahead(0) === TOK_LBRACKET) { - right = this.expression(rbp); - } else if (this._lookahead(0) === TOK_FILTER) { - right = this.expression(rbp); - } else if (this._lookahead(0) === TOK_DOT) { - this._match(TOK_DOT); - right = this._parseDotRHS(rbp); - } else { - var t = this._lookaheadToken(0); - var error = new Error("Sytanx error, unexpected token: " + - t.value + "(" + t.type + ")"); - error.name = "ParserError"; - throw error; - } - return right; - }, +/***/ 34589: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _parseMultiselectList: function() { - var expressions = []; - while (this._lookahead(0) !== TOK_RBRACKET) { - var expression = this.expression(0); - expressions.push(expression); - if (this._lookahead(0) === TOK_COMMA) { - this._match(TOK_COMMA); - if (this._lookahead(0) === TOK_RBRACKET) { - throw new Error("Unexpected token Rbracket"); - } - } - } - this._match(TOK_RBRACKET); - return {type: "MultiSelectList", children: expressions}; - }, +"use strict"; - _parseMultiselectHash: function() { - var pairs = []; - var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER]; - var keyToken, keyName, value, node; - for (;;) { - keyToken = this._lookaheadToken(0); - if (identifierTypes.indexOf(keyToken.type) < 0) { - throw new Error("Expecting an identifier token, got: " + - keyToken.type); - } - keyName = keyToken.value; - this._advance(); - this._match(TOK_COLON); - value = this.expression(0); - node = {type: "KeyValuePair", name: keyName, value: value}; - pairs.push(node); - if (this._lookahead(0) === TOK_COMMA) { - this._match(TOK_COMMA); - } else if (this._lookahead(0) === TOK_RBRACE) { - this._match(TOK_RBRACE); - break; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const events_1 = __nccwpck_require__(28614); +const utils_1 = __nccwpck_require__(94832); +const util_1 = __nccwpck_require__(94582); +const redis_1 = __nccwpck_require__(83609); +const debug = utils_1.Debug("cluster:connectionPool"); +class ConnectionPool extends events_1.EventEmitter { + constructor(redisOptions) { + super(); + this.redisOptions = redisOptions; + // master + slave = all + this.nodes = { + all: {}, + master: {}, + slave: {}, + }; + this.specifiedOptions = {}; + } + getNodes(role = "all") { + const nodes = this.nodes[role]; + return Object.keys(nodes).map((key) => nodes[key]); + } + getInstanceByKey(key) { + return this.nodes.all[key]; + } + getSampleInstance(role) { + const keys = Object.keys(this.nodes[role]); + const sampleKey = utils_1.sample(keys); + return this.nodes[role][sampleKey]; + } + /** + * Find or create a connection to the node + * + * @param {IRedisOptions} node + * @param {boolean} [readOnly=false] + * @returns {*} + * @memberof ConnectionPool + */ + findOrCreate(node, readOnly = false) { + const key = util_1.getNodeKey(node); + readOnly = Boolean(readOnly); + if (this.specifiedOptions[key]) { + Object.assign(node, this.specifiedOptions[key]); } - return {type: "MultiSelectHash", children: pairs}; - } - }; - - - function TreeInterpreter(runtime) { - this.runtime = runtime; - } - - TreeInterpreter.prototype = { - search: function(node, value) { - return this.visit(node, value); - }, - - visit: function(node, value) { - var matched, current, result, first, second, field, left, right, collected, i; - switch (node.type) { - case "Field": - if (value === null ) { - return null; - } else if (isObject(value)) { - field = value[node.name]; - if (field === undefined) { - return null; - } else { - return field; - } - } else { - return null; - } - break; - case "Subexpression": - result = this.visit(node.children[0], value); - for (i = 1; i < node.children.length; i++) { - result = this.visit(node.children[1], result); - if (result === null) { - return null; - } - } - return result; - case "IndexExpression": - left = this.visit(node.children[0], value); - right = this.visit(node.children[1], left); - return right; - case "Index": - if (!isArray(value)) { - return null; - } - var index = node.value; - if (index < 0) { - index = value.length + index; - } - result = value[index]; - if (result === undefined) { - result = null; - } - return result; - case "Slice": - if (!isArray(value)) { - return null; - } - var sliceParams = node.children.slice(0); - var computed = this.computeSliceParams(value.length, sliceParams); - var start = computed[0]; - var stop = computed[1]; - var step = computed[2]; - result = []; - if (step > 0) { - for (i = start; i < stop; i += step) { - result.push(value[i]); - } - } else { - for (i = start; i > stop; i += step) { - result.push(value[i]); - } - } - return result; - case "Projection": - // Evaluate left child. - var base = this.visit(node.children[0], value); - if (!isArray(base)) { - return null; - } - collected = []; - for (i = 0; i < base.length; i++) { - current = this.visit(node.children[1], base[i]); - if (current !== null) { - collected.push(current); - } - } - return collected; - case "ValueProjection": - // Evaluate left child. - base = this.visit(node.children[0], value); - if (!isObject(base)) { - return null; - } - collected = []; - var values = objValues(base); - for (i = 0; i < values.length; i++) { - current = this.visit(node.children[1], values[i]); - if (current !== null) { - collected.push(current); - } - } - return collected; - case "FilterProjection": - base = this.visit(node.children[0], value); - if (!isArray(base)) { - return null; - } - var filtered = []; - var finalResults = []; - for (i = 0; i < base.length; i++) { - matched = this.visit(node.children[2], base[i]); - if (!isFalse(matched)) { - filtered.push(base[i]); + else { + this.specifiedOptions[key] = node; + } + let redis; + if (this.nodes.all[key]) { + redis = this.nodes.all[key]; + if (redis.options.readOnly !== readOnly) { + redis.options.readOnly = readOnly; + debug("Change role of %s to %s", key, readOnly ? "slave" : "master"); + redis[readOnly ? "readonly" : "readwrite"]().catch(utils_1.noop); + if (readOnly) { + delete this.nodes.master[key]; + this.nodes.slave[key] = redis; } - } - for (var j = 0; j < filtered.length; j++) { - current = this.visit(node.children[1], filtered[j]); - if (current !== null) { - finalResults.push(current); + else { + delete this.nodes.slave[key]; + this.nodes.master[key] = redis; } - } - return finalResults; - case "Comparator": - first = this.visit(node.children[0], value); - second = this.visit(node.children[1], value); - switch(node.name) { - case TOK_EQ: - result = strictDeepEqual(first, second); - break; - case TOK_NE: - result = !strictDeepEqual(first, second); - break; - case TOK_GT: - result = first > second; - break; - case TOK_GTE: - result = first >= second; - break; - case TOK_LT: - result = first < second; - break; - case TOK_LTE: - result = first <= second; - break; - default: - throw new Error("Unknown comparator: " + node.name); - } - return result; - case TOK_FLATTEN: - var original = this.visit(node.children[0], value); - if (!isArray(original)) { - return null; - } - var merged = []; - for (i = 0; i < original.length; i++) { - current = original[i]; - if (isArray(current)) { - merged.push.apply(merged, current); - } else { - merged.push(current); + } + } + else { + debug("Connecting to %s as %s", key, readOnly ? "slave" : "master"); + redis = new redis_1.default(utils_1.defaults({ + // Never try to reconnect when a node is lose, + // instead, waiting for a `MOVED` error and + // fetch the slots again. + retryStrategy: null, + // Offline queue should be enabled so that + // we don't need to wait for the `ready` event + // before sending commands to the node. + enableOfflineQueue: true, + readOnly: readOnly, + }, node, this.redisOptions, { lazyConnect: true })); + this.nodes.all[key] = redis; + this.nodes[readOnly ? "slave" : "master"][key] = redis; + redis.once("end", () => { + this.removeNode(key); + this.emit("-node", redis, key); + if (!Object.keys(this.nodes.all).length) { + this.emit("drain"); } - } - return merged; - case "Identity": - return value; - case "MultiSelectList": - if (value === null) { - return null; - } - collected = []; - for (i = 0; i < node.children.length; i++) { - collected.push(this.visit(node.children[i], value)); - } - return collected; - case "MultiSelectHash": - if (value === null) { - return null; - } - collected = {}; - var child; - for (i = 0; i < node.children.length; i++) { - child = node.children[i]; - collected[child.name] = this.visit(child.value, value); - } - return collected; - case "OrExpression": - matched = this.visit(node.children[0], value); - if (isFalse(matched)) { - matched = this.visit(node.children[1], value); - } - return matched; - case "AndExpression": - first = this.visit(node.children[0], value); + }); + this.emit("+node", redis, key); + redis.on("error", function (error) { + this.emit("nodeError", error, key); + }); + } + return redis; + } + /** + * Remove a node from the pool. + */ + removeNode(key) { + const { nodes } = this; + if (nodes.all[key]) { + debug("Remove %s from the pool", key); + delete nodes.all[key]; + } + delete nodes.master[key]; + delete nodes.slave[key]; + } + /** + * Reset the pool with a set of nodes. + * The old node will be removed. + * + * @param {(Array)} nodes + * @memberof ConnectionPool + */ + reset(nodes) { + debug("Reset with %O", nodes); + const newNodes = {}; + nodes.forEach((node) => { + const key = util_1.getNodeKey(node); + // Don't override the existing (master) node + // when the current one is slave. + if (!(node.readOnly && newNodes[key])) { + newNodes[key] = node; + } + }); + Object.keys(this.nodes.all).forEach((key) => { + if (!newNodes[key]) { + debug("Disconnect %s because the node does not hold any slot", key); + this.nodes.all[key].disconnect(); + this.removeNode(key); + } + }); + Object.keys(newNodes).forEach((key) => { + const node = newNodes[key]; + this.findOrCreate(node, node.readOnly); + }); + } +} +exports.default = ConnectionPool; - if (isFalse(first) === true) { - return first; - } - return this.visit(node.children[1], value); - case "NotExpression": - first = this.visit(node.children[0], value); - return isFalse(first); - case "Literal": - return node.value; - case TOK_PIPE: - left = this.visit(node.children[0], value); - return this.visit(node.children[1], left); - case TOK_CURRENT: - return value; - case "Function": - var resolvedArgs = []; - for (i = 0; i < node.children.length; i++) { - resolvedArgs.push(this.visit(node.children[i], value)); - } - return this.runtime.callFunction(node.name, resolvedArgs); - case "ExpressionReference": - var refNode = node.children[0]; - // Tag the node with a specific attribute so the type - // checker verify the type. - refNode.jmespathType = TOK_EXPREF; - return refNode; - default: - throw new Error("Unknown node type: " + node.type); - } - }, - computeSliceParams: function(arrayLength, sliceParams) { - var start = sliceParams[0]; - var stop = sliceParams[1]; - var step = sliceParams[2]; - var computed = [null, null, null]; - if (step === null) { - step = 1; - } else if (step === 0) { - var error = new Error("Invalid slice, step cannot be 0"); - error.name = "RuntimeError"; - throw error; +/***/ }), + +/***/ 12770: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +"use strict"; + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils_1 = __nccwpck_require__(94832); +const Deque = __nccwpck_require__(42342); +const debug = utils_1.Debug("delayqueue"); +/** + * Queue that runs items after specified duration + * + * @export + * @class DelayQueue + */ +class DelayQueue { + constructor() { + this.queues = {}; + this.timeouts = {}; + } + /** + * Add a new item to the queue + * + * @param {string} bucket bucket name + * @param {Function} item function that will run later + * @param {IDelayQueueOptions} options + * @memberof DelayQueue + */ + push(bucket, item, options) { + const callback = options.callback || process.nextTick; + if (!this.queues[bucket]) { + this.queues[bucket] = new Deque(); } - var stepValueNegative = step < 0 ? true : false; - - if (start === null) { - start = stepValueNegative ? arrayLength - 1 : 0; - } else { - start = this.capSliceRange(arrayLength, start, step); + const queue = this.queues[bucket]; + queue.push(item); + if (!this.timeouts[bucket]) { + this.timeouts[bucket] = setTimeout(() => { + callback(() => { + this.timeouts[bucket] = null; + this.execute(bucket); + }); + }, options.timeout); } - - if (stop === null) { - stop = stepValueNegative ? -1 : arrayLength; - } else { - stop = this.capSliceRange(arrayLength, stop, step); + } + execute(bucket) { + const queue = this.queues[bucket]; + if (!queue) { + return; } - computed[0] = start; - computed[1] = stop; - computed[2] = step; - return computed; - }, + const { length } = queue; + if (!length) { + return; + } + debug("send %d commands in %s queue", length, bucket); + this.queues[bucket] = null; + while (queue.length > 0) { + queue.shift()(); + } + } +} +exports.default = DelayQueue; - capSliceRange: function(arrayLength, actualValue, step) { - if (actualValue < 0) { - actualValue += arrayLength; - if (actualValue < 0) { - actualValue = step < 0 ? -1 : 0; - } - } else if (actualValue >= arrayLength) { - actualValue = step < 0 ? arrayLength - 1 : arrayLength; - } - return actualValue; - } - }; +/***/ }), - function Runtime(interpreter) { - this._interpreter = interpreter; - this.functionTable = { - // name: [function, ] - // The can be: - // - // { - // args: [[type1, type2], [type1, type2]], - // variadic: true|false - // } - // - // Each arg in the arg list is a list of valid types - // (if the function is overloaded and supports multiple - // types. If the type is "any" then no type checking - // occurs on the argument. Variadic is optional - // and if not provided is assumed to be false. - abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]}, - avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, - ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]}, - contains: { - _func: this._functionContains, - _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}, - {types: [TYPE_ANY]}]}, - "ends_with": { - _func: this._functionEndsWith, - _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, - floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]}, - length: { - _func: this._functionLength, - _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]}, - map: { - _func: this._functionMap, - _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]}, - max: { - _func: this._functionMax, - _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, - "merge": { - _func: this._functionMerge, - _signature: [{types: [TYPE_OBJECT], variadic: true}] - }, - "max_by": { - _func: this._functionMaxBy, - _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] - }, - sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, - "starts_with": { - _func: this._functionStartsWith, - _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, - min: { - _func: this._functionMin, - _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, - "min_by": { - _func: this._functionMinBy, - _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] - }, - type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]}, - keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]}, - values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]}, - sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]}, - "sort_by": { - _func: this._functionSortBy, - _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] - }, - join: { - _func: this._functionJoin, - _signature: [ - {types: [TYPE_STRING]}, - {types: [TYPE_ARRAY_STRING]} - ] - }, - reverse: { - _func: this._functionReverse, - _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]}, - "to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]}, - "to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]}, - "to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]}, - "not_null": { - _func: this._functionNotNull, - _signature: [{types: [TYPE_ANY], variadic: true}] - } - }; - } +/***/ 17208: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - Runtime.prototype = { - callFunction: function(name, resolvedArgs) { - var functionEntry = this.functionTable[name]; - if (functionEntry === undefined) { - throw new Error("Unknown function: " + name + "()"); - } - this._validateArgs(name, resolvedArgs, functionEntry._signature); - return functionEntry._func.call(this, resolvedArgs); - }, +"use strict"; - _validateArgs: function(name, args, signature) { - // Validating the args requires validating - // the correct arity and the correct type of each arg. - // If the last argument is declared as variadic, then we need - // a minimum number of args to be required. Otherwise it has to - // be an exact amount. - var pluralized; - if (signature[signature.length - 1].variadic) { - if (args.length < signature.length) { - pluralized = signature.length === 1 ? " argument" : " arguments"; - throw new Error("ArgumentError: " + name + "() " + - "takes at least" + signature.length + pluralized + - " but received " + args.length); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const events_1 = __nccwpck_require__(28614); +const ClusterAllFailedError_1 = __nccwpck_require__(97282); +const utils_1 = __nccwpck_require__(94832); +const ConnectionPool_1 = __nccwpck_require__(34589); +const util_1 = __nccwpck_require__(94582); +const ClusterSubscriber_1 = __nccwpck_require__(18394); +const DelayQueue_1 = __nccwpck_require__(12770); +const ScanStream_1 = __nccwpck_require__(6134); +const redis_errors_1 = __nccwpck_require__(81879); +const standard_as_callback_1 = __nccwpck_require__(91543); +const PromiseContainer = __nccwpck_require__(71475); +const ClusterOptions_1 = __nccwpck_require__(35835); +const utils_2 = __nccwpck_require__(94832); +const commands = __nccwpck_require__(98020); +const command_1 = __nccwpck_require__(90803); +const redis_1 = __nccwpck_require__(83609); +const commander_1 = __nccwpck_require__(33642); +const Deque = __nccwpck_require__(42342); +const debug = utils_1.Debug("cluster"); +/** + * Client for the official Redis Cluster + * + * @class Cluster + * @extends {EventEmitter} + */ +class Cluster extends events_1.EventEmitter { + /** + * Creates an instance of Cluster. + * + * @param {((string | number | object)[])} startupNodes + * @param {IClusterOptions} [options={}] + * @memberof Cluster + */ + constructor(startupNodes, options = {}) { + super(); + this.slots = []; + this.retryAttempts = 0; + this.delayQueue = new DelayQueue_1.default(); + this.offlineQueue = new Deque(); + this.isRefreshing = false; + this.isCluster = true; + this._autoPipelines = new Map(); + this._groupsIds = {}; + this._groupsBySlot = Array(16384); + this._runningAutoPipelines = new Set(); + this._readyDelayedCallbacks = []; + this._addedScriptHashes = {}; + /** + * Every time Cluster#connect() is called, this value will be + * auto-incrementing. The purpose of this value is used for + * discarding previous connect attampts when creating a new + * connection. + * + * @private + * @type {number} + * @memberof Cluster + */ + this.connectionEpoch = 0; + commander_1.default.call(this); + this.startupNodes = startupNodes; + this.options = utils_1.defaults({}, options, ClusterOptions_1.DEFAULT_CLUSTER_OPTIONS, this.options); + // validate options + if (typeof this.options.scaleReads !== "function" && + ["all", "master", "slave"].indexOf(this.options.scaleReads) === -1) { + throw new Error('Invalid option scaleReads "' + + this.options.scaleReads + + '". Expected "all", "master", "slave" or a custom function'); + } + this.connectionPool = new ConnectionPool_1.default(this.options.redisOptions); + this.connectionPool.on("-node", (redis, key) => { + this.emit("-node", redis); + }); + this.connectionPool.on("+node", (redis) => { + this.emit("+node", redis); + }); + this.connectionPool.on("drain", () => { + this.setStatus("close"); + }); + this.connectionPool.on("nodeError", (error, key) => { + this.emit("node error", error, key); + }); + this.subscriber = new ClusterSubscriber_1.default(this.connectionPool, this); + if (this.options.lazyConnect) { + this.setStatus("wait"); + } + else { + this.connect().catch((err) => { + debug("connecting failed: %s", err); + }); + } + } + resetOfflineQueue() { + this.offlineQueue = new Deque(); + } + clearNodesRefreshInterval() { + if (this.slotsTimer) { + clearTimeout(this.slotsTimer); + this.slotsTimer = null; + } + } + resetNodesRefreshInterval() { + if (this.slotsTimer) { + return; + } + const nextRound = () => { + this.slotsTimer = setTimeout(() => { + debug('refreshing slot caches... (triggered by "slotsRefreshInterval" option)'); + this.refreshSlotsCache(() => { + nextRound(); + }); + }, this.options.slotsRefreshInterval); + }; + nextRound(); + } + /** + * Connect to a cluster + * + * @returns {Promise} + * @memberof Cluster + */ + connect() { + const Promise = PromiseContainer.get(); + return new Promise((resolve, reject) => { + if (this.status === "connecting" || + this.status === "connect" || + this.status === "ready") { + reject(new Error("Redis is already connecting/connected")); + return; + } + // Make sure only one timer is active at a time + clearInterval(this._addedScriptHashesCleanInterval); + // Start the script cache cleaning + this._addedScriptHashesCleanInterval = setInterval(() => { + this._addedScriptHashes = {}; + }, this.options.maxScriptsCachingTime); + const epoch = ++this.connectionEpoch; + this.setStatus("connecting"); + this.resolveStartupNodeHostnames() + .then((nodes) => { + if (this.connectionEpoch !== epoch) { + debug("discard connecting after resolving startup nodes because epoch not match: %d != %d", epoch, this.connectionEpoch); + reject(new redis_errors_1.RedisError("Connection is discarded because a new connection is made")); + return; + } + if (this.status !== "connecting") { + debug("discard connecting after resolving startup nodes because the status changed to %s", this.status); + reject(new redis_errors_1.RedisError("Connection is aborted")); + return; + } + this.connectionPool.reset(nodes); + function readyHandler() { + this.setStatus("ready"); + this.retryAttempts = 0; + this.executeOfflineCommands(); + this.resetNodesRefreshInterval(); + resolve(); + } + let closeListener = undefined; + const refreshListener = () => { + this.invokeReadyDelayedCallbacks(undefined); + this.removeListener("close", closeListener); + this.manuallyClosing = false; + this.setStatus("connect"); + if (this.options.enableReadyCheck) { + this.readyCheck((err, fail) => { + if (err || fail) { + debug("Ready check failed (%s). Reconnecting...", err || fail); + if (this.status === "connect") { + this.disconnect(true); + } + } + else { + readyHandler.call(this); + } + }); + } + else { + readyHandler.call(this); + } + }; + closeListener = function () { + const error = new Error("None of startup nodes is available"); + this.removeListener("refresh", refreshListener); + this.invokeReadyDelayedCallbacks(error); + reject(error); + }; + this.once("refresh", refreshListener); + this.once("close", closeListener); + this.once("close", this.handleCloseEvent.bind(this)); + this.refreshSlotsCache(function (err) { + if (err && err.message === "Failed to refresh slots cache.") { + redis_1.default.prototype.silentEmit.call(this, "error", err); + this.connectionPool.reset([]); + } + }.bind(this)); + this.subscriber.start(); + }) + .catch((err) => { + this.setStatus("close"); + this.handleCloseEvent(err); + this.invokeReadyDelayedCallbacks(err); + reject(err); + }); + }); + } + /** + * Called when closed to check whether a reconnection should be made + * + * @private + * @memberof Cluster + */ + handleCloseEvent(reason) { + if (reason) { + debug("closed because %s", reason); + } + let retryDelay; + if (!this.manuallyClosing && + typeof this.options.clusterRetryStrategy === "function") { + retryDelay = this.options.clusterRetryStrategy.call(this, ++this.retryAttempts, reason); + } + if (typeof retryDelay === "number") { + this.setStatus("reconnecting"); + this.reconnectTimeout = setTimeout(function () { + this.reconnectTimeout = null; + debug("Cluster is disconnected. Retrying after %dms", retryDelay); + this.connect().catch(function (err) { + debug("Got error %s when reconnecting. Ignoring...", err); + }); + }.bind(this), retryDelay); + } + else { + this.setStatus("end"); + this.flushQueue(new Error("None of startup nodes is available")); + } + } + /** + * Disconnect from every node in the cluster. + * + * @param {boolean} [reconnect=false] + * @memberof Cluster + */ + disconnect(reconnect = false) { + const status = this.status; + this.setStatus("disconnecting"); + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = null; + if (!reconnect) { + this.manuallyClosing = true; + } + if (this.reconnectTimeout && !reconnect) { + clearTimeout(this.reconnectTimeout); + this.reconnectTimeout = null; + debug("Canceled reconnecting attempts"); + } + this.clearNodesRefreshInterval(); + this.subscriber.stop(); + if (status === "wait") { + this.setStatus("close"); + this.handleCloseEvent(); + } + else { + this.connectionPool.reset([]); + } + } + /** + * Quit the cluster gracefully. + * + * @param {CallbackFunction<'OK'>} [callback] + * @returns {Promise<'OK'>} + * @memberof Cluster + */ + quit(callback) { + const status = this.status; + this.setStatus("disconnecting"); + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = null; + this.manuallyClosing = true; + if (this.reconnectTimeout) { + clearTimeout(this.reconnectTimeout); + this.reconnectTimeout = null; + } + this.clearNodesRefreshInterval(); + this.subscriber.stop(); + const Promise = PromiseContainer.get(); + if (status === "wait") { + const ret = standard_as_callback_1.default(Promise.resolve("OK"), callback); + // use setImmediate to make sure "close" event + // being emitted after quit() is returned + setImmediate(function () { + this.setStatus("close"); + this.handleCloseEvent(); + }.bind(this)); + return ret; + } + return standard_as_callback_1.default(Promise.all(this.nodes().map((node) => node.quit().catch((err) => { + // Ignore the error caused by disconnecting since + // we're disconnecting... + if (err.message === utils_2.CONNECTION_CLOSED_ERROR_MSG) { + return "OK"; + } + throw err; + }))).then(() => "OK"), callback); + } + /** + * Create a new instance with the same startup nodes and options as the current one. + * + * @example + * ```js + * var cluster = new Redis.Cluster([{ host: "127.0.0.1", port: "30001" }]); + * var anotherCluster = cluster.duplicate(); + * ``` + * + * @public + * @param {((string | number | object)[])} [overrideStartupNodes=[]] + * @param {IClusterOptions} [overrideOptions={}] + * @memberof Cluster + */ + duplicate(overrideStartupNodes = [], overrideOptions = {}) { + const startupNodes = overrideStartupNodes.length > 0 + ? overrideStartupNodes + : this.startupNodes.slice(0); + const options = Object.assign({}, this.options, overrideOptions); + return new Cluster(startupNodes, options); + } + /** + * Get nodes with the specified role + * + * @param {NodeRole} [role='all'] + * @returns {any[]} + * @memberof Cluster + */ + nodes(role = "all") { + if (role !== "all" && role !== "master" && role !== "slave") { + throw new Error('Invalid role "' + role + '". Expected "all", "master" or "slave"'); + } + return this.connectionPool.getNodes(role); + } + // This is needed in order not to install a listener for each auto pipeline + delayUntilReady(callback) { + this._readyDelayedCallbacks.push(callback); + } + /** + * Get the number of commands queued in automatic pipelines. + * + * This is not available (and returns 0) until the cluster is connected and slots information have been received. + */ + get autoPipelineQueueSize() { + let queued = 0; + for (const pipeline of this._autoPipelines.values()) { + queued += pipeline.length; + } + return queued; + } + /** + * Change cluster instance's status + * + * @private + * @param {ClusterStatus} status + * @memberof Cluster + */ + setStatus(status) { + debug("status: %s -> %s", this.status || "[empty]", status); + this.status = status; + process.nextTick(() => { + this.emit(status); + }); + } + /** + * Refresh the slot cache + * + * @private + * @param {CallbackFunction} [callback] + * @memberof Cluster + */ + refreshSlotsCache(callback) { + if (this.isRefreshing) { + if (typeof callback === "function") { + process.nextTick(callback); } - } else if (args.length !== signature.length) { - pluralized = signature.length === 1 ? " argument" : " arguments"; - throw new Error("ArgumentError: " + name + "() " + - "takes " + signature.length + pluralized + - " but received " + args.length); + return; } - var currentSpec; - var actualType; - var typeMatched; - for (var i = 0; i < signature.length; i++) { - typeMatched = false; - currentSpec = signature[i].types; - actualType = this._getTypeName(args[i]); - for (var j = 0; j < currentSpec.length; j++) { - if (this._typeMatches(actualType, currentSpec[j], args[i])) { - typeMatched = true; - break; - } + this.isRefreshing = true; + const _this = this; + const wrapper = function (error) { + _this.isRefreshing = false; + if (typeof callback === "function") { + callback(error); } - if (!typeMatched) { - throw new Error("TypeError: " + name + "() " + - "expected argument " + (i + 1) + - " to be type " + currentSpec + - " but received type " + actualType + - " instead."); + }; + const nodes = utils_2.shuffle(this.connectionPool.getNodes()); + let lastNodeError = null; + function tryNode(index) { + if (index === nodes.length) { + const error = new ClusterAllFailedError_1.default("Failed to refresh slots cache.", lastNodeError); + return wrapper(error); } - } - }, - - _typeMatches: function(actual, expected, argValue) { - if (expected === TYPE_ANY) { - return true; - } - if (expected === TYPE_ARRAY_STRING || - expected === TYPE_ARRAY_NUMBER || - expected === TYPE_ARRAY) { - // The expected type can either just be array, - // or it can require a specific subtype (array of numbers). - // - // The simplest case is if "array" with no subtype is specified. - if (expected === TYPE_ARRAY) { - return actual === TYPE_ARRAY; - } else if (actual === TYPE_ARRAY) { - // Otherwise we need to check subtypes. - // I think this has potential to be improved. - var subtype; - if (expected === TYPE_ARRAY_NUMBER) { - subtype = TYPE_NUMBER; - } else if (expected === TYPE_ARRAY_STRING) { - subtype = TYPE_STRING; + const node = nodes[index]; + const key = `${node.options.host}:${node.options.port}`; + debug("getting slot cache from %s", key); + _this.getInfoFromNode(node, function (err) { + switch (_this.status) { + case "close": + case "end": + return wrapper(new Error("Cluster is disconnected.")); + case "disconnecting": + return wrapper(new Error("Cluster is disconnecting.")); } - for (var i = 0; i < argValue.length; i++) { - if (!this._typeMatches( - this._getTypeName(argValue[i]), subtype, - argValue[i])) { - return false; - } + if (err) { + _this.emit("node error", err, key); + lastNodeError = err; + tryNode(index + 1); } - return true; - } - } else { - return actual === expected; + else { + _this.emit("refresh"); + wrapper(); + } + }); } - }, - _getTypeName: function(obj) { - switch (Object.prototype.toString.call(obj)) { - case "[object String]": - return TYPE_STRING; - case "[object Number]": - return TYPE_NUMBER; - case "[object Array]": - return TYPE_ARRAY; - case "[object Boolean]": - return TYPE_BOOLEAN; - case "[object Null]": - return TYPE_NULL; - case "[object Object]": - // Check if it's an expref. If it has, it's been - // tagged with a jmespathType attr of 'Expref'; - if (obj.jmespathType === TOK_EXPREF) { - return TYPE_EXPREF; - } else { - return TYPE_OBJECT; - } + tryNode(0); + } + /** + * Flush offline queue with error. + * + * @param {Error} error + * @memberof Cluster + */ + flushQueue(error) { + let item; + while (this.offlineQueue.length > 0) { + item = this.offlineQueue.shift(); + item.command.reject(error); } - }, - - _functionStartsWith: function(resolvedArgs) { - return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; - }, - - _functionEndsWith: function(resolvedArgs) { - var searchStr = resolvedArgs[0]; - var suffix = resolvedArgs[1]; - return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; - }, - - _functionReverse: function(resolvedArgs) { - var typeName = this._getTypeName(resolvedArgs[0]); - if (typeName === TYPE_STRING) { - var originalStr = resolvedArgs[0]; - var reversedStr = ""; - for (var i = originalStr.length - 1; i >= 0; i--) { - reversedStr += originalStr[i]; - } - return reversedStr; - } else { - var reversedArray = resolvedArgs[0].slice(0); - reversedArray.reverse(); - return reversedArray; + } + executeOfflineCommands() { + if (this.offlineQueue.length) { + debug("send %d commands in offline queue", this.offlineQueue.length); + const offlineQueue = this.offlineQueue; + this.resetOfflineQueue(); + while (offlineQueue.length > 0) { + const item = offlineQueue.shift(); + this.sendCommand(item.command, item.stream, item.node); + } } - }, - - _functionAbs: function(resolvedArgs) { - return Math.abs(resolvedArgs[0]); - }, - - _functionCeil: function(resolvedArgs) { - return Math.ceil(resolvedArgs[0]); - }, - - _functionAvg: function(resolvedArgs) { - var sum = 0; - var inputArray = resolvedArgs[0]; - for (var i = 0; i < inputArray.length; i++) { - sum += inputArray[i]; + } + natMapper(nodeKey) { + if (this.options.natMap && typeof this.options.natMap === "object") { + const key = typeof nodeKey === "string" + ? nodeKey + : `${nodeKey.host}:${nodeKey.port}`; + const mapped = this.options.natMap[key]; + if (mapped) { + debug("NAT mapping %s -> %O", key, mapped); + return Object.assign({}, mapped); + } } - return sum / inputArray.length; - }, - - _functionContains: function(resolvedArgs) { - return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; - }, - - _functionFloor: function(resolvedArgs) { - return Math.floor(resolvedArgs[0]); - }, - - _functionLength: function(resolvedArgs) { - if (!isObject(resolvedArgs[0])) { - return resolvedArgs[0].length; - } else { - // As far as I can tell, there's no way to get the length - // of an object without O(n) iteration through the object. - return Object.keys(resolvedArgs[0]).length; - } - }, - - _functionMap: function(resolvedArgs) { - var mapped = []; - var interpreter = this._interpreter; - var exprefNode = resolvedArgs[0]; - var elements = resolvedArgs[1]; - for (var i = 0; i < elements.length; i++) { - mapped.push(interpreter.visit(exprefNode, elements[i])); - } - return mapped; - }, - - _functionMerge: function(resolvedArgs) { - var merged = {}; - for (var i = 0; i < resolvedArgs.length; i++) { - var current = resolvedArgs[i]; - for (var key in current) { - merged[key] = current[key]; + return typeof nodeKey === "string" + ? util_1.nodeKeyToRedisOptions(nodeKey) + : nodeKey; + } + sendCommand(command, stream, node) { + if (this.status === "wait") { + this.connect().catch(utils_1.noop); } - } - return merged; - }, - - _functionMax: function(resolvedArgs) { - if (resolvedArgs[0].length > 0) { - var typeName = this._getTypeName(resolvedArgs[0][0]); - if (typeName === TYPE_NUMBER) { - return Math.max.apply(Math, resolvedArgs[0]); - } else { - var elements = resolvedArgs[0]; - var maxElement = elements[0]; - for (var i = 1; i < elements.length; i++) { - if (maxElement.localeCompare(elements[i]) < 0) { - maxElement = elements[i]; - } - } - return maxElement; + if (this.status === "end") { + command.reject(new Error(utils_2.CONNECTION_CLOSED_ERROR_MSG)); + return command.promise; } - } else { - return null; - } - }, - - _functionMin: function(resolvedArgs) { - if (resolvedArgs[0].length > 0) { - var typeName = this._getTypeName(resolvedArgs[0][0]); - if (typeName === TYPE_NUMBER) { - return Math.min.apply(Math, resolvedArgs[0]); - } else { - var elements = resolvedArgs[0]; - var minElement = elements[0]; - for (var i = 1; i < elements.length; i++) { - if (elements[i].localeCompare(minElement) < 0) { - minElement = elements[i]; - } - } - return minElement; + let to = this.options.scaleReads; + if (to !== "master") { + const isCommandReadOnly = command.isReadOnly || + (commands.exists(command.name) && + commands.hasFlag(command.name, "readonly")); + if (!isCommandReadOnly) { + to = "master"; + } } - } else { - return null; - } - }, - - _functionSum: function(resolvedArgs) { - var sum = 0; - var listToSum = resolvedArgs[0]; - for (var i = 0; i < listToSum.length; i++) { - sum += listToSum[i]; - } - return sum; - }, - - _functionType: function(resolvedArgs) { - switch (this._getTypeName(resolvedArgs[0])) { - case TYPE_NUMBER: - return "number"; - case TYPE_STRING: - return "string"; - case TYPE_ARRAY: - return "array"; - case TYPE_OBJECT: - return "object"; - case TYPE_BOOLEAN: - return "boolean"; - case TYPE_EXPREF: - return "expref"; - case TYPE_NULL: - return "null"; + let targetSlot = node ? node.slot : command.getSlot(); + const ttl = {}; + const _this = this; + if (!node && !command.__is_reject_overwritten) { + // eslint-disable-next-line @typescript-eslint/camelcase + command.__is_reject_overwritten = true; + const reject = command.reject; + command.reject = function (err) { + const partialTry = tryConnection.bind(null, true); + _this.handleError(err, ttl, { + moved: function (slot, key) { + debug("command %s is moved to %s", command.name, key); + targetSlot = Number(slot); + if (_this.slots[slot]) { + _this.slots[slot][0] = key; + } + else { + _this.slots[slot] = [key]; + } + _this._groupsBySlot[slot] = _this._groupsIds[_this.slots[slot].join(';')]; + _this.connectionPool.findOrCreate(_this.natMapper(key)); + tryConnection(); + debug("refreshing slot caches... (triggered by MOVED error)"); + _this.refreshSlotsCache(); + }, + ask: function (slot, key) { + debug("command %s is required to ask %s:%s", command.name, key); + const mapped = _this.natMapper(key); + _this.connectionPool.findOrCreate(mapped); + tryConnection(false, `${mapped.host}:${mapped.port}`); + }, + tryagain: partialTry, + clusterDown: partialTry, + connectionClosed: partialTry, + maxRedirections: function (redirectionError) { + reject.call(command, redirectionError); + }, + defaults: function () { + reject.call(command, err); + }, + }); + }; } - }, - - _functionKeys: function(resolvedArgs) { - return Object.keys(resolvedArgs[0]); - }, - - _functionValues: function(resolvedArgs) { - var obj = resolvedArgs[0]; - var keys = Object.keys(obj); - var values = []; - for (var i = 0; i < keys.length; i++) { - values.push(obj[keys[i]]); + tryConnection(); + function tryConnection(random, asking) { + if (_this.status === "end") { + command.reject(new redis_errors_1.AbortError("Cluster is ended.")); + return; + } + let redis; + if (_this.status === "ready" || command.name === "cluster") { + if (node && node.redis) { + redis = node.redis; + } + else if (command_1.default.checkFlag("ENTER_SUBSCRIBER_MODE", command.name) || + command_1.default.checkFlag("EXIT_SUBSCRIBER_MODE", command.name)) { + redis = _this.subscriber.getInstance(); + if (!redis) { + command.reject(new redis_errors_1.AbortError("No subscriber for the cluster")); + return; + } + } + else { + if (!random) { + if (typeof targetSlot === "number" && _this.slots[targetSlot]) { + const nodeKeys = _this.slots[targetSlot]; + if (typeof to === "function") { + const nodes = nodeKeys.map(function (key) { + return _this.connectionPool.getInstanceByKey(key); + }); + redis = to(nodes, command); + if (Array.isArray(redis)) { + redis = utils_2.sample(redis); + } + if (!redis) { + redis = nodes[0]; + } + } + else { + let key; + if (to === "all") { + key = utils_2.sample(nodeKeys); + } + else if (to === "slave" && nodeKeys.length > 1) { + key = utils_2.sample(nodeKeys, 1); + } + else { + key = nodeKeys[0]; + } + redis = _this.connectionPool.getInstanceByKey(key); + } + } + if (asking) { + redis = _this.connectionPool.getInstanceByKey(asking); + redis.asking(); + } + } + if (!redis) { + redis = + (typeof to === "function" + ? null + : _this.connectionPool.getSampleInstance(to)) || + _this.connectionPool.getSampleInstance("all"); + } + } + if (node && !node.redis) { + node.redis = redis; + } + } + if (redis) { + redis.sendCommand(command, stream); + } + else if (_this.options.enableOfflineQueue) { + _this.offlineQueue.push({ + command: command, + stream: stream, + node: node, + }); + } + else { + command.reject(new Error("Cluster isn't ready and enableOfflineQueue options is false")); + } } - return values; - }, - - _functionJoin: function(resolvedArgs) { - var joinChar = resolvedArgs[0]; - var listJoin = resolvedArgs[1]; - return listJoin.join(joinChar); - }, - - _functionToArray: function(resolvedArgs) { - if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { - return resolvedArgs[0]; - } else { - return [resolvedArgs[0]]; + return command.promise; + } + handleError(error, ttl, handlers) { + if (typeof ttl.value === "undefined") { + ttl.value = this.options.maxRedirections; } - }, - - _functionToString: function(resolvedArgs) { - if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { - return resolvedArgs[0]; - } else { - return JSON.stringify(resolvedArgs[0]); + else { + ttl.value -= 1; } - }, - - _functionToNumber: function(resolvedArgs) { - var typeName = this._getTypeName(resolvedArgs[0]); - var convertedValue; - if (typeName === TYPE_NUMBER) { - return resolvedArgs[0]; - } else if (typeName === TYPE_STRING) { - convertedValue = +resolvedArgs[0]; - if (!isNaN(convertedValue)) { - return convertedValue; - } + if (ttl.value <= 0) { + handlers.maxRedirections(new Error("Too many Cluster redirections. Last error: " + error)); + return; } - return null; - }, - - _functionNotNull: function(resolvedArgs) { - for (var i = 0; i < resolvedArgs.length; i++) { - if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { - return resolvedArgs[i]; + const errv = error.message.split(" "); + if (errv[0] === "MOVED") { + const timeout = this.options.retryDelayOnMoved; + if (timeout && typeof timeout === "number") { + this.delayQueue.push("moved", handlers.moved.bind(null, errv[1], errv[2]), { timeout }); + } + else { + handlers.moved(errv[1], errv[2]); } } - return null; - }, - - _functionSort: function(resolvedArgs) { - var sortedArray = resolvedArgs[0].slice(0); - sortedArray.sort(); - return sortedArray; - }, - - _functionSortBy: function(resolvedArgs) { - var sortedArray = resolvedArgs[0].slice(0); - if (sortedArray.length === 0) { - return sortedArray; + else if (errv[0] === "ASK") { + handlers.ask(errv[1], errv[2]); } - var interpreter = this._interpreter; - var exprefNode = resolvedArgs[1]; - var requiredType = this._getTypeName( - interpreter.visit(exprefNode, sortedArray[0])); - if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) { - throw new Error("TypeError"); + else if (errv[0] === "TRYAGAIN") { + this.delayQueue.push("tryagain", handlers.tryagain, { + timeout: this.options.retryDelayOnTryAgain, + }); } - var that = this; - // In order to get a stable sort out of an unstable - // sort algorithm, we decorate/sort/undecorate (DSU) - // by creating a new list of [index, element] pairs. - // In the cmp function, if the evaluated elements are - // equal, then the index will be used as the tiebreaker. - // After the decorated list has been sorted, it will be - // undecorated to extract the original elements. - var decorated = []; - for (var i = 0; i < sortedArray.length; i++) { - decorated.push([i, sortedArray[i]]); + else if (errv[0] === "CLUSTERDOWN" && + this.options.retryDelayOnClusterDown > 0) { + this.delayQueue.push("clusterdown", handlers.connectionClosed, { + timeout: this.options.retryDelayOnClusterDown, + callback: this.refreshSlotsCache.bind(this), + }); } - decorated.sort(function(a, b) { - var exprA = interpreter.visit(exprefNode, a[1]); - var exprB = interpreter.visit(exprefNode, b[1]); - if (that._getTypeName(exprA) !== requiredType) { - throw new Error( - "TypeError: expected " + requiredType + ", received " + - that._getTypeName(exprA)); - } else if (that._getTypeName(exprB) !== requiredType) { - throw new Error( - "TypeError: expected " + requiredType + ", received " + - that._getTypeName(exprB)); - } - if (exprA > exprB) { - return 1; - } else if (exprA < exprB) { - return -1; - } else { - // If they're equal compare the items by their - // order to maintain relative order of equal keys - // (i.e. to get a stable sort). - return a[0] - b[0]; - } - }); - // Undecorate: extract out the original list elements. - for (var j = 0; j < decorated.length; j++) { - sortedArray[j] = decorated[j][1]; + else if (error.message === utils_2.CONNECTION_CLOSED_ERROR_MSG && + this.options.retryDelayOnFailover > 0 && + this.status === "ready") { + this.delayQueue.push("failover", handlers.connectionClosed, { + timeout: this.options.retryDelayOnFailover, + callback: this.refreshSlotsCache.bind(this), + }); } - return sortedArray; - }, - - _functionMaxBy: function(resolvedArgs) { - var exprefNode = resolvedArgs[1]; - var resolvedArray = resolvedArgs[0]; - var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); - var maxNumber = -Infinity; - var maxRecord; - var current; - for (var i = 0; i < resolvedArray.length; i++) { - current = keyFunction(resolvedArray[i]); - if (current > maxNumber) { - maxNumber = current; - maxRecord = resolvedArray[i]; + else { + handlers.defaults(); } - } - return maxRecord; - }, - - _functionMinBy: function(resolvedArgs) { - var exprefNode = resolvedArgs[1]; - var resolvedArray = resolvedArgs[0]; - var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); - var minNumber = Infinity; - var minRecord; - var current; - for (var i = 0; i < resolvedArray.length; i++) { - current = keyFunction(resolvedArray[i]); - if (current < minNumber) { - minNumber = current; - minRecord = resolvedArray[i]; + } + getInfoFromNode(redis, callback) { + if (!redis) { + return callback(new Error("Node is disconnected")); } - } - return minRecord; - }, - - createKeyFunction: function(exprefNode, allowedTypes) { - var that = this; - var interpreter = this._interpreter; - var keyFunc = function(x) { - var current = interpreter.visit(exprefNode, x); - if (allowedTypes.indexOf(that._getTypeName(current)) < 0) { - var msg = "TypeError: expected one of " + allowedTypes + - ", received " + that._getTypeName(current); - throw new Error(msg); + // Use a duplication of the connection to avoid + // timeouts when the connection is in the blocking + // mode (e.g. waiting for BLPOP). + const duplicatedConnection = redis.duplicate({ + enableOfflineQueue: true, + enableReadyCheck: false, + retryStrategy: null, + connectionName: util_1.getConnectionName("refresher", this.options.redisOptions && this.options.redisOptions.connectionName), + }); + // Ignore error events since we will handle + // exceptions for the CLUSTER SLOTS command. + duplicatedConnection.on("error", utils_1.noop); + duplicatedConnection.cluster("slots", utils_2.timeout((err, result) => { + duplicatedConnection.disconnect(); + if (err) { + return callback(err); + } + if (this.status === "disconnecting" || + this.status === "close" || + this.status === "end") { + debug("ignore CLUSTER.SLOTS results (count: %d) since cluster status is %s", result.length, this.status); + callback(); + return; + } + const nodes = []; + debug("cluster slots result count: %d", result.length); + for (let i = 0; i < result.length; ++i) { + const items = result[i]; + const slotRangeStart = items[0]; + const slotRangeEnd = items[1]; + const keys = []; + for (let j = 2; j < items.length; j++) { + if (!items[j][0]) { + continue; + } + items[j] = this.natMapper({ host: items[j][0], port: items[j][1] }); + items[j].readOnly = j !== 2; + nodes.push(items[j]); + keys.push(items[j].host + ":" + items[j].port); + } + debug("cluster slots result [%d]: slots %d~%d served by %s", i, slotRangeStart, slotRangeEnd, keys); + for (let slot = slotRangeStart; slot <= slotRangeEnd; slot++) { + this.slots[slot] = keys; + } + } + // Assign to each node keys a numeric value to make autopipeline comparison faster. + this._groupsIds = Object.create(null); + let j = 0; + for (let i = 0; i < 16384; i++) { + const target = (this.slots[i] || []).join(';'); + if (!target.length) { + this._groupsBySlot[i] = undefined; + continue; + } + if (!this._groupsIds[target]) { + this._groupsIds[target] = ++j; + } + this._groupsBySlot[i] = this._groupsIds[target]; + } + this.connectionPool.reset(nodes); + callback(); + }, this.options.slotsRefreshTimeout)); + } + invokeReadyDelayedCallbacks(err) { + for (const c of this._readyDelayedCallbacks) { + process.nextTick(c, err); } - return current; - }; - return keyFunc; + this._readyDelayedCallbacks = []; } - - }; - - function compile(stream) { - var parser = new Parser(); - var ast = parser.parse(stream); - return ast; - } - - function tokenize(stream) { - var lexer = new Lexer(); - return lexer.tokenize(stream); - } - - function search(data, expression) { - var parser = new Parser(); - // This needs to be improved. Both the interpreter and runtime depend on - // each other. The runtime needs the interpreter to support exprefs. - // There's likely a clean way to avoid the cyclic dependency. - var runtime = new Runtime(); - var interpreter = new TreeInterpreter(runtime); - runtime._interpreter = interpreter; - var node = parser.parse(expression); - return interpreter.search(node, data); - } - - exports.tokenize = tokenize; - exports.compile = compile; - exports.search = search; - exports.strictDeepEqual = strictDeepEqual; -})( false ? 0 : exports); - - -/***/ }), - -/***/ 21917: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - - -var yaml = __nccwpck_require__(40916); - - -module.exports = yaml; - - -/***/ }), - -/***/ 40916: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - - -var loader = __nccwpck_require__(45190); -var dumper = __nccwpck_require__(73034); - - -function deprecated(name) { - return function () { - throw new Error('Function ' + name + ' is deprecated and cannot be used.'); - }; -} - - -module.exports.Type = __nccwpck_require__(30967); -module.exports.Schema = __nccwpck_require__(66514); -module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(66037); -module.exports.JSON_SCHEMA = __nccwpck_require__(1571); -module.exports.CORE_SCHEMA = __nccwpck_require__(92183); -module.exports.DEFAULT_SAFE_SCHEMA = __nccwpck_require__(48949); -module.exports.DEFAULT_FULL_SCHEMA = __nccwpck_require__(56874); -module.exports.load = loader.load; -module.exports.loadAll = loader.loadAll; -module.exports.safeLoad = loader.safeLoad; -module.exports.safeLoadAll = loader.safeLoadAll; -module.exports.dump = dumper.dump; -module.exports.safeDump = dumper.safeDump; -module.exports.YAMLException = __nccwpck_require__(65199); - -// Deprecated schema names from JS-YAML 2.0.x -module.exports.MINIMAL_SCHEMA = __nccwpck_require__(66037); -module.exports.SAFE_SCHEMA = __nccwpck_require__(48949); -module.exports.DEFAULT_SCHEMA = __nccwpck_require__(56874); - -// Deprecated functions from JS-YAML 1.x.x -module.exports.scan = deprecated('scan'); -module.exports.parse = deprecated('parse'); -module.exports.compose = deprecated('compose'); -module.exports.addConstructor = deprecated('addConstructor'); - - -/***/ }), - -/***/ 59136: -/***/ ((module) => { - -"use strict"; - - - -function isNothing(subject) { - return (typeof subject === 'undefined') || (subject === null); -} - - -function isObject(subject) { - return (typeof subject === 'object') && (subject !== null); -} - - -function toArray(sequence) { - if (Array.isArray(sequence)) return sequence; - else if (isNothing(sequence)) return []; - - return [ sequence ]; -} - - -function extend(target, source) { - var index, length, key, sourceKeys; - - if (source) { - sourceKeys = Object.keys(source); - - for (index = 0, length = sourceKeys.length; index < length; index += 1) { - key = sourceKeys[index]; - target[key] = source[key]; + /** + * Check whether Cluster is able to process commands + * + * @param {Function} callback + * @private + */ + readyCheck(callback) { + this.cluster("info", function (err, res) { + if (err) { + return callback(err); + } + if (typeof res !== "string") { + return callback(); + } + let state; + const lines = res.split("\r\n"); + for (let i = 0; i < lines.length; ++i) { + const parts = lines[i].split(":"); + if (parts[0] === "cluster_state") { + state = parts[1]; + break; + } + } + if (state === "fail") { + debug("cluster state not ok (%s)", state); + callback(null, state); + } + else { + callback(); + } + }); } - } - - return target; -} - - -function repeat(string, count) { - var result = '', cycle; - - for (cycle = 0; cycle < count; cycle += 1) { - result += string; - } - - return result; -} - - -function isNegativeZero(number) { - return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); -} - - -module.exports.isNothing = isNothing; -module.exports.isObject = isObject; -module.exports.toArray = toArray; -module.exports.repeat = repeat; -module.exports.isNegativeZero = isNegativeZero; -module.exports.extend = extend; - - -/***/ }), - -/***/ 73034: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -/*eslint-disable no-use-before-define*/ - -var common = __nccwpck_require__(59136); -var YAMLException = __nccwpck_require__(65199); -var DEFAULT_FULL_SCHEMA = __nccwpck_require__(56874); -var DEFAULT_SAFE_SCHEMA = __nccwpck_require__(48949); - -var _toString = Object.prototype.toString; -var _hasOwnProperty = Object.prototype.hasOwnProperty; - -var CHAR_TAB = 0x09; /* Tab */ -var CHAR_LINE_FEED = 0x0A; /* LF */ -var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ -var CHAR_SPACE = 0x20; /* Space */ -var CHAR_EXCLAMATION = 0x21; /* ! */ -var CHAR_DOUBLE_QUOTE = 0x22; /* " */ -var CHAR_SHARP = 0x23; /* # */ -var CHAR_PERCENT = 0x25; /* % */ -var CHAR_AMPERSAND = 0x26; /* & */ -var CHAR_SINGLE_QUOTE = 0x27; /* ' */ -var CHAR_ASTERISK = 0x2A; /* * */ -var CHAR_COMMA = 0x2C; /* , */ -var CHAR_MINUS = 0x2D; /* - */ -var CHAR_COLON = 0x3A; /* : */ -var CHAR_EQUALS = 0x3D; /* = */ -var CHAR_GREATER_THAN = 0x3E; /* > */ -var CHAR_QUESTION = 0x3F; /* ? */ -var CHAR_COMMERCIAL_AT = 0x40; /* @ */ -var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ -var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ -var CHAR_GRAVE_ACCENT = 0x60; /* ` */ -var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ -var CHAR_VERTICAL_LINE = 0x7C; /* | */ -var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ - -var ESCAPE_SEQUENCES = {}; - -ESCAPE_SEQUENCES[0x00] = '\\0'; -ESCAPE_SEQUENCES[0x07] = '\\a'; -ESCAPE_SEQUENCES[0x08] = '\\b'; -ESCAPE_SEQUENCES[0x09] = '\\t'; -ESCAPE_SEQUENCES[0x0A] = '\\n'; -ESCAPE_SEQUENCES[0x0B] = '\\v'; -ESCAPE_SEQUENCES[0x0C] = '\\f'; -ESCAPE_SEQUENCES[0x0D] = '\\r'; -ESCAPE_SEQUENCES[0x1B] = '\\e'; -ESCAPE_SEQUENCES[0x22] = '\\"'; -ESCAPE_SEQUENCES[0x5C] = '\\\\'; -ESCAPE_SEQUENCES[0x85] = '\\N'; -ESCAPE_SEQUENCES[0xA0] = '\\_'; -ESCAPE_SEQUENCES[0x2028] = '\\L'; -ESCAPE_SEQUENCES[0x2029] = '\\P'; - -var DEPRECATED_BOOLEANS_SYNTAX = [ - 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', - 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' -]; - -function compileStyleMap(schema, map) { - var result, keys, index, length, tag, style, type; - - if (map === null) return {}; - - result = {}; - keys = Object.keys(map); - - for (index = 0, length = keys.length; index < length; index += 1) { - tag = keys[index]; - style = String(map[tag]); - - if (tag.slice(0, 2) === '!!') { - tag = 'tag:yaml.org,2002:' + tag.slice(2); + resolveSrv(hostname) { + return new Promise((resolve, reject) => { + this.options.resolveSrv(hostname, (err, records) => { + if (err) { + return reject(err); + } + const self = this, groupedRecords = util_1.groupSrvRecords(records), sortedKeys = Object.keys(groupedRecords).sort((a, b) => parseInt(a) - parseInt(b)); + function tryFirstOne(err) { + if (!sortedKeys.length) { + return reject(err); + } + const key = sortedKeys[0], group = groupedRecords[key], record = util_1.weightSrvRecords(group); + if (!group.records.length) { + sortedKeys.shift(); + } + self.dnsLookup(record.name).then((host) => resolve({ + host, + port: record.port, + }), tryFirstOne); + } + tryFirstOne(); + }); + }); } - type = schema.compiledTypeMap['fallback'][tag]; - - if (type && _hasOwnProperty.call(type.styleAliases, style)) { - style = type.styleAliases[style]; + dnsLookup(hostname) { + return new Promise((resolve, reject) => { + this.options.dnsLookup(hostname, (err, address) => { + if (err) { + debug("failed to resolve hostname %s to IP: %s", hostname, err.message); + reject(err); + } + else { + debug("resolved hostname %s to IP %s", hostname, address); + resolve(address); + } + }); + }); + } + /** + * Normalize startup nodes, and resolving hostnames to IPs. + * + * This process happens every time when #connect() is called since + * #startupNodes and DNS records may chanage. + * + * @private + * @returns {Promise} + */ + resolveStartupNodeHostnames() { + if (!Array.isArray(this.startupNodes) || this.startupNodes.length === 0) { + return Promise.reject(new Error("`startupNodes` should contain at least one node.")); + } + const startupNodes = util_1.normalizeNodeOptions(this.startupNodes); + const hostnames = util_1.getUniqueHostnamesFromOptions(startupNodes); + if (hostnames.length === 0) { + return Promise.resolve(startupNodes); + } + return Promise.all(hostnames.map((this.options.useSRVRecords ? this.resolveSrv : this.dnsLookup).bind(this))).then((configs) => { + const hostnameToConfig = utils_2.zipMap(hostnames, configs); + return startupNodes.map((node) => { + const config = hostnameToConfig.get(node.host); + if (!config) { + return node; + } + else if (this.options.useSRVRecords) { + return Object.assign({}, node, config); + } + else { + return Object.assign({}, node, { host: config }); + } + }); + }); } - - result[tag] = style; - } - - return result; } +Object.getOwnPropertyNames(commander_1.default.prototype).forEach((name) => { + if (!Cluster.prototype.hasOwnProperty(name)) { + Cluster.prototype[name] = commander_1.default.prototype[name]; + } +}); +const scanCommands = [ + "sscan", + "hscan", + "zscan", + "sscanBuffer", + "hscanBuffer", + "zscanBuffer", +]; +scanCommands.forEach((command) => { + Cluster.prototype[command + "Stream"] = function (key, options) { + return new ScanStream_1.default(utils_1.defaults({ + objectMode: true, + key: key, + redis: this, + command: command, + }, options)); + }; +}); +__nccwpck_require__(14645).addTransactionSupport(Cluster.prototype); +exports.default = Cluster; -function encodeHex(character) { - var string, handle, length; - - string = character.toString(16).toUpperCase(); - - if (character <= 0xFF) { - handle = 'x'; - length = 2; - } else if (character <= 0xFFFF) { - handle = 'u'; - length = 4; - } else if (character <= 0xFFFFFFFF) { - handle = 'U'; - length = 8; - } else { - throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); - } - - return '\\' + handle + common.repeat('0', length - string.length) + string; -} -function State(options) { - this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; - this.indent = Math.max(1, (options['indent'] || 2)); - this.noArrayIndent = options['noArrayIndent'] || false; - this.skipInvalid = options['skipInvalid'] || false; - this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); - this.styleMap = compileStyleMap(this.schema, options['styles'] || null); - this.sortKeys = options['sortKeys'] || false; - this.lineWidth = options['lineWidth'] || 80; - this.noRefs = options['noRefs'] || false; - this.noCompatMode = options['noCompatMode'] || false; - this.condenseFlow = options['condenseFlow'] || false; +/***/ }), - this.implicitTypes = this.schema.compiledImplicit; - this.explicitTypes = this.schema.compiledExplicit; +/***/ 94582: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - this.tag = null; - this.result = ''; +"use strict"; - this.duplicates = []; - this.usedDuplicates = null; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils_1 = __nccwpck_require__(94832); +const net_1 = __nccwpck_require__(11631); +function getNodeKey(node) { + node.port = node.port || 6379; + node.host = node.host || "127.0.0.1"; + return node.host + ":" + node.port; } - -// Indents every line in a string. Empty lines (\n only) are not indented. -function indentString(string, spaces) { - var ind = common.repeat(' ', spaces), - position = 0, - next = -1, - result = '', - line, - length = string.length; - - while (position < length) { - next = string.indexOf('\n', position); - if (next === -1) { - line = string.slice(position); - position = length; - } else { - line = string.slice(position, next + 1); - position = next + 1; +exports.getNodeKey = getNodeKey; +function nodeKeyToRedisOptions(nodeKey) { + const portIndex = nodeKey.lastIndexOf(":"); + if (portIndex === -1) { + throw new Error(`Invalid node key ${nodeKey}`); } - - if (line.length && line !== '\n') result += ind; - - result += line; - } - - return result; -} - -function generateNextLine(state, level) { - return '\n' + common.repeat(' ', state.indent * level); + return { + host: nodeKey.slice(0, portIndex), + port: Number(nodeKey.slice(portIndex + 1)), + }; } - -function testImplicitResolving(state, str) { - var index, length, type; - - for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { - type = state.implicitTypes[index]; - - if (type.resolve(str)) { - return true; - } - } - - return false; +exports.nodeKeyToRedisOptions = nodeKeyToRedisOptions; +function normalizeNodeOptions(nodes) { + return nodes.map((node) => { + const options = {}; + if (typeof node === "object") { + Object.assign(options, node); + } + else if (typeof node === "string") { + Object.assign(options, utils_1.parseURL(node)); + } + else if (typeof node === "number") { + options.port = node; + } + else { + throw new Error("Invalid argument " + node); + } + if (typeof options.port === "string") { + options.port = parseInt(options.port, 10); + } + // Cluster mode only support db 0 + delete options.db; + if (!options.port) { + options.port = 6379; + } + if (!options.host) { + options.host = "127.0.0.1"; + } + return options; + }); } - -// [33] s-white ::= s-space | s-tab -function isWhitespace(c) { - return c === CHAR_SPACE || c === CHAR_TAB; +exports.normalizeNodeOptions = normalizeNodeOptions; +function getUniqueHostnamesFromOptions(nodes) { + const uniqueHostsMap = {}; + nodes.forEach((node) => { + uniqueHostsMap[node.host] = true; + }); + return Object.keys(uniqueHostsMap).filter((host) => !net_1.isIP(host)); } - -// Returns true if the character can be printed without escaping. -// From YAML 1.2: "any allowed characters known to be non-printable -// should also be escaped. [However,] This isn’t mandatory" -// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. -function isPrintable(c) { - return (0x00020 <= c && c <= 0x00007E) - || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) - || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) - || (0x10000 <= c && c <= 0x10FFFF); +exports.getUniqueHostnamesFromOptions = getUniqueHostnamesFromOptions; +function groupSrvRecords(records) { + const recordsByPriority = {}; + for (const record of records) { + if (!recordsByPriority.hasOwnProperty(record.priority)) { + recordsByPriority[record.priority] = { + totalWeight: record.weight, + records: [record], + }; + } + else { + recordsByPriority[record.priority].totalWeight += record.weight; + recordsByPriority[record.priority].records.push(record); + } + } + return recordsByPriority; } - -// [34] ns-char ::= nb-char - s-white -// [27] nb-char ::= c-printable - b-char - c-byte-order-mark -// [26] b-char ::= b-line-feed | b-carriage-return -// [24] b-line-feed ::= #xA /* LF */ -// [25] b-carriage-return ::= #xD /* CR */ -// [3] c-byte-order-mark ::= #xFEFF -function isNsChar(c) { - return isPrintable(c) && !isWhitespace(c) - // byte-order-mark - && c !== 0xFEFF - // b-char - && c !== CHAR_CARRIAGE_RETURN - && c !== CHAR_LINE_FEED; +exports.groupSrvRecords = groupSrvRecords; +function weightSrvRecords(recordsGroup) { + if (recordsGroup.records.length === 1) { + recordsGroup.totalWeight = 0; + return recordsGroup.records.shift(); + } + // + `recordsGroup.records.length` to support `weight` 0 + const random = Math.floor(Math.random() * (recordsGroup.totalWeight + recordsGroup.records.length)); + let total = 0; + for (const [i, record] of recordsGroup.records.entries()) { + total += 1 + record.weight; + if (total > random) { + recordsGroup.totalWeight -= record.weight; + recordsGroup.records.splice(i, 1); + return record; + } + } } - -// Simplified test for values allowed after the first character in plain style. -function isPlainSafe(c, prev) { - // Uses a subset of nb-char - c-flow-indicator - ":" - "#" - // where nb-char ::= c-printable - b-char - c-byte-order-mark. - return isPrintable(c) && c !== 0xFEFF - // - c-flow-indicator - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // - ":" - "#" - // /* An ns-char preceding */ "#" - && c !== CHAR_COLON - && ((c !== CHAR_SHARP) || (prev && isNsChar(prev))); +exports.weightSrvRecords = weightSrvRecords; +function getConnectionName(component, nodeConnectionName) { + const prefix = `ioredis-cluster(${component})`; + return nodeConnectionName ? `${prefix}:${nodeConnectionName}` : prefix; } +exports.getConnectionName = getConnectionName; -// Simplified test for values allowed as the first character in plain style. -function isPlainSafeFirst(c) { - // Uses a subset of ns-char - c-indicator - // where ns-char = nb-char - s-white. - return isPrintable(c) && c !== 0xFEFF - && !isWhitespace(c) // - s-white - // - (c-indicator ::= - // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” - && c !== CHAR_MINUS - && c !== CHAR_QUESTION - && c !== CHAR_COLON - && c !== CHAR_COMMA - && c !== CHAR_LEFT_SQUARE_BRACKET - && c !== CHAR_RIGHT_SQUARE_BRACKET - && c !== CHAR_LEFT_CURLY_BRACKET - && c !== CHAR_RIGHT_CURLY_BRACKET - // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” - && c !== CHAR_SHARP - && c !== CHAR_AMPERSAND - && c !== CHAR_ASTERISK - && c !== CHAR_EXCLAMATION - && c !== CHAR_VERTICAL_LINE - && c !== CHAR_EQUALS - && c !== CHAR_GREATER_THAN - && c !== CHAR_SINGLE_QUOTE - && c !== CHAR_DOUBLE_QUOTE - // | “%” | “@” | “`”) - && c !== CHAR_PERCENT - && c !== CHAR_COMMERCIAL_AT - && c !== CHAR_GRAVE_ACCENT; -} -// Determines whether block indentation indicator is required. -function needIndentIndicator(string) { - var leadingSpaceRe = /^\n* /; - return leadingSpaceRe.test(string); -} +/***/ }), -var STYLE_PLAIN = 1, - STYLE_SINGLE = 2, - STYLE_LITERAL = 3, - STYLE_FOLDED = 4, - STYLE_DOUBLE = 5; +/***/ 90803: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -// Determines which scalar styles are possible and returns the preferred style. -// lineWidth = -1 => no limit. -// Pre-conditions: str.length > 0. -// Post-conditions: -// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. -// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). -// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). -function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { - var i; - var char, prev_char; - var hasLineBreak = false; - var hasFoldableLine = false; // only checked if shouldTrackWidth - var shouldTrackWidth = lineWidth !== -1; - var previousLineBreak = -1; // count the first line correctly - var plain = isPlainSafeFirst(string.charCodeAt(0)) - && !isWhitespace(string.charCodeAt(string.length - 1)); +"use strict"; - if (singleLineOnly) { - // Case: no block styles. - // Check for disallowed characters to rule out plain and single. - for (i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - prev_char = i > 0 ? string.charCodeAt(i - 1) : null; - plain = plain && isPlainSafe(char, prev_char); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const commands = __nccwpck_require__(98020); +const calculateSlot = __nccwpck_require__(48481); +const standard_as_callback_1 = __nccwpck_require__(91543); +const utils_1 = __nccwpck_require__(94832); +const lodash_1 = __nccwpck_require__(20961); +const promiseContainer_1 = __nccwpck_require__(71475); +/** + * Command instance + * + * It's rare that you need to create a Command instance yourself. + * + * @export + * @class Command + * + * @example + * ```js + * var infoCommand = new Command('info', null, function (err, result) { + * console.log('result', result); + * }); + * + * redis.sendCommand(infoCommand); + * + * // When no callback provided, Command instance will have a `promise` property, + * // which will resolve/reject with the result of the command. + * var getCommand = new Command('get', ['foo']); + * getCommand.promise.then(function (result) { + * console.log('result', result); + * }); + * ``` + * @see {@link Redis#sendCommand} which can send a Command instance to Redis + */ +class Command { + /** + * Creates an instance of Command. + * @param {string} name Command name + * @param {(Array)} [args=[]] An array of command arguments + * @param {ICommandOptions} [options={}] + * @param {CallbackFunction} [callback] The callback that handles the response. + * If omit, the response will be handled via Promise + * @memberof Command + */ + constructor(name, args = [], options = {}, callback) { + this.name = name; + this.transformed = false; + this.isCustomCommand = false; + this.inTransaction = false; + this.isResolved = false; + this.replyEncoding = options.replyEncoding; + this.errorStack = options.errorStack; + this.args = lodash_1.flatten(args); + this.callback = callback; + this.initPromise(); + if (options.keyPrefix) { + this._iterateKeys((key) => options.keyPrefix + key); + } + if (options.readOnly) { + this.isReadOnly = true; + } + } + static getFlagMap() { + if (!this.flagMap) { + this.flagMap = Object.keys(Command.FLAGS).reduce((map, flagName) => { + map[flagName] = {}; + Command.FLAGS[flagName].forEach((commandName) => { + map[flagName][commandName] = true; + }); + return map; + }, {}); + } + return this.flagMap; + } + /** + * Check whether the command has the flag + * + * @param {string} flagName + * @param {string} commandName + * @return {boolean} + */ + static checkFlag(flagName, commandName) { + return !!this.getFlagMap()[flagName][commandName]; + } + static setArgumentTransformer(name, func) { + this._transformer.argument[name] = func; + } + static setReplyTransformer(name, func) { + this._transformer.reply[name] = func; + } + initPromise() { + const Promise = promiseContainer_1.get(); + const promise = new Promise((resolve, reject) => { + if (!this.transformed) { + this.transformed = true; + const transformer = Command._transformer.argument[this.name]; + if (transformer) { + this.args = transformer(this.args); + } + this.stringifyArguments(); + } + this.resolve = this._convertValue(resolve); + if (this.errorStack) { + this.reject = (err) => { + reject(utils_1.optimizeErrorStack(err, this.errorStack.stack, __dirname)); + }; + } + else { + this.reject = reject; + } + }); + this.promise = standard_as_callback_1.default(promise, this.callback); + } + getSlot() { + if (typeof this.slot === "undefined") { + const key = this.getKeys()[0]; + this.slot = key == null ? null : calculateSlot(key); + } + return this.slot; + } + getKeys() { + return this._iterateKeys(); + } + /** + * Iterate through the command arguments that are considered keys. + * + * @param {Function} [transform=(key) => key] The transformation that should be applied to + * each key. The transformations will persist. + * @returns {string[]} The keys of the command. + * @memberof Command + */ + _iterateKeys(transform = (key) => key) { + if (typeof this.keys === "undefined") { + this.keys = []; + if (commands.exists(this.name)) { + const keyIndexes = commands.getKeyIndexes(this.name, this.args); + for (const index of keyIndexes) { + this.args[index] = transform(this.args[index]); + this.keys.push(this.args[index]); + } + } + } + return this.keys; + } + /** + * Convert command to writable buffer or string + * + * @return {string|Buffer} + * @see {@link Redis#sendCommand} + * @public + */ + toWritable() { + let bufferMode = false; + for (const arg of this.args) { + if (arg instanceof Buffer) { + bufferMode = true; + break; + } + } + let result; + const commandStr = "*" + + (this.args.length + 1) + + "\r\n$" + + Buffer.byteLength(this.name) + + "\r\n" + + this.name + + "\r\n"; + if (bufferMode) { + const buffers = new MixedBuffers(); + buffers.push(commandStr); + for (const arg of this.args) { + if (arg instanceof Buffer) { + if (arg.length === 0) { + buffers.push("$0\r\n\r\n"); + } + else { + buffers.push("$" + arg.length + "\r\n"); + buffers.push(arg); + buffers.push("\r\n"); + } + } + else { + buffers.push("$" + + Buffer.byteLength(arg) + + "\r\n" + + arg + + "\r\n"); + } + } + result = buffers.toBuffer(); + } + else { + result = commandStr; + for (const arg of this.args) { + result += + "$" + + Buffer.byteLength(arg) + + "\r\n" + + arg + + "\r\n"; + } + } + return result; + } + stringifyArguments() { + for (let i = 0; i < this.args.length; ++i) { + const arg = this.args[i]; + if (!(arg instanceof Buffer) && typeof arg !== "string") { + this.args[i] = utils_1.toArg(arg); + } + } + } + /** + * Convert the value from buffer to the target encoding. + * + * @private + * @param {Function} resolve The resolve function of the Promise + * @returns {Function} A function to transform and resolve a value + * @memberof Command + */ + _convertValue(resolve) { + return (value) => { + try { + const existingTimer = this._commandTimeoutTimer; + if (existingTimer) { + clearTimeout(existingTimer); + delete this._commandTimeoutTimer; + } + resolve(this.transformReply(value)); + this.isResolved = true; + } + catch (err) { + this.reject(err); + } + return this.promise; + }; } - } else { - // Case: block styles permitted. - for (i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - if (char === CHAR_LINE_FEED) { - hasLineBreak = true; - // Check if any line can be folded. - if (shouldTrackWidth) { - hasFoldableLine = hasFoldableLine || - // Foldable line = too long, and not more-indented. - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' '); - previousLineBreak = i; + /** + * Convert buffer/buffer[] to string/string[], + * and apply reply transformer. + * + * @memberof Command + */ + transformReply(result) { + if (this.replyEncoding) { + result = utils_1.convertBufferToString(result, this.replyEncoding); } - } else if (!isPrintable(char)) { - return STYLE_DOUBLE; - } - prev_char = i > 0 ? string.charCodeAt(i - 1) : null; - plain = plain && isPlainSafe(char, prev_char); + const transformer = Command._transformer.reply[this.name]; + if (transformer) { + result = transformer(result); + } + return result; } - // in case the end is missing a \n - hasFoldableLine = hasFoldableLine || (shouldTrackWidth && - (i - previousLineBreak - 1 > lineWidth && - string[previousLineBreak + 1] !== ' ')); - } - // Although every style can represent \n without escaping, prefer block styles - // for multiline, since they're more readable and they don't add empty lines. - // Also prefer folding a super-long line. - if (!hasLineBreak && !hasFoldableLine) { - // Strings interpretable as another type have to be quoted; - // e.g. the string 'true' vs. the boolean true. - return plain && !testAmbiguousType(string) - ? STYLE_PLAIN : STYLE_SINGLE; - } - // Edge case: block indentation indicator can only have one digit. - if (indentPerLevel > 9 && needIndentIndicator(string)) { - return STYLE_DOUBLE; - } - // At this point we know block styles are valid. - // Prefer literal style unless we want to fold. - return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; -} - -// Note: line breaking/folding is implemented for only the folded style. -// NB. We drop the last trailing newline (if any) of a returned block scalar -// since the dumper adds its own newline. This always works: -// • No ending newline => unaffected; already using strip "-" chomping. -// • Ending newline => removed then restored. -// Importantly, this keeps the "+" chomp indicator from gaining an extra line. -function writeScalar(state, string, level, iskey) { - state.dump = (function () { - if (string.length === 0) { - return "''"; + /** + * Set the wait time before terminating the attempt to execute a command + * and generating an error. + */ + setTimeout(ms) { + if (!this._commandTimeoutTimer) { + this._commandTimeoutTimer = setTimeout(() => { + if (!this.isResolved) { + this.reject(new Error("Command timed out")); + } + }, ms); + } } - if (!state.noCompatMode && - DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { - return "'" + string + "'"; +} +exports.default = Command; +Command.FLAGS = { + VALID_IN_SUBSCRIBER_MODE: [ + "subscribe", + "psubscribe", + "unsubscribe", + "punsubscribe", + "ping", + "quit", + ], + VALID_IN_MONITOR_MODE: ["monitor", "auth"], + ENTER_SUBSCRIBER_MODE: ["subscribe", "psubscribe"], + EXIT_SUBSCRIBER_MODE: ["unsubscribe", "punsubscribe"], + WILL_DISCONNECT: ["quit"], +}; +Command._transformer = { + argument: {}, + reply: {}, +}; +const msetArgumentTransformer = function (args) { + if (args.length === 1) { + if (typeof Map !== "undefined" && args[0] instanceof Map) { + return utils_1.convertMapToArray(args[0]); + } + if (typeof args[0] === "object" && args[0] !== null) { + return utils_1.convertObjectToArray(args[0]); + } } - - var indent = state.indent * Math.max(1, level); // no 0-indent scalars - // As indentation gets deeper, let the width decrease monotonically - // to the lower bound min(state.lineWidth, 40). - // Note that this implies - // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. - // state.lineWidth > 40 + state.indent: width decreases until the lower bound. - // This behaves better than a constant minimum width which disallows narrower options, - // or an indent threshold which causes the width to suddenly increase. - var lineWidth = state.lineWidth === -1 - ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); - - // Without knowing if keys are implicit/explicit, assume implicit for safety. - var singleLineOnly = iskey - // No block styles in flow mode. - || (state.flowLevel > -1 && level >= state.flowLevel); - function testAmbiguity(string) { - return testImplicitResolving(state, string); + return args; +}; +const hsetArgumentTransformer = function (args) { + if (args.length === 2) { + if (typeof Map !== "undefined" && args[1] instanceof Map) { + return [args[0]].concat(utils_1.convertMapToArray(args[1])); + } + if (typeof args[1] === "object" && args[1] !== null) { + return [args[0]].concat(utils_1.convertObjectToArray(args[1])); + } } - - switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { - case STYLE_PLAIN: - return string; - case STYLE_SINGLE: - return "'" + string.replace(/'/g, "''") + "'"; - case STYLE_LITERAL: - return '|' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(string, indent)); - case STYLE_FOLDED: - return '>' + blockHeader(string, state.indent) - + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); - case STYLE_DOUBLE: - return '"' + escapeString(string, lineWidth) + '"'; - default: - throw new YAMLException('impossible error: invalid scalar style'); + return args; +}; +Command.setArgumentTransformer("mset", msetArgumentTransformer); +Command.setArgumentTransformer("msetnx", msetArgumentTransformer); +Command.setArgumentTransformer("hset", hsetArgumentTransformer); +Command.setArgumentTransformer("hmset", hsetArgumentTransformer); +Command.setReplyTransformer("hgetall", function (result) { + if (Array.isArray(result)) { + const obj = {}; + for (let i = 0; i < result.length; i += 2) { + const key = result[i]; + const value = result[i + 1]; + if (obj[key]) { + // can only be truthy if the property is special somehow, like '__proto__' or 'constructor' + // https://github.com/luin/ioredis/issues/1267 + Object.defineProperty(obj, key, { + value, + configurable: true, + enumerable: true, + writable: true, + }); + } + else { + obj[key] = value; + } + } + return obj; } - }()); -} - -// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. -function blockHeader(string, indentPerLevel) { - var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; - - // note the special case: the string '\n' counts as a "trailing" empty line. - var clip = string[string.length - 1] === '\n'; - var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); - var chomp = keep ? '+' : (clip ? '' : '-'); - - return indentIndicator + chomp + '\n'; -} - -// (See the note for writeScalar.) -function dropEndingNewline(string) { - return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; -} - -// Note: a long line without a suitable break point will exceed the width limit. -// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. -function foldString(string, width) { - // In folded style, $k$ consecutive newlines output as $k+1$ newlines— - // unless they're before or after a more-indented line, or at the very - // beginning or end, in which case $k$ maps to $k$. - // Therefore, parse each chunk as newline(s) followed by a content line. - var lineRe = /(\n+)([^\n]*)/g; - - // first line (possibly an empty line) - var result = (function () { - var nextLF = string.indexOf('\n'); - nextLF = nextLF !== -1 ? nextLF : string.length; - lineRe.lastIndex = nextLF; - return foldLine(string.slice(0, nextLF), width); - }()); - // If we haven't reached the first content line yet, don't add an extra \n. - var prevMoreIndented = string[0] === '\n' || string[0] === ' '; - var moreIndented; - - // rest of the lines - var match; - while ((match = lineRe.exec(string))) { - var prefix = match[1], line = match[2]; - moreIndented = (line[0] === ' '); - result += prefix - + (!prevMoreIndented && !moreIndented && line !== '' - ? '\n' : '') - + foldLine(line, width); - prevMoreIndented = moreIndented; - } - - return result; -} - -// Greedy line breaking. -// Picks the longest line under the limit each time, -// otherwise settles for the shortest line over the limit. -// NB. More-indented lines *cannot* be folded, as that would add an extra \n. -function foldLine(line, width) { - if (line === '' || line[0] === ' ') return line; - - // Since a more-indented line adds a \n, breaks can't be followed by a space. - var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. - var match; - // start is an inclusive index. end, curr, and next are exclusive. - var start = 0, end, curr = 0, next = 0; - var result = ''; - - // Invariants: 0 <= start <= length-1. - // 0 <= curr <= next <= max(0, length-2). curr - start <= width. - // Inside the loop: - // A match implies length >= 2, so curr and next are <= length-2. - while ((match = breakRe.exec(line))) { - next = match.index; - // maintain invariant: curr - start <= width - if (next - start > width) { - end = (curr > start) ? curr : next; // derive end <= length-2 - result += '\n' + line.slice(start, end); - // skip the space that was output as \n - start = end + 1; // derive start <= length-1 + return result; +}); +class MixedBuffers { + constructor() { + this.length = 0; + this.items = []; } - curr = next; - } - - // By the invariants, start <= length-1, so there is something left over. - // It is either the whole string or a part starting from non-whitespace. - result += '\n'; - // Insert a break if the remainder is too long and there is a break available. - if (line.length - start > width && curr > start) { - result += line.slice(start, curr) + '\n' + line.slice(curr + 1); - } else { - result += line.slice(start); - } - - return result.slice(1); // drop extra \n joiner -} - -// Escapes a double-quoted string. -function escapeString(string) { - var result = ''; - var char, nextChar; - var escapeSeq; - - for (var i = 0; i < string.length; i++) { - char = string.charCodeAt(i); - // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). - if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { - nextChar = string.charCodeAt(i + 1); - if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { - // Combine the surrogate pair and store it escaped. - result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); - // Advance index one extra since we already used that char here. - i++; continue; - } + push(x) { + this.length += Buffer.byteLength(x); + this.items.push(x); } - escapeSeq = ESCAPE_SEQUENCES[char]; - result += !escapeSeq && isPrintable(char) - ? string[i] - : escapeSeq || encodeHex(char); - } - - return result; -} - -function writeFlowSequence(state, level, object) { - var _result = '', - _tag = state.tag, - index, - length; - - for (index = 0, length = object.length; index < length; index += 1) { - // Write only valid elements. - if (writeNode(state, level, object[index], false, false)) { - if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); - _result += state.dump; + toBuffer() { + const result = Buffer.allocUnsafe(this.length); + let offset = 0; + for (const item of this.items) { + const length = Buffer.byteLength(item); + Buffer.isBuffer(item) + ? item.copy(result, offset) + : result.write(item, offset, length); + offset += length; + } + return result; } - } - - state.tag = _tag; - state.dump = '[' + _result + ']'; } -function writeBlockSequence(state, level, object, compact) { - var _result = '', - _tag = state.tag, - index, - length; - for (index = 0, length = object.length; index < length; index += 1) { - // Write only valid elements. - if (writeNode(state, level + 1, object[index], true, true)) { - if (!compact || index !== 0) { - _result += generateNextLine(state, level); - } +/***/ }), - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - _result += '-'; - } else { - _result += '- '; - } +/***/ 33642: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - _result += state.dump; - } - } +"use strict"; - state.tag = _tag; - state.dump = _result || '[]'; // Empty sequence if no valid values. +Object.defineProperty(exports, "__esModule", ({ value: true })); +const lodash_1 = __nccwpck_require__(20961); +const command_1 = __nccwpck_require__(90803); +const script_1 = __nccwpck_require__(88540); +const PromiseContainer = __nccwpck_require__(71475); +const standard_as_callback_1 = __nccwpck_require__(91543); +const autoPipelining_1 = __nccwpck_require__(97873); +const DROP_BUFFER_SUPPORT_ERROR = "*Buffer methods are not available " + + 'because "dropBufferSupport" option is enabled.' + + "Refer to https://github.com/luin/ioredis/wiki/Improve-Performance for more details."; +/** + * Commander + * + * This is the base class of Redis, Redis.Cluster and Pipeline + * + * @param {boolean} [options.showFriendlyErrorStack=false] - Whether to show a friendly error stack. + * Will decrease the performance significantly. + * @constructor + */ +function Commander() { + this.options = lodash_1.defaults({}, this.options || {}, { + showFriendlyErrorStack: false, + }); + this.scriptsSet = {}; + this.addedBuiltinSet = new Set(); } - -function writeFlowMapping(state, level, object) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - pairBuffer; - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - - pairBuffer = ''; - if (index !== 0) pairBuffer += ', '; - - if (state.condenseFlow) pairBuffer += '"'; - - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; - - if (!writeNode(state, level, objectKey, false, false)) { - continue; // Skip this pair because of invalid key; - } - - if (state.dump.length > 1024) pairBuffer += '? '; - - pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); - - if (!writeNode(state, level, objectValue, false, false)) { - continue; // Skip this pair because of invalid value. +exports.default = Commander; +const commands = __nccwpck_require__(98020).list.filter(function (command) { + return command !== "monitor"; +}); +commands.push("sentinel"); +/** + * Return supported builtin commands + * + * @return {string[]} command list + * @public + */ +Commander.prototype.getBuiltinCommands = function () { + return commands.slice(0); +}; +/** + * Create a builtin command + * + * @param {string} commandName - command name + * @return {object} functions + * @public + */ +Commander.prototype.createBuiltinCommand = function (commandName) { + return { + string: generateFunction(null, commandName, "utf8"), + buffer: generateFunction(null, commandName, null), + }; +}; +/** + * Create add builtin command + * + * @param {string} commandName - command name + * @return {object} functions + * @public + */ +Commander.prototype.addBuiltinCommand = function (commandName) { + this.addedBuiltinSet.add(commandName); + this[commandName] = generateFunction(commandName, commandName, "utf8"); + this[commandName + "Buffer"] = generateFunction(commandName + "Buffer", commandName, null); +}; +commands.forEach(function (commandName) { + Commander.prototype[commandName] = generateFunction(commandName, commandName, "utf8"); + Commander.prototype[commandName + "Buffer"] = generateFunction(commandName + "Buffer", commandName, null); +}); +Commander.prototype.call = generateFunction("call", "utf8"); +Commander.prototype.callBuffer = generateFunction("callBuffer", null); +// eslint-disable-next-line @typescript-eslint/camelcase +Commander.prototype.send_command = Commander.prototype.call; +/** + * Define a custom command using lua script + * + * @param {string} name - the command name + * @param {object} definition + * @param {string} definition.lua - the lua code + * @param {number} [definition.numberOfKeys=null] - the number of keys. + * @param {boolean} [definition.readOnly=false] - force this script to be readonly so it executes on slaves as well. + * If omit, you have to pass the number of keys as the first argument every time you invoke the command + */ +Commander.prototype.defineCommand = function (name, definition) { + const script = new script_1.default(definition.lua, definition.numberOfKeys, this.options.keyPrefix, definition.readOnly); + this.scriptsSet[name] = script; + this[name] = generateScriptingFunction(name, name, script, "utf8"); + this[name + "Buffer"] = generateScriptingFunction(name + "Buffer", name, script, null); +}; +/** + * Send a command + * + * @abstract + * @public + */ +Commander.prototype.sendCommand = function () { }; +function generateFunction(functionName, _commandName, _encoding) { + if (typeof _encoding === "undefined") { + _encoding = _commandName; + _commandName = null; } - - pairBuffer += state.dump; - - // Both key and value are valid. - _result += pairBuffer; - } - - state.tag = _tag; - state.dump = '{' + _result + '}'; + return function (...args) { + const commandName = _commandName || args.shift(); + let callback = args[args.length - 1]; + if (typeof callback === "function") { + args.pop(); + } + else { + callback = undefined; + } + const options = { + errorStack: this.options.showFriendlyErrorStack ? new Error() : undefined, + keyPrefix: this.options.keyPrefix, + replyEncoding: _encoding, + }; + if (this.options.dropBufferSupport && !_encoding) { + return standard_as_callback_1.default(PromiseContainer.get().reject(new Error(DROP_BUFFER_SUPPORT_ERROR)), callback); + } + // No auto pipeline, use regular command sending + if (!autoPipelining_1.shouldUseAutoPipelining(this, functionName, commandName)) { + return this.sendCommand(new command_1.default(commandName, args, options, callback)); + } + // Create a new pipeline and make sure it's scheduled + return autoPipelining_1.executeWithAutoPipelining(this, functionName, commandName, args, callback); + }; +} +function generateScriptingFunction(functionName, commandName, script, encoding) { + return function () { + let length = arguments.length; + const lastArgIndex = length - 1; + let callback = arguments[lastArgIndex]; + if (typeof callback !== "function") { + callback = undefined; + } + else { + length = lastArgIndex; + } + const args = new Array(length); + for (let i = 0; i < length; i++) { + args[i] = arguments[i]; + } + let options; + if (this.options.dropBufferSupport) { + if (!encoding) { + return standard_as_callback_1.default(PromiseContainer.get().reject(new Error(DROP_BUFFER_SUPPORT_ERROR)), callback); + } + options = { replyEncoding: null }; + } + else { + options = { replyEncoding: encoding }; + } + if (this.options.showFriendlyErrorStack) { + options.errorStack = new Error(); + } + // No auto pipeline, use regular command sending + if (!autoPipelining_1.shouldUseAutoPipelining(this, functionName, commandName)) { + return script.execute(this, args, options, callback); + } + // Create a new pipeline and make sure it's scheduled + return autoPipelining_1.executeWithAutoPipelining(this, functionName, commandName, args, callback); + }; } -function writeBlockMapping(state, level, object, compact) { - var _result = '', - _tag = state.tag, - objectKeyList = Object.keys(object), - index, - length, - objectKey, - objectValue, - explicitPair, - pairBuffer; - - // Allow sorting keys so that the output file is deterministic - if (state.sortKeys === true) { - // Default sorting - objectKeyList.sort(); - } else if (typeof state.sortKeys === 'function') { - // Custom sort function - objectKeyList.sort(state.sortKeys); - } else if (state.sortKeys) { - // Something is wrong - throw new YAMLException('sortKeys must be a boolean or a function'); - } - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - pairBuffer = ''; +/***/ }), - if (!compact || index !== 0) { - pairBuffer += generateNextLine(state, level); - } +/***/ 72712: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - objectKey = objectKeyList[index]; - objectValue = object[objectKey]; +"use strict"; - if (!writeNode(state, level + 1, objectKey, true, true, true)) { - continue; // Skip this pair because of invalid key. +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils_1 = __nccwpck_require__(94832); +const debug = utils_1.Debug("AbstractConnector"); +class AbstractConnector { + constructor(disconnectTimeout) { + this.connecting = false; + this.disconnectTimeout = disconnectTimeout; } - - explicitPair = (state.tag !== null && state.tag !== '?') || - (state.dump && state.dump.length > 1024); - - if (explicitPair) { - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += '?'; - } else { - pairBuffer += '? '; - } + check(info) { + return true; } - - pairBuffer += state.dump; - - if (explicitPair) { - pairBuffer += generateNextLine(state, level); + disconnect() { + this.connecting = false; + if (this.stream) { + const stream = this.stream; // Make sure callbacks refer to the same instance + const timeout = setTimeout(() => { + debug("stream %s:%s still open, destroying it", stream.remoteAddress, stream.remotePort); + stream.destroy(); + }, this.disconnectTimeout); + stream.on("close", () => clearTimeout(timeout)); + stream.end(); + } } +} +exports.default = AbstractConnector; - if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { - continue; // Skip this pair because of invalid value. - } - if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { - pairBuffer += ':'; - } else { - pairBuffer += ': '; - } +/***/ }), - pairBuffer += state.dump; +/***/ 22913: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - // Both key and value are valid. - _result += pairBuffer; - } +"use strict"; - state.tag = _tag; - state.dump = _result || '{}'; // Empty mapping if no valid pairs. +var __awaiter = (this && this.__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()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils_1 = __nccwpck_require__(94832); +const debug = utils_1.Debug("FailoverDetector"); +const CHANNEL_NAME = "+switch-master"; +class FailoverDetector { + // sentinels can't be used for regular commands after this + constructor(connector, sentinels) { + this.isDisconnected = false; + this.connector = connector; + this.sentinels = sentinels; + } + cleanup() { + this.isDisconnected = true; + for (const sentinel of this.sentinels) { + sentinel.client.disconnect(); + } + } + subscribe() { + return __awaiter(this, void 0, void 0, function* () { + debug("Starting FailoverDetector"); + const promises = []; + for (const sentinel of this.sentinels) { + const promise = sentinel.client.subscribe(CHANNEL_NAME).catch((err) => { + debug("Failed to subscribe to failover messages on sentinel %s:%s (%s)", sentinel.address.host || "127.0.0.1", sentinel.address.port || 26739, err.message); + }); + promises.push(promise); + sentinel.client.on("message", (channel) => { + if (!this.isDisconnected && channel === CHANNEL_NAME) { + this.disconnect(); + } + }); + } + yield Promise.all(promises); + }); + } + disconnect() { + // Avoid disconnecting more than once per failover. + // A new FailoverDetector will be created after reconnecting. + this.isDisconnected = true; + debug("Failover detected, disconnecting"); + // Will call this.cleanup() + this.connector.disconnect(); + } } +exports.FailoverDetector = FailoverDetector; -function detectType(state, object, explicit) { - var _result, typeList, index, length, type, style; - - typeList = explicit ? state.explicitTypes : state.implicitTypes; - - for (index = 0, length = typeList.length; index < length; index += 1) { - type = typeList[index]; - if ((type.instanceOf || type.predicate) && - (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && - (!type.predicate || type.predicate(object))) { +/***/ }), - state.tag = explicit ? type.tag : '?'; +/***/ 72225: +/***/ ((__unused_webpack_module, exports) => { - if (type.represent) { - style = state.styleMap[type.tag] || type.defaultStyle; +"use strict"; - if (_toString.call(type.represent) === '[object Function]') { - _result = type.represent(object, style); - } else if (_hasOwnProperty.call(type.represent, style)) { - _result = type.represent[style](object, style); - } else { - throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); +Object.defineProperty(exports, "__esModule", ({ value: true })); +function isSentinelEql(a, b) { + return ((a.host || "127.0.0.1") === (b.host || "127.0.0.1") && + (a.port || 26379) === (b.port || 26379)); +} +class SentinelIterator { + constructor(sentinels) { + this.cursor = 0; + this.sentinels = sentinels.slice(0); + } + next() { + const done = this.cursor >= this.sentinels.length; + return { done, value: done ? undefined : this.sentinels[this.cursor++] }; + } + reset(moveCurrentEndpointToFirst) { + if (moveCurrentEndpointToFirst && + this.sentinels.length > 1 && + this.cursor !== 1) { + this.sentinels.unshift(...this.sentinels.splice(this.cursor - 1)); } - - state.dump = _result; - } - - return true; + this.cursor = 0; + } + add(sentinel) { + for (let i = 0; i < this.sentinels.length; i++) { + if (isSentinelEql(sentinel, this.sentinels[i])) { + return false; + } + } + this.sentinels.push(sentinel); + return true; + } + toString() { + return `${JSON.stringify(this.sentinels)} @${this.cursor}`; } - } - - return false; } +exports.default = SentinelIterator; -// Serializes `object` and writes it to global `result`. -// Returns true on success, or false on invalid object. -// -function writeNode(state, level, object, block, compact, iskey) { - state.tag = null; - state.dump = object; - - if (!detectType(state, object, false)) { - detectType(state, object, true); - } - - var type = _toString.call(state.dump); - - if (block) { - block = (state.flowLevel < 0 || state.flowLevel > level); - } - var objectOrArray = type === '[object Object]' || type === '[object Array]', - duplicateIndex, - duplicate; +/***/ }), - if (objectOrArray) { - duplicateIndex = state.duplicates.indexOf(object); - duplicate = duplicateIndex !== -1; - } +/***/ 10379: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { - compact = false; - } +"use strict"; - if (duplicate && state.usedDuplicates[duplicateIndex]) { - state.dump = '*ref_' + duplicateIndex; - } else { - if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { - state.usedDuplicates[duplicateIndex] = true; - } - if (type === '[object Object]') { - if (block && (Object.keys(state.dump).length !== 0)) { - writeBlockMapping(state, level, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; +var __awaiter = (this && this.__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()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const net_1 = __nccwpck_require__(11631); +const utils_1 = __nccwpck_require__(94832); +const tls_1 = __nccwpck_require__(4016); +const StandaloneConnector_1 = __nccwpck_require__(8774); +const SentinelIterator_1 = __nccwpck_require__(72225); +exports.SentinelIterator = SentinelIterator_1.default; +const AbstractConnector_1 = __nccwpck_require__(72712); +const redis_1 = __nccwpck_require__(83609); +const FailoverDetector_1 = __nccwpck_require__(22913); +const debug = utils_1.Debug("SentinelConnector"); +class SentinelConnector extends AbstractConnector_1.default { + constructor(options) { + super(options.disconnectTimeout); + this.options = options; + this.failoverDetector = null; + this.emitter = null; + if (!this.options.sentinels.length) { + throw new Error("Requires at least one sentinel to connect to."); } - } else { - writeFlowMapping(state, level, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + if (!this.options.name) { + throw new Error("Requires the name of master."); } - } - } else if (type === '[object Array]') { - var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; - if (block && (state.dump.length !== 0)) { - writeBlockSequence(state, arrayLevel, state.dump, compact); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + state.dump; + this.sentinelIterator = new SentinelIterator_1.default(this.options.sentinels); + } + check(info) { + const roleMatches = !info.role || this.options.role === info.role; + if (!roleMatches) { + debug("role invalid, expected %s, but got %s", this.options.role, info.role); + // Start from the next item. + // Note that `reset` will move the cursor to the previous element, + // so we advance two steps here. + this.sentinelIterator.next(); + this.sentinelIterator.next(); + this.sentinelIterator.reset(true); } - } else { - writeFlowSequence(state, arrayLevel, state.dump); - if (duplicate) { - state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + return roleMatches; + } + disconnect() { + super.disconnect(); + if (this.failoverDetector) { + this.failoverDetector.cleanup(); } - } - } else if (type === '[object String]') { - if (state.tag !== '?') { - writeScalar(state, state.dump, level, iskey); - } - } else { - if (state.skipInvalid) return false; - throw new YAMLException('unacceptable kind of an object to dump ' + type); } - - if (state.tag !== null && state.tag !== '?') { - state.dump = '!<' + state.tag + '> ' + state.dump; + connect(eventEmitter) { + this.connecting = true; + this.retryAttempts = 0; + let lastError; + const connectToNext = () => __awaiter(this, void 0, void 0, function* () { + const endpoint = this.sentinelIterator.next(); + if (endpoint.done) { + this.sentinelIterator.reset(false); + const retryDelay = typeof this.options.sentinelRetryStrategy === "function" + ? this.options.sentinelRetryStrategy(++this.retryAttempts) + : null; + let errorMsg = typeof retryDelay !== "number" + ? "All sentinels are unreachable and retry is disabled." + : `All sentinels are unreachable. Retrying from scratch after ${retryDelay}ms.`; + if (lastError) { + errorMsg += ` Last error: ${lastError.message}`; + } + debug(errorMsg); + const error = new Error(errorMsg); + if (typeof retryDelay === "number") { + eventEmitter("error", error); + yield new Promise((resolve) => setTimeout(resolve, retryDelay)); + return connectToNext(); + } + else { + throw error; + } + } + let resolved = null; + let err = null; + try { + resolved = yield this.resolve(endpoint.value); + } + catch (error) { + err = error; + } + if (!this.connecting) { + throw new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG); + } + const endpointAddress = endpoint.value.host + ":" + endpoint.value.port; + if (resolved) { + debug("resolved: %s:%s from sentinel %s", resolved.host, resolved.port, endpointAddress); + if (this.options.enableTLSForSentinelMode && this.options.tls) { + Object.assign(resolved, this.options.tls); + this.stream = tls_1.connect(resolved); + } + else { + this.stream = net_1.createConnection(resolved); + } + this.stream.once("connect", () => this.initFailoverDetector()); + this.stream.once("error", (err) => { + this.firstError = err; + }); + return this.stream; + } + else { + const errorMsg = err + ? "failed to connect to sentinel " + + endpointAddress + + " because " + + err.message + : "connected to sentinel " + + endpointAddress + + " successfully, but got an invalid reply: " + + resolved; + debug(errorMsg); + eventEmitter("sentinelError", new Error(errorMsg)); + if (err) { + lastError = err; + } + return connectToNext(); + } + }); + return connectToNext(); + } + updateSentinels(client) { + return __awaiter(this, void 0, void 0, function* () { + if (!this.options.updateSentinels) { + return; + } + const result = yield client.sentinel("sentinels", this.options.name); + if (!Array.isArray(result)) { + return; + } + result + .map(utils_1.packObject) + .forEach((sentinel) => { + const flags = sentinel.flags ? sentinel.flags.split(",") : []; + if (flags.indexOf("disconnected") === -1 && + sentinel.ip && + sentinel.port) { + const endpoint = this.sentinelNatResolve(addressResponseToAddress(sentinel)); + if (this.sentinelIterator.add(endpoint)) { + debug("adding sentinel %s:%s", endpoint.host, endpoint.port); + } + } + }); + debug("Updated internal sentinels: %s", this.sentinelIterator); + }); + } + resolveMaster(client) { + return __awaiter(this, void 0, void 0, function* () { + const result = yield client.sentinel("get-master-addr-by-name", this.options.name); + yield this.updateSentinels(client); + return this.sentinelNatResolve(Array.isArray(result) + ? { host: result[0], port: Number(result[1]) } + : null); + }); + } + resolveSlave(client) { + return __awaiter(this, void 0, void 0, function* () { + const result = yield client.sentinel("slaves", this.options.name); + if (!Array.isArray(result)) { + return null; + } + const availableSlaves = result + .map(utils_1.packObject) + .filter((slave) => slave.flags && !slave.flags.match(/(disconnected|s_down|o_down)/)); + return this.sentinelNatResolve(selectPreferredSentinel(availableSlaves, this.options.preferredSlaves)); + }); + } + sentinelNatResolve(item) { + if (!item || !this.options.natMap) + return item; + return this.options.natMap[`${item.host}:${item.port}`] || item; + } + connectToSentinel(endpoint, options) { + return new redis_1.default(Object.assign({ port: endpoint.port || 26379, host: endpoint.host, username: this.options.sentinelUsername || null, password: this.options.sentinelPassword || null, family: endpoint.family || + (StandaloneConnector_1.isIIpcConnectionOptions(this.options) + ? undefined + : this.options.family), tls: this.options.sentinelTLS, retryStrategy: null, enableReadyCheck: false, connectTimeout: this.options.connectTimeout, commandTimeout: this.options.sentinelCommandTimeout, dropBufferSupport: true }, options)); + } + resolve(endpoint) { + return __awaiter(this, void 0, void 0, function* () { + const client = this.connectToSentinel(endpoint); + // ignore the errors since resolve* methods will handle them + client.on("error", noop); + try { + if (this.options.role === "slave") { + return yield this.resolveSlave(client); + } + else { + return yield this.resolveMaster(client); + } + } + finally { + client.disconnect(); + } + }); + } + initFailoverDetector() { + var _a; + return __awaiter(this, void 0, void 0, function* () { + if (!this.options.failoverDetector) { + return; + } + // Move the current sentinel to the first position + this.sentinelIterator.reset(true); + const sentinels = []; + // In case of a large amount of sentinels, limit the number of concurrent connections + while (sentinels.length < this.options.sentinelMaxConnections) { + const { done, value } = this.sentinelIterator.next(); + if (done) { + break; + } + const client = this.connectToSentinel(value, { + lazyConnect: true, + retryStrategy: this.options.sentinelReconnectStrategy, + }); + client.on("reconnecting", () => { + var _a; + // Tests listen to this event + (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit("sentinelReconnecting"); + }); + sentinels.push({ address: value, client }); + } + this.sentinelIterator.reset(false); + if (this.failoverDetector) { + // Clean up previous detector + this.failoverDetector.cleanup(); + } + this.failoverDetector = new FailoverDetector_1.FailoverDetector(this, sentinels); + yield this.failoverDetector.subscribe(); + // Tests listen to this event + (_a = this.emitter) === null || _a === void 0 ? void 0 : _a.emit("failoverSubscribed"); + }); } - } - - return true; } +exports.default = SentinelConnector; +function selectPreferredSentinel(availableSlaves, preferredSlaves) { + if (availableSlaves.length === 0) { + return null; + } + let selectedSlave; + if (typeof preferredSlaves === "function") { + selectedSlave = preferredSlaves(availableSlaves); + } + else if (preferredSlaves !== null && typeof preferredSlaves === "object") { + const preferredSlavesArray = Array.isArray(preferredSlaves) + ? preferredSlaves + : [preferredSlaves]; + // sort by priority + preferredSlavesArray.sort((a, b) => { + // default the priority to 1 + if (!a.prio) { + a.prio = 1; + } + if (!b.prio) { + b.prio = 1; + } + // lowest priority first + if (a.prio < b.prio) { + return -1; + } + if (a.prio > b.prio) { + return 1; + } + return 0; + }); + // loop over preferred slaves and return the first match + for (let p = 0; p < preferredSlavesArray.length; p++) { + for (let a = 0; a < availableSlaves.length; a++) { + const slave = availableSlaves[a]; + if (slave.ip === preferredSlavesArray[p].ip) { + if (slave.port === preferredSlavesArray[p].port) { + selectedSlave = slave; + break; + } + } + } + if (selectedSlave) { + break; + } + } + } + // if none of the preferred slaves are available, a random available slave is returned + if (!selectedSlave) { + selectedSlave = utils_1.sample(availableSlaves); + } + return addressResponseToAddress(selectedSlave); +} +function addressResponseToAddress(input) { + return { host: input.ip, port: Number(input.port) }; +} +function noop() { } -function getDuplicateReferences(object, state) { - var objects = [], - duplicatesIndexes = [], - index, - length; - - inspectNode(object, objects, duplicatesIndexes); - for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { - state.duplicates.push(objects[duplicatesIndexes[index]]); - } - state.usedDuplicates = new Array(length); -} +/***/ }), -function inspectNode(object, objects, duplicatesIndexes) { - var objectKeyList, - index, - length; +/***/ 8774: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (object !== null && typeof object === 'object') { - index = objects.indexOf(object); - if (index !== -1) { - if (duplicatesIndexes.indexOf(index) === -1) { - duplicatesIndexes.push(index); - } - } else { - objects.push(object); +"use strict"; - if (Array.isArray(object)) { - for (index = 0, length = object.length; index < length; index += 1) { - inspectNode(object[index], objects, duplicatesIndexes); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const net_1 = __nccwpck_require__(11631); +const tls_1 = __nccwpck_require__(4016); +const utils_1 = __nccwpck_require__(94832); +const AbstractConnector_1 = __nccwpck_require__(72712); +function isIIpcConnectionOptions(value) { + return value.path; +} +exports.isIIpcConnectionOptions = isIIpcConnectionOptions; +class StandaloneConnector extends AbstractConnector_1.default { + constructor(options) { + super(options.disconnectTimeout); + this.options = options; + } + connect(_) { + const { options } = this; + this.connecting = true; + let connectionOptions; + if (isIIpcConnectionOptions(options)) { + connectionOptions = { + path: options.path, + }; + } + else { + connectionOptions = {}; + if (options.port != null) { + connectionOptions.port = options.port; + } + if (options.host != null) { + connectionOptions.host = options.host; + } + if (options.family != null) { + connectionOptions.family = options.family; + } } - } else { - objectKeyList = Object.keys(object); - - for (index = 0, length = objectKeyList.length; index < length; index += 1) { - inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + if (options.tls) { + Object.assign(connectionOptions, options.tls); } - } + // TODO: + // We use native Promise here since other Promise + // implementation may use different schedulers that + // cause issue when the stream is resolved in the + // next tick. + // Should use the provided promise in the next major + // version and do not connect before resolved. + return new Promise((resolve, reject) => { + process.nextTick(() => { + if (!this.connecting) { + reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + return; + } + try { + if (options.tls) { + this.stream = tls_1.connect(connectionOptions); + } + else { + this.stream = net_1.createConnection(connectionOptions); + } + } + catch (err) { + reject(err); + return; + } + this.stream.once("error", (err) => { + this.firstError = err; + }); + resolve(this.stream); + }); + }); } - } } +exports.default = StandaloneConnector; -function dump(input, options) { - options = options || {}; - - var state = new State(options); - - if (!state.noRefs) getDuplicateReferences(input, state); - if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; +/***/ }), - return ''; -} +/***/ 72340: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function safeDump(input, options) { - return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); -} +"use strict"; -module.exports.dump = dump; -module.exports.safeDump = safeDump; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const StandaloneConnector_1 = __nccwpck_require__(8774); +exports.StandaloneConnector = StandaloneConnector_1.default; +const SentinelConnector_1 = __nccwpck_require__(10379); +exports.SentinelConnector = SentinelConnector_1.default; /***/ }), -/***/ 65199: -/***/ ((module) => { +/***/ 97282: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; -// YAML error class. http://stackoverflow.com/questions/8458984 -// - - -function YAMLException(reason, mark) { - // Super constructor - Error.call(this); - this.name = 'YAMLException'; - this.reason = reason; - this.mark = mark; - this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); - - // Include stack trace in error object - if (Error.captureStackTrace) { - // Chrome and NodeJS - Error.captureStackTrace(this, this.constructor); - } else { - // FF, IE 10+ and Safari 6+. Fallback for others - this.stack = (new Error()).stack || ''; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const redis_errors_1 = __nccwpck_require__(81879); +class ClusterAllFailedError extends redis_errors_1.RedisError { + constructor(message, lastNodeError) { + super(message); + this.lastNodeError = lastNodeError; + Error.captureStackTrace(this, this.constructor); + } + get name() { + return this.constructor.name; + } } - - -// Inherit from Error -YAMLException.prototype = Object.create(Error.prototype); -YAMLException.prototype.constructor = YAMLException; - - -YAMLException.prototype.toString = function toString(compact) { - var result = this.name + ': '; - - result += this.reason || '(unknown reason)'; - - if (!compact && this.mark) { - result += ' ' + this.mark.toString(); - } - - return result; -}; - - -module.exports = YAMLException; +exports.default = ClusterAllFailedError; /***/ }), -/***/ 45190: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 90735: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; - -/*eslint-disable max-len,no-use-before-define*/ - -var common = __nccwpck_require__(59136); -var YAMLException = __nccwpck_require__(65199); -var Mark = __nccwpck_require__(55426); -var DEFAULT_SAFE_SCHEMA = __nccwpck_require__(48949); -var DEFAULT_FULL_SCHEMA = __nccwpck_require__(56874); - - -var _hasOwnProperty = Object.prototype.hasOwnProperty; - - -var CONTEXT_FLOW_IN = 1; -var CONTEXT_FLOW_OUT = 2; -var CONTEXT_BLOCK_IN = 3; -var CONTEXT_BLOCK_OUT = 4; - - -var CHOMPING_CLIP = 1; -var CHOMPING_STRIP = 2; -var CHOMPING_KEEP = 3; - - -var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; -var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; -var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; -var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; -var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; - - -function _class(obj) { return Object.prototype.toString.call(obj); } - -function is_EOL(c) { - return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); -} - -function is_WHITE_SPACE(c) { - return (c === 0x09/* Tab */) || (c === 0x20/* Space */); -} - -function is_WS_OR_EOL(c) { - return (c === 0x09/* Tab */) || - (c === 0x20/* Space */) || - (c === 0x0A/* LF */) || - (c === 0x0D/* CR */); -} - -function is_FLOW_INDICATOR(c) { - return c === 0x2C/* , */ || - c === 0x5B/* [ */ || - c === 0x5D/* ] */ || - c === 0x7B/* { */ || - c === 0x7D/* } */; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const redis_errors_1 = __nccwpck_require__(81879); +class MaxRetriesPerRequestError extends redis_errors_1.AbortError { + constructor(maxRetriesPerRequest) { + const message = `Reached the max retries per request limit (which is ${maxRetriesPerRequest}). Refer to "maxRetriesPerRequest" option for details.`; + super(message); + Error.captureStackTrace(this, this.constructor); + } + get name() { + return this.constructor.name; + } } +exports.default = MaxRetriesPerRequestError; -function fromHexCode(c) { - var lc; - - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - /*eslint-disable no-bitwise*/ - lc = c | 0x20; +/***/ }), - if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { - return lc - 0x61 + 10; - } +/***/ 23961: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - return -1; -} +"use strict"; -function escapedHexLen(c) { - if (c === 0x78/* x */) { return 2; } - if (c === 0x75/* u */) { return 4; } - if (c === 0x55/* U */) { return 8; } - return 0; -} +Object.defineProperty(exports, "__esModule", ({ value: true })); +const MaxRetriesPerRequestError_1 = __nccwpck_require__(90735); +exports.MaxRetriesPerRequestError = MaxRetriesPerRequestError_1.default; -function fromDecimalCode(c) { - if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { - return c - 0x30; - } - return -1; -} +/***/ }), -function simpleEscapeSequence(c) { - /* eslint-disable indent */ - return (c === 0x30/* 0 */) ? '\x00' : - (c === 0x61/* a */) ? '\x07' : - (c === 0x62/* b */) ? '\x08' : - (c === 0x74/* t */) ? '\x09' : - (c === 0x09/* Tab */) ? '\x09' : - (c === 0x6E/* n */) ? '\x0A' : - (c === 0x76/* v */) ? '\x0B' : - (c === 0x66/* f */) ? '\x0C' : - (c === 0x72/* r */) ? '\x0D' : - (c === 0x65/* e */) ? '\x1B' : - (c === 0x20/* Space */) ? ' ' : - (c === 0x22/* " */) ? '\x22' : - (c === 0x2F/* / */) ? '/' : - (c === 0x5C/* \ */) ? '\x5C' : - (c === 0x4E/* N */) ? '\x85' : - (c === 0x5F/* _ */) ? '\xA0' : - (c === 0x4C/* L */) ? '\u2028' : - (c === 0x50/* P */) ? '\u2029' : ''; -} +/***/ 45069: +/***/ ((module, exports, __nccwpck_require__) => { -function charFromCodepoint(c) { - if (c <= 0xFFFF) { - return String.fromCharCode(c); - } - // Encode UTF-16 surrogate pair - // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF - return String.fromCharCode( - ((c - 0x010000) >> 10) + 0xD800, - ((c - 0x010000) & 0x03FF) + 0xDC00 - ); -} +"use strict"; -var simpleEscapeCheck = new Array(256); // integer, for fast access -var simpleEscapeMap = new Array(256); -for (var i = 0; i < 256; i++) { - simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; - simpleEscapeMap[i] = simpleEscapeSequence(i); +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports = module.exports = __nccwpck_require__(83609).default; +var redis_1 = __nccwpck_require__(83609); +exports.default = redis_1.default; +var cluster_1 = __nccwpck_require__(17208); +exports.Cluster = cluster_1.default; +var command_1 = __nccwpck_require__(90803); +exports.Command = command_1.default; +var ScanStream_1 = __nccwpck_require__(6134); +exports.ScanStream = ScanStream_1.default; +var pipeline_1 = __nccwpck_require__(42803); +exports.Pipeline = pipeline_1.default; +var AbstractConnector_1 = __nccwpck_require__(72712); +exports.AbstractConnector = AbstractConnector_1.default; +var SentinelConnector_1 = __nccwpck_require__(10379); +exports.SentinelConnector = SentinelConnector_1.default; +exports.SentinelIterator = SentinelConnector_1.SentinelIterator; +// No TS typings +exports.ReplyError = __nccwpck_require__(81879).ReplyError; +const PromiseContainer = __nccwpck_require__(71475); +Object.defineProperty(exports, "Promise", ({ + get() { + return PromiseContainer.get(); + }, + set(lib) { + PromiseContainer.set(lib); + }, +})); +function print(err, reply) { + if (err) { + console.log("Error: " + err); + } + else { + console.log("Reply: " + reply); + } } +exports.print = print; -function State(input, options) { - this.input = input; - - this.filename = options['filename'] || null; - this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; - this.onWarning = options['onWarning'] || null; - this.legacy = options['legacy'] || false; - this.json = options['json'] || false; - this.listener = options['listener'] || null; - - this.implicitTypes = this.schema.compiledImplicit; - this.typeMap = this.schema.compiledTypeMap; - - this.length = input.length; - this.position = 0; - this.line = 0; - this.lineStart = 0; - this.lineIndent = 0; - - this.documents = []; - - /* - this.version; - this.checkLineBreaks; - this.tagMap; - this.anchorMap; - this.tag; - this.anchor; - this.kind; - this.result;*/ - -} +/***/ }), +/***/ 42803: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { -function generateError(state, message) { - return new YAMLException( - message, - new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); -} +"use strict"; -function throwError(state, message) { - throw generateError(state, message); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const command_1 = __nccwpck_require__(90803); +const util_1 = __nccwpck_require__(31669); +const standard_as_callback_1 = __nccwpck_require__(91543); +const redis_commands_1 = __nccwpck_require__(98020); +const calculateSlot = __nccwpck_require__(48481); +const pMap = __nccwpck_require__(91855); +const PromiseContainer = __nccwpck_require__(71475); +const commander_1 = __nccwpck_require__(33642); +/* + This function derives from the cluster-key-slot implementation. + Instead of checking that all keys have the same slot, it checks that all slots are served by the same set of nodes. + If this is satisfied, it returns the first key's slot. +*/ +function generateMultiWithNodes(redis, keys) { + const slot = calculateSlot(keys[0]); + const target = redis._groupsBySlot[slot]; + for (let i = 1; i < keys.length; i++) { + if (redis._groupsBySlot[calculateSlot(keys[i])] !== target) { + return -1; + } + } + return slot; } - -function throwWarning(state, message) { - if (state.onWarning) { - state.onWarning.call(null, generateError(state, message)); - } +function Pipeline(redis) { + commander_1.default.call(this); + this.redis = redis; + this.isCluster = + this.redis.constructor.name === "Cluster" || this.redis.isCluster; + this.isPipeline = true; + this.options = redis.options; + this._queue = []; + this._result = []; + this._transactions = 0; + this._shaToScript = {}; + Object.keys(redis.scriptsSet).forEach((name) => { + const script = redis.scriptsSet[name]; + this._shaToScript[script.sha] = script; + this[name] = redis[name]; + this[name + "Buffer"] = redis[name + "Buffer"]; + }); + redis.addedBuiltinSet.forEach((name) => { + this[name] = redis[name]; + this[name + "Buffer"] = redis[name + "Buffer"]; + }); + const Promise = PromiseContainer.get(); + this.promise = new Promise((resolve, reject) => { + this.resolve = resolve; + this.reject = reject; + }); + const _this = this; + Object.defineProperty(this, "length", { + get: function () { + return _this._queue.length; + }, + }); } - - -var directiveHandlers = { - - YAML: function handleYamlDirective(state, name, args) { - - var match, major, minor; - - if (state.version !== null) { - throwError(state, 'duplication of %YAML directive'); +exports.default = Pipeline; +Object.assign(Pipeline.prototype, commander_1.default.prototype); +Pipeline.prototype.fillResult = function (value, position) { + if (this._queue[position].name === "exec" && Array.isArray(value[1])) { + const execLength = value[1].length; + for (let i = 0; i < execLength; i++) { + if (value[1][i] instanceof Error) { + continue; + } + const cmd = this._queue[position - (execLength - i)]; + try { + value[1][i] = cmd.transformReply(value[1][i]); + } + catch (err) { + value[1][i] = err; + } + } + } + this._result[position] = value; + if (--this.replyPending) { + return; + } + if (this.isCluster) { + let retriable = true; + let commonError; + for (let i = 0; i < this._result.length; ++i) { + const error = this._result[i][0]; + const command = this._queue[i]; + if (error) { + if (command.name === "exec" && + error.message === + "EXECABORT Transaction discarded because of previous errors.") { + continue; + } + if (!commonError) { + commonError = { + name: error.name, + message: error.message, + }; + } + else if (commonError.name !== error.name || + commonError.message !== error.message) { + retriable = false; + break; + } + } + else if (!command.inTransaction) { + const isReadOnly = redis_commands_1.exists(command.name) && redis_commands_1.hasFlag(command.name, "readonly"); + if (!isReadOnly) { + retriable = false; + break; + } + } + } + if (commonError && retriable) { + const _this = this; + const errv = commonError.message.split(" "); + const queue = this._queue; + let inTransaction = false; + this._queue = []; + for (let i = 0; i < queue.length; ++i) { + if (errv[0] === "ASK" && + !inTransaction && + queue[i].name !== "asking" && + (!queue[i - 1] || queue[i - 1].name !== "asking")) { + const asking = new command_1.default("asking"); + asking.ignore = true; + this.sendCommand(asking); + } + queue[i].initPromise(); + this.sendCommand(queue[i]); + inTransaction = queue[i].inTransaction; + } + let matched = true; + if (typeof this.leftRedirections === "undefined") { + this.leftRedirections = {}; + } + const exec = function () { + _this.exec(); + }; + this.redis.handleError(commonError, this.leftRedirections, { + moved: function (slot, key) { + _this.preferKey = key; + _this.redis.slots[errv[1]] = [key]; + _this.redis._groupsBySlot[errv[1]] = _this.redis._groupsIds[_this.redis.slots[errv[1]].join(";")]; + _this.redis.refreshSlotsCache(); + _this.exec(); + }, + ask: function (slot, key) { + _this.preferKey = key; + _this.exec(); + }, + tryagain: exec, + clusterDown: exec, + connectionClosed: exec, + maxRedirections: () => { + matched = false; + }, + defaults: () => { + matched = false; + }, + }); + if (matched) { + return; + } + } } - - if (args.length !== 1) { - throwError(state, 'YAML directive accepts exactly one argument'); + let ignoredCount = 0; + for (let i = 0; i < this._queue.length - ignoredCount; ++i) { + if (this._queue[i + ignoredCount].ignore) { + ignoredCount += 1; + } + this._result[i] = this._result[i + ignoredCount]; } - - match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); - - if (match === null) { - throwError(state, 'ill-formed argument of the YAML directive'); + this.resolve(this._result.slice(0, this._result.length - ignoredCount)); +}; +Pipeline.prototype.sendCommand = function (command) { + if (this._transactions > 0) { + command.inTransaction = true; } - - major = parseInt(match[1], 10); - minor = parseInt(match[2], 10); - - if (major !== 1) { - throwError(state, 'unacceptable YAML version of the document'); + const position = this._queue.length; + command.pipelineIndex = position; + command.promise + .then((result) => { + this.fillResult([null, result], position); + }) + .catch((error) => { + this.fillResult([error], position); + }); + this._queue.push(command); + return this; +}; +Pipeline.prototype.addBatch = function (commands) { + let command, commandName, args; + for (let i = 0; i < commands.length; ++i) { + command = commands[i]; + commandName = command[0]; + args = command.slice(1); + this[commandName].apply(this, args); } - - state.version = args[0]; - state.checkLineBreaks = (minor < 2); - - if (minor !== 1 && minor !== 2) { - throwWarning(state, 'unsupported YAML version of the document'); + return this; +}; +const multi = Pipeline.prototype.multi; +Pipeline.prototype.multi = function () { + this._transactions += 1; + return multi.apply(this, arguments); +}; +const execBuffer = Pipeline.prototype.execBuffer; +const exec = Pipeline.prototype.exec; +Pipeline.prototype.execBuffer = util_1.deprecate(function () { + if (this._transactions > 0) { + this._transactions -= 1; } - }, - - TAG: function handleTagDirective(state, name, args) { - - var handle, prefix; - - if (args.length !== 2) { - throwError(state, 'TAG directive accepts exactly two arguments'); + return execBuffer.apply(this, arguments); +}, "Pipeline#execBuffer: Use Pipeline#exec instead"); +Pipeline.prototype.exec = function (callback) { + // Wait for the cluster to be connected, since we need nodes information before continuing + if (this.isCluster && !this.redis.slots.length) { + this.redis.delayUntilReady((err) => { + if (err) { + callback(err); + return; + } + this.exec(callback); + }); + return this.promise; } - - handle = args[0]; - prefix = args[1]; - - if (!PATTERN_TAG_HANDLE.test(handle)) { - throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + if (this._transactions > 0) { + this._transactions -= 1; + return (this.options.dropBufferSupport ? exec : execBuffer).apply(this, arguments); } - - if (_hasOwnProperty.call(state.tagMap, handle)) { - throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + if (!this.nodeifiedPromise) { + this.nodeifiedPromise = true; + standard_as_callback_1.default(this.promise, callback); } - - if (!PATTERN_TAG_URI.test(prefix)) { - throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + if (!this._queue.length) { + this.resolve([]); } - - state.tagMap[handle] = prefix; - } -}; - - -function captureSegment(state, start, end, checkJson) { - var _position, _length, _character, _result; - - if (start < end) { - _result = state.input.slice(start, end); - - if (checkJson) { - for (_position = 0, _length = _result.length; _position < _length; _position += 1) { - _character = _result.charCodeAt(_position); - if (!(_character === 0x09 || - (0x20 <= _character && _character <= 0x10FFFF))) { - throwError(state, 'expected valid JSON character'); + let pipelineSlot; + if (this.isCluster) { + // List of the first key for each command + const sampleKeys = []; + for (let i = 0; i < this._queue.length; i++) { + const keys = this._queue[i].getKeys(); + if (keys.length) { + sampleKeys.push(keys[0]); + } + // For each command, check that the keys belong to the same slot + if (keys.length && calculateSlot.generateMulti(keys) < 0) { + this.reject(new Error("All the keys in a pipeline command should belong to the same slot")); + return this.promise; + } + } + if (sampleKeys.length) { + pipelineSlot = generateMultiWithNodes(this.redis, sampleKeys); + if (pipelineSlot < 0) { + this.reject(new Error("All keys in the pipeline should belong to the same slots allocation group")); + return this.promise; + } + } + else { + // Send the pipeline to a random node + pipelineSlot = (Math.random() * 16384) | 0; } - } - } else if (PATTERN_NON_PRINTABLE.test(_result)) { - throwError(state, 'the stream contains non-printable characters'); } + // Check whether scripts exists + const scripts = []; + for (let i = 0; i < this._queue.length; ++i) { + const item = this._queue[i]; + if (item.name !== "evalsha") { + continue; + } + const script = this._shaToScript[item.args[0]]; + if (!script || + this.redis._addedScriptHashes[script.sha] || + scripts.includes(script)) { + continue; + } + scripts.push(script); + } + const _this = this; + if (!scripts.length) { + return execPipeline(); + } + // In cluster mode, always load scripts before running the pipeline + if (this.isCluster) { + return pMap(scripts, (script) => _this.redis.script("load", script.lua), { + concurrency: 10, + }).then(function () { + for (let i = 0; i < scripts.length; i++) { + _this.redis._addedScriptHashes[scripts[i].sha] = true; + } + return execPipeline(); + }); + } + return this.redis + .script("exists", scripts.map(({ sha }) => sha)) + .then(function (results) { + const pending = []; + for (let i = 0; i < results.length; ++i) { + if (!results[i]) { + pending.push(scripts[i]); + } + } + const Promise = PromiseContainer.get(); + return Promise.all(pending.map(function (script) { + return _this.redis.script("load", script.lua); + })); + }) + .then(function () { + for (let i = 0; i < scripts.length; i++) { + _this.redis._addedScriptHashes[scripts[i].sha] = true; + } + return execPipeline(); + }); + function execPipeline() { + let data = ""; + let buffers; + let writePending = (_this.replyPending = _this._queue.length); + let node; + if (_this.isCluster) { + node = { + slot: pipelineSlot, + redis: _this.redis.connectionPool.nodes.all[_this.preferKey], + }; + } + let bufferMode = false; + const stream = { + write: function (writable) { + if (writable instanceof Buffer) { + bufferMode = true; + } + if (bufferMode) { + if (!buffers) { + buffers = []; + } + if (typeof data === "string") { + buffers.push(Buffer.from(data, "utf8")); + data = undefined; + } + buffers.push(typeof writable === "string" + ? Buffer.from(writable, "utf8") + : writable); + } + else { + data += writable; + } + if (!--writePending) { + let sendData; + if (buffers) { + sendData = Buffer.concat(buffers); + } + else { + sendData = data; + } + if (_this.isCluster) { + node.redis.stream.write(sendData); + } + else { + _this.redis.stream.write(sendData); + } + // Reset writePending for resending + writePending = _this._queue.length; + data = ""; + buffers = undefined; + bufferMode = false; + } + }, + }; + for (let i = 0; i < _this._queue.length; ++i) { + _this.redis.sendCommand(_this._queue[i], stream, node); + } + return _this.promise; + } +}; - state.result += _result; - } -} - -function mergeMappings(state, destination, source, overridableKeys) { - var sourceKeys, key, index, quantity; - if (!common.isObject(source)) { - throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); - } +/***/ }), - sourceKeys = Object.keys(source); +/***/ 71475: +/***/ ((__unused_webpack_module, exports) => { - for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { - key = sourceKeys[index]; +"use strict"; - if (!_hasOwnProperty.call(destination, key)) { - destination[key] = source[key]; - overridableKeys[key] = true; +Object.defineProperty(exports, "__esModule", ({ value: true })); +function isPromise(obj) { + return (!!obj && + (typeof obj === "object" || typeof obj === "function") && + typeof obj.then === "function"); +} +exports.isPromise = isPromise; +let promise = Promise; +function get() { + return promise; +} +exports.get = get; +function set(lib) { + if (typeof lib !== "function") { + throw new Error(`Provided Promise must be a function, got ${lib}`); } - } + promise = lib; } +exports.set = set; -function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { - var index, quantity; - // The output is a plain object here, so keys can only be strings. - // We need to convert keyNode to a string, but doing so can hang the process - // (deeply nested arrays that explode exponentially using aliases). - if (Array.isArray(keyNode)) { - keyNode = Array.prototype.slice.call(keyNode); +/***/ }), - for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { - if (Array.isArray(keyNode[index])) { - throwError(state, 'nested arrays are not supported inside keys'); - } +/***/ 1422: +/***/ ((__unused_webpack_module, exports) => { - if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { - keyNode[index] = '[object Object]'; - } - } - } +"use strict"; - // Avoid code execution in load() via toString property - // (still use its own toString for arrays, timestamps, - // and whatever user schema extensions happen to have @@toStringTag) - if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { - keyNode = '[object Object]'; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.DEFAULT_REDIS_OPTIONS = { + // Connection + port: 6379, + host: "localhost", + family: 4, + connectTimeout: 10000, + disconnectTimeout: 2000, + retryStrategy: function (times) { + return Math.min(times * 50, 2000); + }, + keepAlive: 0, + noDelay: true, + connectionName: null, + // Sentinel + sentinels: null, + name: null, + role: "master", + sentinelRetryStrategy: function (times) { + return Math.min(times * 10, 1000); + }, + sentinelReconnectStrategy: function () { + // This strategy only applies when sentinels are used for detecting + // a failover, not during initial master resolution. + // The deployment can still function when some of the sentinels are down + // for a long period of time, so we may not want to attempt reconnection + // very often. Therefore the default interval is fairly long (1 minute). + return 60000; + }, + natMap: null, + enableTLSForSentinelMode: false, + updateSentinels: true, + failoverDetector: false, + // Status + username: null, + password: null, + db: 0, + // Others + dropBufferSupport: false, + enableOfflineQueue: true, + enableReadyCheck: true, + autoResubscribe: true, + autoResendUnfulfilledCommands: true, + lazyConnect: false, + keyPrefix: "", + reconnectOnError: null, + readOnly: false, + stringNumbers: false, + maxRetriesPerRequest: 20, + maxLoadingRetryTime: 10000, + enableAutoPipelining: false, + autoPipeliningIgnoredCommands: [], + maxScriptsCachingTime: 60000, + sentinelMaxConnections: 10, +}; - keyNode = String(keyNode); +/***/ }), - if (_result === null) { - _result = {}; - } +/***/ 74276: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (keyTag === 'tag:yaml.org,2002:merge') { - if (Array.isArray(valueNode)) { - for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { - mergeMappings(state, _result, valueNode[index], overridableKeys); - } - } else { - mergeMappings(state, _result, valueNode, overridableKeys); - } - } else { - if (!state.json && - !_hasOwnProperty.call(overridableKeys, keyNode) && - _hasOwnProperty.call(_result, keyNode)) { - state.line = startLine || state.line; - state.position = startPos || state.position; - throwError(state, 'duplicated mapping key'); - } - _result[keyNode] = valueNode; - delete overridableKeys[keyNode]; - } +"use strict"; - return _result; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const redis_errors_1 = __nccwpck_require__(81879); +const command_1 = __nccwpck_require__(90803); +const errors_1 = __nccwpck_require__(23961); +const utils_1 = __nccwpck_require__(94832); +const DataHandler_1 = __nccwpck_require__(30545); +const debug = utils_1.Debug("connection"); +function connectHandler(self) { + return function () { + self.setStatus("connect"); + self.resetCommandQueue(); + // AUTH command should be processed before any other commands + let flushed = false; + const { connectionEpoch } = self; + if (self.condition.auth) { + self.auth(self.condition.auth, function (err) { + if (connectionEpoch !== self.connectionEpoch) { + return; + } + if (err) { + if (err.message.indexOf("no password is set") !== -1) { + console.warn("[WARN] Redis server does not require a password, but a password was supplied."); + } + else if (err.message.indexOf("without any password configured for the default user") !== -1) { + console.warn("[WARN] This Redis server's `default` user does not require a password, but a password was supplied"); + } + else if (err.message.indexOf("wrong number of arguments for 'auth' command") !== -1) { + console.warn(`[ERROR] The server returned "wrong number of arguments for 'auth' command". You are probably passing both username and password to Redis version 5 or below. You should only pass the 'password' option for Redis version 5 and under.`); + } + else { + flushed = true; + self.recoverFromFatalError(err, err); + } + } + }); + } + if (self.condition.select) { + self.select(self.condition.select).catch((err) => { + // If the node is in cluster mode, select is disallowed. + // In this case, reconnect won't help. + self.silentEmit("error", err); + }); + } + if (!self.options.enableReadyCheck) { + exports.readyHandler(self)(); + } + /* + No need to keep the reference of DataHandler here + because we don't need to do the cleanup. + `Stream#end()` will remove all listeners for us. + */ + new DataHandler_1.default(self, { + stringNumbers: self.options.stringNumbers, + dropBufferSupport: self.options.dropBufferSupport, + }); + if (self.options.enableReadyCheck) { + self._readyCheck(function (err, info) { + if (connectionEpoch !== self.connectionEpoch) { + return; + } + if (err) { + if (!flushed) { + self.recoverFromFatalError(new Error("Ready check failed: " + err.message), err); + } + } + else { + self.serverInfo = info; + if (self.connector.check(info)) { + exports.readyHandler(self)(); + } + else { + self.disconnect(true); + } + } + }); + } + }; } - -function readLineBreak(state) { - var ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x0A/* LF */) { - state.position++; - } else if (ch === 0x0D/* CR */) { - state.position++; - if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { - state.position++; - } - } else { - throwError(state, 'a line break is expected'); - } - - state.line += 1; - state.lineStart = state.position; +exports.connectHandler = connectHandler; +function abortError(command) { + const err = new redis_errors_1.AbortError("Command aborted due to connection close"); + err.command = { + name: command.name, + args: command.args, + }; + return err; } - -function skipSeparationSpace(state, allowComments, checkIndent) { - var lineBreaks = 0, - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (allowComments && ch === 0x23/* # */) { - do { - ch = state.input.charCodeAt(++state.position); - } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); +// If a contiguous set of pipeline commands starts from index zero then they +// can be safely reattempted. If however we have a chain of pipelined commands +// starting at index 1 or more it means we received a partial response before +// the connection close and those pipelined commands must be aborted. For +// example, if the queue looks like this: [2, 3, 4, 0, 1, 2] then after +// aborting and purging we'll have a queue that looks like this: [0, 1, 2] +function abortIncompletePipelines(commandQueue) { + let expectedIndex = 0; + for (let i = 0; i < commandQueue.length;) { + const command = commandQueue.peekAt(i).command; + const pipelineIndex = command.pipelineIndex; + if (pipelineIndex === undefined || pipelineIndex === 0) { + expectedIndex = 0; + } + if (pipelineIndex !== undefined && pipelineIndex !== expectedIndex++) { + commandQueue.remove(i, 1); + command.reject(abortError(command)); + continue; + } + i++; } - - if (is_EOL(ch)) { - readLineBreak(state); - - ch = state.input.charCodeAt(state.position); - lineBreaks++; - state.lineIndent = 0; - - while (ch === 0x20/* Space */) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); - } - } else { - break; +} +// If only a partial transaction result was received before connection close, +// we have to abort any transaction fragments that may have ended up in the +// offline queue +function abortTransactionFragments(commandQueue) { + for (let i = 0; i < commandQueue.length;) { + const command = commandQueue.peekAt(i).command; + if (command.name === "multi") { + break; + } + if (command.name === "exec") { + commandQueue.remove(i, 1); + command.reject(abortError(command)); + break; + } + if (command.inTransaction) { + commandQueue.remove(i, 1); + command.reject(abortError(command)); + } + else { + i++; + } } - } - - if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { - throwWarning(state, 'deficient indentation'); - } - - return lineBreaks; } - -function testDocumentSeparator(state) { - var _position = state.position, - ch; - - ch = state.input.charCodeAt(_position); - - // Condition state.position === state.lineStart is tested - // in parent on each call, for efficiency. No needs to test here again. - if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && - ch === state.input.charCodeAt(_position + 1) && - ch === state.input.charCodeAt(_position + 2)) { - - _position += 3; - - ch = state.input.charCodeAt(_position); - - if (ch === 0 || is_WS_OR_EOL(ch)) { - return true; +function closeHandler(self) { + return function () { + self.setStatus("close"); + if (!self.prevCondition) { + self.prevCondition = self.condition; + } + if (self.commandQueue.length) { + abortIncompletePipelines(self.commandQueue); + self.prevCommandQueue = self.commandQueue; + } + if (self.offlineQueue.length) { + abortTransactionFragments(self.offlineQueue); + } + if (self.manuallyClosing) { + self.manuallyClosing = false; + debug("skip reconnecting since the connection is manually closed."); + return close(); + } + if (typeof self.options.retryStrategy !== "function") { + debug("skip reconnecting because `retryStrategy` is not a function"); + return close(); + } + const retryDelay = self.options.retryStrategy(++self.retryAttempts); + if (typeof retryDelay !== "number") { + debug("skip reconnecting because `retryStrategy` doesn't return a number"); + return close(); + } + debug("reconnect in %sms", retryDelay); + self.setStatus("reconnecting", retryDelay); + self.reconnectTimeout = setTimeout(function () { + self.reconnectTimeout = null; + self.connect().catch(utils_1.noop); + }, retryDelay); + const { maxRetriesPerRequest } = self.options; + if (typeof maxRetriesPerRequest === "number") { + if (maxRetriesPerRequest < 0) { + debug("maxRetriesPerRequest is negative, ignoring..."); + } + else { + const remainder = self.retryAttempts % (maxRetriesPerRequest + 1); + if (remainder === 0) { + debug("reach maxRetriesPerRequest limitation, flushing command queue..."); + self.flushQueue(new errors_1.MaxRetriesPerRequestError(maxRetriesPerRequest)); + } + } + } + }; + function close() { + self.setStatus("end"); + self.flushQueue(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); } - } - - return false; } - -function writeFoldedLines(state, count) { - if (count === 1) { - state.result += ' '; - } else if (count > 1) { - state.result += common.repeat('\n', count - 1); - } +exports.closeHandler = closeHandler; +function errorHandler(self) { + return function (error) { + debug("error: %s", error); + self.silentEmit("error", error); + }; +} +exports.errorHandler = errorHandler; +function readyHandler(self) { + return function () { + self.setStatus("ready"); + self.retryAttempts = 0; + if (self.options.monitor) { + self.call("monitor"); + const { sendCommand } = self; + self.sendCommand = function (command) { + if (command_1.default.checkFlag("VALID_IN_MONITOR_MODE", command.name)) { + return sendCommand.call(self, command); + } + command.reject(new Error("Connection is in monitoring mode, can't process commands.")); + return command.promise; + }; + self.once("close", function () { + delete self.sendCommand; + }); + self.setStatus("monitoring"); + return; + } + const finalSelect = self.prevCondition + ? self.prevCondition.select + : self.condition.select; + if (self.options.connectionName) { + debug("set the connection name [%s]", self.options.connectionName); + self.client("setname", self.options.connectionName).catch(utils_1.noop); + } + if (self.options.readOnly) { + debug("set the connection to readonly mode"); + self.readonly().catch(utils_1.noop); + } + if (self.prevCondition) { + const condition = self.prevCondition; + self.prevCondition = null; + if (condition.subscriber && self.options.autoResubscribe) { + // We re-select the previous db first since + // `SELECT` command is not valid in sub mode. + if (self.condition.select !== finalSelect) { + debug("connect to db [%d]", finalSelect); + self.select(finalSelect); + } + const subscribeChannels = condition.subscriber.channels("subscribe"); + if (subscribeChannels.length) { + debug("subscribe %d channels", subscribeChannels.length); + self.subscribe(subscribeChannels); + } + const psubscribeChannels = condition.subscriber.channels("psubscribe"); + if (psubscribeChannels.length) { + debug("psubscribe %d channels", psubscribeChannels.length); + self.psubscribe(psubscribeChannels); + } + } + } + if (self.prevCommandQueue) { + if (self.options.autoResendUnfulfilledCommands) { + debug("resend %d unfulfilled commands", self.prevCommandQueue.length); + while (self.prevCommandQueue.length > 0) { + const item = self.prevCommandQueue.shift(); + if (item.select !== self.condition.select && + item.command.name !== "select") { + self.select(item.select); + } + self.sendCommand(item.command, item.stream); + } + } + else { + self.prevCommandQueue = null; + } + } + if (self.offlineQueue.length) { + debug("send %d commands in offline queue", self.offlineQueue.length); + const offlineQueue = self.offlineQueue; + self.resetOfflineQueue(); + while (offlineQueue.length > 0) { + const item = offlineQueue.shift(); + if (item.select !== self.condition.select && + item.command.name !== "select") { + self.select(item.select); + } + self.sendCommand(item.command, item.stream); + } + } + if (self.condition.select !== finalSelect) { + debug("connect to db [%d]", finalSelect); + self.select(finalSelect); + } + }; } +exports.readyHandler = readyHandler; -function readPlainScalar(state, nodeIndent, withinFlowCollection) { - var preceding, - following, - captureStart, - captureEnd, - hasPendingContent, - _line, - _lineStart, - _lineIndent, - _kind = state.kind, - _result = state.result, - ch; +/***/ }), - ch = state.input.charCodeAt(state.position); +/***/ 83609: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (is_WS_OR_EOL(ch) || - is_FLOW_INDICATOR(ch) || - ch === 0x23/* # */ || - ch === 0x26/* & */ || - ch === 0x2A/* * */ || - ch === 0x21/* ! */ || - ch === 0x7C/* | */ || - ch === 0x3E/* > */ || - ch === 0x27/* ' */ || - ch === 0x22/* " */ || - ch === 0x25/* % */ || - ch === 0x40/* @ */ || - ch === 0x60/* ` */) { - return false; - } +"use strict"; - if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { - following = state.input.charCodeAt(state.position + 1); +Object.defineProperty(exports, "__esModule", ({ value: true })); +const lodash_1 = __nccwpck_require__(20961); +const util_1 = __nccwpck_require__(31669); +const events_1 = __nccwpck_require__(28614); +const Deque = __nccwpck_require__(42342); +const command_1 = __nccwpck_require__(90803); +const commander_1 = __nccwpck_require__(33642); +const utils_1 = __nccwpck_require__(94832); +const standard_as_callback_1 = __nccwpck_require__(91543); +const eventHandler = __nccwpck_require__(74276); +const connectors_1 = __nccwpck_require__(72340); +const ScanStream_1 = __nccwpck_require__(6134); +const commands = __nccwpck_require__(98020); +const PromiseContainer = __nccwpck_require__(71475); +const transaction_1 = __nccwpck_require__(14645); +const RedisOptions_1 = __nccwpck_require__(1422); +const debug = utils_1.Debug("redis"); +/** + * Creates a Redis instance + * + * @constructor + * @param {(number|string|Object)} [port=6379] - Port of the Redis server, + * or a URL string(see the examples below), + * or the `options` object(see the third argument). + * @param {string|Object} [host=localhost] - Host of the Redis server, + * when the first argument is a URL string, + * this argument is an object represents the options. + * @param {Object} [options] - Other options. + * @param {number} [options.port=6379] - Port of the Redis server. + * @param {string} [options.host=localhost] - Host of the Redis server. + * @param {string} [options.family=4] - Version of IP stack. Defaults to 4. + * @param {string} [options.path=null] - Local domain socket path. If set the `port`, + * `host` and `family` will be ignored. + * @param {number} [options.keepAlive=0] - TCP KeepAlive on the socket with a X ms delay before start. + * Set to a non-number value to disable keepAlive. + * @param {boolean} [options.noDelay=true] - Whether to disable the Nagle's Algorithm. By default we disable + * it to reduce the latency. + * @param {string} [options.connectionName=null] - Connection name. + * @param {number} [options.db=0] - Database index to use. + * @param {string} [options.password=null] - If set, client will send AUTH command + * with the value of this option when connected. + * @param {string} [options.username=null] - Similar to `password`, Provide this for Redis ACL support. + * @param {boolean} [options.dropBufferSupport=false] - Drop the buffer support for better performance. + * This option is recommended to be enabled when + * handling large array response and you don't need the buffer support. + * @param {boolean} [options.enableReadyCheck=true] - When a connection is established to + * the Redis server, the server might still be loading the database from disk. + * While loading, the server not respond to any commands. + * To work around this, when this option is `true`, + * ioredis will check the status of the Redis server, + * and when the Redis server is able to process commands, + * a `ready` event will be emitted. + * @param {boolean} [options.enableOfflineQueue=true] - By default, + * if there is no active connection to the Redis server, + * commands are added to a queue and are executed once the connection is "ready" + * (when `enableReadyCheck` is `true`, + * "ready" means the Redis server has loaded the database from disk, otherwise means the connection + * to the Redis server has been established). If this option is false, + * when execute the command when the connection isn't ready, an error will be returned. + * @param {number} [options.connectTimeout=10000] - The milliseconds before a timeout occurs during the initial + * connection to the Redis server. + * @param {boolean} [options.autoResubscribe=true] - After reconnected, if the previous connection was in the + * subscriber mode, client will auto re-subscribe these channels. + * @param {boolean} [options.autoResendUnfulfilledCommands=true] - If true, client will resend unfulfilled + * commands(e.g. block commands) in the previous connection when reconnected. + * @param {boolean} [options.lazyConnect=false] - By default, + * When a new `Redis` instance is created, it will connect to Redis server automatically. + * If you want to keep the instance disconnected until a command is called, you can pass the `lazyConnect` option to + * the constructor: + * + * ```javascript + * var redis = new Redis({ lazyConnect: true }); + * // No attempting to connect to the Redis server here. - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - return false; + * // Now let's connect to the Redis server + * redis.get('foo', function () { + * }); + * ``` + * @param {Object} [options.tls] - TLS connection support. See https://github.com/luin/ioredis#tls-options + * @param {string} [options.keyPrefix=''] - The prefix to prepend to all keys in a command. + * @param {function} [options.retryStrategy] - See "Quick Start" section + * @param {number} [options.maxRetriesPerRequest] - See "Quick Start" section + * @param {number} [options.maxLoadingRetryTime=10000] - when redis server is not ready, we will wait for + * `loading_eta_seconds` from `info` command or maxLoadingRetryTime (milliseconds), whichever is smaller. + * @param {function} [options.reconnectOnError] - See "Quick Start" section + * @param {boolean} [options.readOnly=false] - Enable READONLY mode for the connection. + * Only available for cluster mode. + * @param {boolean} [options.stringNumbers=false] - Force numbers to be always returned as JavaScript + * strings. This option is necessary when dealing with big numbers (exceed the [-2^53, +2^53] range). + * @param {boolean} [options.enableTLSForSentinelMode=false] - Whether to support the `tls` option + * when connecting to Redis via sentinel mode. + * @param {NatMap} [options.natMap=null] NAT map for sentinel connector. + * @param {boolean} [options.updateSentinels=true] - Update the given `sentinels` list with new IP + * addresses when communicating with existing sentinels. + * @param {boolean} [options.failoverDetector=false] - Detect failover actively by subscribing to the + * related channels. With this option disabled, ioredis is still able to detect failovers because Redis + * Sentinel will disconnect all clients whenever a failover happens, so ioredis will reconnect to the new + * master. This option is useful when you want to detect failover quicker, but it will create more TCP + * connections to Redis servers in order to subscribe to related channels. +* @param {boolean} [options.enableAutoPipelining=false] - When enabled, all commands issued during an event loop + * iteration are automatically wrapped in a pipeline and sent to the server at the same time. + * This can dramatically improve performance. + * @param {string[]} [options.autoPipeliningIgnoredCommands=[]] - The list of commands which must not be automatically wrapped in pipelines. + * @param {number} [options.maxScriptsCachingTime=60000] Default script definition caching time. + * @extends [EventEmitter](http://nodejs.org/api/events.html#events_class_events_eventemitter) + * @extends Commander + * @example + * ```js + * var Redis = require('ioredis'); + * + * var redis = new Redis(); + * + * var redisOnPort6380 = new Redis(6380); + * var anotherRedis = new Redis(6380, '192.168.100.1'); + * var unixSocketRedis = new Redis({ path: '/tmp/echo.sock' }); + * var unixSocketRedis2 = new Redis('/tmp/echo.sock'); + * var urlRedis = new Redis('redis://user:password@redis-service.com:6379/'); + * var urlRedis2 = new Redis('//localhost:6379'); + * var urlRedisTls = new Redis('rediss://user:password@redis-service.com:6379/'); + * var authedRedis = new Redis(6380, '192.168.100.1', { password: 'password' }); + * ``` + */ +exports.default = Redis; +function Redis() { + if (!(this instanceof Redis)) { + console.error(new Error("Calling `Redis()` like a function is deprecated. Using `new Redis()` instead.").stack.replace("Error", "Warning")); + return new Redis(arguments[0], arguments[1], arguments[2]); } - } - - state.kind = 'scalar'; - state.result = ''; - captureStart = captureEnd = state.position; - hasPendingContent = false; - - while (ch !== 0) { - if (ch === 0x3A/* : */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following) || - withinFlowCollection && is_FLOW_INDICATOR(following)) { - break; - } - - } else if (ch === 0x23/* # */) { - preceding = state.input.charCodeAt(state.position - 1); - - if (is_WS_OR_EOL(preceding)) { - break; - } - - } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || - withinFlowCollection && is_FLOW_INDICATOR(ch)) { - break; - - } else if (is_EOL(ch)) { - _line = state.line; - _lineStart = state.lineStart; - _lineIndent = state.lineIndent; - skipSeparationSpace(state, false, -1); - - if (state.lineIndent >= nodeIndent) { - hasPendingContent = true; - ch = state.input.charCodeAt(state.position); - continue; - } else { - state.position = captureEnd; - state.line = _line; - state.lineStart = _lineStart; - state.lineIndent = _lineIndent; - break; - } + this.parseOptions(arguments[0], arguments[1], arguments[2]); + events_1.EventEmitter.call(this); + commander_1.default.call(this); + this.resetCommandQueue(); + this.resetOfflineQueue(); + this.connectionEpoch = 0; + if (this.options.Connector) { + this.connector = new this.options.Connector(this.options); } - - if (hasPendingContent) { - captureSegment(state, captureStart, captureEnd, false); - writeFoldedLines(state, state.line - _line); - captureStart = captureEnd = state.position; - hasPendingContent = false; + else if (this.options.sentinels) { + const sentinelConnector = new connectors_1.SentinelConnector(this.options); + sentinelConnector.emitter = this; + this.connector = sentinelConnector; } - - if (!is_WHITE_SPACE(ch)) { - captureEnd = state.position + 1; + else { + this.connector = new connectors_1.StandaloneConnector(this.options); } - - ch = state.input.charCodeAt(++state.position); - } - - captureSegment(state, captureStart, captureEnd, false); - - if (state.result) { - return true; - } - - state.kind = _kind; - state.result = _result; - return false; -} - -function readSingleQuotedScalar(state, nodeIndent) { - var ch, - captureStart, captureEnd; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x27/* ' */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x27/* ' */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x27/* ' */) { - captureStart = state.position; - state.position++; - captureEnd = state.position; - } else { - return true; - } - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a single quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; + this.retryAttempts = 0; + // Prepare a cache of scripts and setup a interval which regularly clears it + this._addedScriptHashes = {}; + // Prepare autopipelines structures + this._autoPipelines = new Map(); + this._runningAutoPipelines = new Set(); + Object.defineProperty(this, "autoPipelineQueueSize", { + get() { + let queued = 0; + for (const pipeline of this._autoPipelines.values()) { + queued += pipeline.length; + } + return queued; + }, + }); + // end(or wait) -> connecting -> connect -> ready -> end + if (this.options.lazyConnect) { + this.setStatus("wait"); + } + else { + this.connect().catch(lodash_1.noop); } - } - - throwError(state, 'unexpected end of the stream within a single quoted scalar'); } - -function readDoubleQuotedScalar(state, nodeIndent) { - var captureStart, - captureEnd, - hexLength, - hexResult, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x22/* " */) { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - state.position++; - captureStart = captureEnd = state.position; - - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - if (ch === 0x22/* " */) { - captureSegment(state, captureStart, state.position, true); - state.position++; - return true; - - } else if (ch === 0x5C/* \ */) { - captureSegment(state, captureStart, state.position, true); - ch = state.input.charCodeAt(++state.position); - - if (is_EOL(ch)) { - skipSeparationSpace(state, false, nodeIndent); - - // TODO: rework to inline fn with no type cast? - } else if (ch < 256 && simpleEscapeCheck[ch]) { - state.result += simpleEscapeMap[ch]; - state.position++; - - } else if ((tmp = escapedHexLen(ch)) > 0) { - hexLength = tmp; - hexResult = 0; - - for (; hexLength > 0; hexLength--) { - ch = state.input.charCodeAt(++state.position); - - if ((tmp = fromHexCode(ch)) >= 0) { - hexResult = (hexResult << 4) + tmp; - - } else { - throwError(state, 'expected hexadecimal character'); - } +util_1.inherits(Redis, events_1.EventEmitter); +Object.assign(Redis.prototype, commander_1.default.prototype); +/** + * Create a Redis instance + * + * @deprecated + */ +// @ts-ignore +Redis.createClient = function (...args) { + // @ts-ignore + return new Redis(...args); +}; +/** + * Default options + * + * @var defaultOptions + * @private + */ +Redis.defaultOptions = RedisOptions_1.DEFAULT_REDIS_OPTIONS; +Redis.prototype.resetCommandQueue = function () { + this.commandQueue = new Deque(); +}; +Redis.prototype.resetOfflineQueue = function () { + this.offlineQueue = new Deque(); +}; +Redis.prototype.parseOptions = function () { + this.options = {}; + let isTls = false; + for (let i = 0; i < arguments.length; ++i) { + const arg = arguments[i]; + if (arg === null || typeof arg === "undefined") { + continue; + } + if (typeof arg === "object") { + lodash_1.defaults(this.options, arg); + } + else if (typeof arg === "string") { + lodash_1.defaults(this.options, utils_1.parseURL(arg)); + if (arg.startsWith("rediss://")) { + isTls = true; + } + } + else if (typeof arg === "number") { + this.options.port = arg; + } + else { + throw new Error("Invalid argument " + arg); } - - state.result += charFromCodepoint(hexResult); - - state.position++; - - } else { - throwError(state, 'unknown escape sequence'); - } - - captureStart = captureEnd = state.position; - - } else if (is_EOL(ch)) { - captureSegment(state, captureStart, captureEnd, true); - writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); - captureStart = captureEnd = state.position; - - } else if (state.position === state.lineStart && testDocumentSeparator(state)) { - throwError(state, 'unexpected end of the document within a double quoted scalar'); - - } else { - state.position++; - captureEnd = state.position; } - } - - throwError(state, 'unexpected end of the stream within a double quoted scalar'); -} - -function readFlowCollection(state, nodeIndent) { - var readNext = true, - _line, - _tag = state.tag, - _result, - _anchor = state.anchor, - following, - terminator, - isPair, - isExplicitPair, - isMapping, - overridableKeys = {}, - keyNode, - keyTag, - valueNode, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x5B/* [ */) { - terminator = 0x5D;/* ] */ - isMapping = false; - _result = []; - } else if (ch === 0x7B/* { */) { - terminator = 0x7D;/* } */ - isMapping = true; - _result = {}; - } else { - return false; - } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(++state.position); - - while (ch !== 0) { - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === terminator) { - state.position++; - state.tag = _tag; - state.anchor = _anchor; - state.kind = isMapping ? 'mapping' : 'sequence'; - state.result = _result; - return true; - } else if (!readNext) { - throwError(state, 'missed comma between flow collection entries'); + if (isTls) { + lodash_1.defaults(this.options, { tls: true }); } - - keyTag = keyNode = valueNode = null; - isPair = isExplicitPair = false; - - if (ch === 0x3F/* ? */) { - following = state.input.charCodeAt(state.position + 1); - - if (is_WS_OR_EOL(following)) { - isPair = isExplicitPair = true; - state.position++; - skipSeparationSpace(state, true, nodeIndent); - } + lodash_1.defaults(this.options, Redis.defaultOptions); + if (typeof this.options.port === "string") { + this.options.port = parseInt(this.options.port, 10); } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - keyTag = state.tag; - keyNode = state.result; - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { - isPair = true; - ch = state.input.charCodeAt(++state.position); - skipSeparationSpace(state, true, nodeIndent); - composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); - valueNode = state.result; + if (typeof this.options.db === "string") { + this.options.db = parseInt(this.options.db, 10); } - - if (isMapping) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); - } else if (isPair) { - _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); - } else { - _result.push(keyNode); + if (this.options.parser === "hiredis") { + console.warn("Hiredis parser is abandoned since ioredis v3.0, and JavaScript parser will be used"); } - - skipSeparationSpace(state, true, nodeIndent); - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x2C/* , */) { - readNext = true; - ch = state.input.charCodeAt(++state.position); - } else { - readNext = false; +}; +/** + * Change instance's status + * @private + */ +Redis.prototype.setStatus = function (status, arg) { + // @ts-ignore + if (debug.enabled) { + debug("status[%s]: %s -> %s", this._getDescription(), this.status || "[empty]", status); } - } - - throwError(state, 'unexpected end of the stream within a flow collection'); -} - -function readBlockScalar(state, nodeIndent) { - var captureStart, - folding, - chomping = CHOMPING_CLIP, - didReadContent = false, - detectedIndent = false, - textIndent = nodeIndent, - emptyLines = 0, - atMoreIndented = false, - tmp, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch === 0x7C/* | */) { - folding = false; - } else if (ch === 0x3E/* > */) { - folding = true; - } else { - return false; - } - - state.kind = 'scalar'; - state.result = ''; - - while (ch !== 0) { - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { - if (CHOMPING_CLIP === chomping) { - chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; - } else { - throwError(state, 'repeat of a chomping mode identifier'); - } - - } else if ((tmp = fromDecimalCode(ch)) >= 0) { - if (tmp === 0) { - throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); - } else if (!detectedIndent) { - textIndent = nodeIndent + tmp - 1; - detectedIndent = true; - } else { - throwError(state, 'repeat of an indentation width identifier'); - } - - } else { - break; + this.status = status; + process.nextTick(this.emit.bind(this, status, arg)); +}; +/** + * Create a connection to Redis. + * This method will be invoked automatically when creating a new Redis instance + * unless `lazyConnect: true` is passed. + * + * When calling this method manually, a Promise is returned, which will + * be resolved when the connection status is ready. + * @param {function} [callback] + * @return {Promise} + * @public + */ +Redis.prototype.connect = function (callback) { + const _Promise = PromiseContainer.get(); + const promise = new _Promise((resolve, reject) => { + if (this.status === "connecting" || + this.status === "connect" || + this.status === "ready") { + reject(new Error("Redis is already connecting/connected")); + return; + } + // Make sure only one timer is active at a time + clearInterval(this._addedScriptHashesCleanInterval); + // Start the script cache cleaning + this._addedScriptHashesCleanInterval = setInterval(() => { + this._addedScriptHashes = {}; + }, this.options.maxScriptsCachingTime); + this.connectionEpoch += 1; + this.setStatus("connecting"); + const { options } = this; + this.condition = { + select: options.db, + auth: options.username + ? [options.username, options.password] + : options.password, + subscriber: false, + }; + const _this = this; + standard_as_callback_1.default(this.connector.connect(function (type, err) { + _this.silentEmit(type, err); + }), function (err, stream) { + if (err) { + _this.flushQueue(err); + _this.silentEmit("error", err); + reject(err); + _this.setStatus("end"); + return; + } + let CONNECT_EVENT = options.tls ? "secureConnect" : "connect"; + if (options.sentinels && !options.enableTLSForSentinelMode) { + CONNECT_EVENT = "connect"; + } + _this.stream = stream; + if (typeof options.keepAlive === "number") { + stream.setKeepAlive(true, options.keepAlive); + } + if (stream.connecting) { + stream.once(CONNECT_EVENT, eventHandler.connectHandler(_this)); + if (options.connectTimeout) { + /* + * Typically, Socket#setTimeout(0) will clear the timer + * set before. However, in some platforms (Electron 3.x~4.x), + * the timer will not be cleared. So we introduce a variable here. + * + * See https://github.com/electron/electron/issues/14915 + */ + let connectTimeoutCleared = false; + stream.setTimeout(options.connectTimeout, function () { + if (connectTimeoutCleared) { + return; + } + stream.setTimeout(0); + stream.destroy(); + const err = new Error("connect ETIMEDOUT"); + // @ts-ignore + err.errorno = "ETIMEDOUT"; + // @ts-ignore + err.code = "ETIMEDOUT"; + // @ts-ignore + err.syscall = "connect"; + eventHandler.errorHandler(_this)(err); + }); + stream.once(CONNECT_EVENT, function () { + connectTimeoutCleared = true; + stream.setTimeout(0); + }); + } + } + else if (stream.destroyed) { + const firstError = _this.connector.firstError; + if (firstError) { + process.nextTick(() => { + eventHandler.errorHandler(_this)(firstError); + }); + } + process.nextTick(eventHandler.closeHandler(_this)); + } + else { + process.nextTick(eventHandler.connectHandler(_this)); + } + if (!stream.destroyed) { + stream.once("error", eventHandler.errorHandler(_this)); + stream.once("close", eventHandler.closeHandler(_this)); + } + if (options.noDelay) { + stream.setNoDelay(true); + } + const connectionReadyHandler = function () { + _this.removeListener("close", connectionCloseHandler); + resolve(); + }; + var connectionCloseHandler = function () { + _this.removeListener("ready", connectionReadyHandler); + reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + }; + _this.once("ready", connectionReadyHandler); + _this.once("close", connectionCloseHandler); + }); + }); + return standard_as_callback_1.default(promise, callback); +}; +/** + * Disconnect from Redis. + * + * This method closes the connection immediately, + * and may lose some pending replies that haven't written to client. + * If you want to wait for the pending replies, use Redis#quit instead. + * @public + */ +Redis.prototype.disconnect = function (reconnect) { + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = null; + if (!reconnect) { + this.manuallyClosing = true; } - } - - if (is_WHITE_SPACE(ch)) { - do { ch = state.input.charCodeAt(++state.position); } - while (is_WHITE_SPACE(ch)); - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (!is_EOL(ch) && (ch !== 0)); + if (this.reconnectTimeout && !reconnect) { + clearTimeout(this.reconnectTimeout); + this.reconnectTimeout = null; } - } - - while (ch !== 0) { - readLineBreak(state); - state.lineIndent = 0; - - ch = state.input.charCodeAt(state.position); - - while ((!detectedIndent || state.lineIndent < textIndent) && - (ch === 0x20/* Space */)) { - state.lineIndent++; - ch = state.input.charCodeAt(++state.position); + if (this.status === "wait") { + eventHandler.closeHandler(this)(); } - - if (!detectedIndent && state.lineIndent > textIndent) { - textIndent = state.lineIndent; + else { + this.connector.disconnect(); } - - if (is_EOL(ch)) { - emptyLines++; - continue; +}; +/** + * Disconnect from Redis. + * + * @deprecated + */ +Redis.prototype.end = function () { + this.disconnect(); +}; +/** + * Create a new instance with the same options as the current one. + * + * @example + * ```js + * var redis = new Redis(6380); + * var anotherRedis = redis.duplicate(); + * ``` + * + * @public + */ +Redis.prototype.duplicate = function (override) { + return new Redis(Object.assign({}, this.options, override || {})); +}; +Redis.prototype.recoverFromFatalError = function (commandError, err, options) { + this.flushQueue(err, options); + this.silentEmit("error", err); + this.disconnect(true); +}; +Redis.prototype.handleReconnection = function handleReconnection(err, item) { + let needReconnect = false; + if (this.options.reconnectOnError) { + needReconnect = this.options.reconnectOnError(err); + } + switch (needReconnect) { + case 1: + case true: + if (this.status !== "reconnecting") { + this.disconnect(true); + } + item.command.reject(err); + break; + case 2: + if (this.status !== "reconnecting") { + this.disconnect(true); + } + if (this.condition.select !== item.select && + item.command.name !== "select") { + this.select(item.select); + } + this.sendCommand(item.command); + break; + default: + item.command.reject(err); } - - // End of the scalar. - if (state.lineIndent < textIndent) { - - // Perform the chomping. - if (chomping === CHOMPING_KEEP) { - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - } else if (chomping === CHOMPING_CLIP) { - if (didReadContent) { // i.e. only if the scalar is not empty. - state.result += '\n'; +}; +/** + * Flush offline queue and command queue with error. + * + * @param {Error} error - The error object to send to the commands + * @param {object} options + * @private + */ +Redis.prototype.flushQueue = function (error, options) { + options = lodash_1.defaults({}, options, { + offlineQueue: true, + commandQueue: true, + }); + let item; + if (options.offlineQueue) { + while (this.offlineQueue.length > 0) { + item = this.offlineQueue.shift(); + item.command.reject(error); } - } - - // Break this `while` cycle and go to the funciton's epilogue. - break; } - - // Folded style: use fancy rules to handle line breaks. - if (folding) { - - // Lines starting with white space characters (more-indented lines) are not folded. - if (is_WHITE_SPACE(ch)) { - atMoreIndented = true; - // except for the first content line (cf. Example 8.1) - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); - - // End of more-indented block. - } else if (atMoreIndented) { - atMoreIndented = false; - state.result += common.repeat('\n', emptyLines + 1); - - // Just one line break - perceive as the same line. - } else if (emptyLines === 0) { - if (didReadContent) { // i.e. only if we have already read some scalar content. - state.result += ' '; + if (options.commandQueue) { + if (this.commandQueue.length > 0) { + if (this.stream) { + this.stream.removeAllListeners("data"); + } + while (this.commandQueue.length > 0) { + item = this.commandQueue.shift(); + item.command.reject(error); + } } - - // Several line breaks - perceive as different lines. - } else { - state.result += common.repeat('\n', emptyLines); - } - - // Literal style: just add exact number of line breaks between content lines. - } else { - // Keep all line breaks except the header line break. - state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); } - - didReadContent = true; - detectedIndent = true; - emptyLines = 0; - captureStart = state.position; - - while (!is_EOL(ch) && (ch !== 0)) { - ch = state.input.charCodeAt(++state.position); +}; +/** + * Check whether Redis has finished loading the persistent data and is able to + * process commands. + * + * @param {Function} callback + * @private + */ +Redis.prototype._readyCheck = function (callback) { + const _this = this; + this.info(function (err, res) { + if (err) { + return callback(err); + } + if (typeof res !== "string") { + return callback(null, res); + } + const info = {}; + const lines = res.split("\r\n"); + for (let i = 0; i < lines.length; ++i) { + const [fieldName, ...fieldValueParts] = lines[i].split(":"); + const fieldValue = fieldValueParts.join(":"); + if (fieldValue) { + info[fieldName] = fieldValue; + } + } + if (!info.loading || info.loading === "0") { + callback(null, info); + } + else { + const loadingEtaMs = (info.loading_eta_seconds || 1) * 1000; + const retryTime = _this.options.maxLoadingRetryTime && + _this.options.maxLoadingRetryTime < loadingEtaMs + ? _this.options.maxLoadingRetryTime + : loadingEtaMs; + debug("Redis server still loading, trying again in " + retryTime + "ms"); + setTimeout(function () { + _this._readyCheck(callback); + }, retryTime); + } + }); +}; +/** + * Emit only when there's at least one listener. + * + * @param {string} eventName - Event to emit + * @param {...*} arguments - Arguments + * @return {boolean} Returns true if event had listeners, false otherwise. + * @private + */ +Redis.prototype.silentEmit = function (eventName) { + let error; + if (eventName === "error") { + error = arguments[1]; + if (this.status === "end") { + return; + } + if (this.manuallyClosing) { + // ignore connection related errors when manually disconnecting + if (error instanceof Error && + (error.message === utils_1.CONNECTION_CLOSED_ERROR_MSG || + // @ts-ignore + error.syscall === "connect" || + // @ts-ignore + error.syscall === "read")) { + return; + } + } } - - captureSegment(state, captureStart, state.position, false); - } - - return true; -} - -function readBlockSequence(state, nodeIndent) { - var _line, - _tag = state.tag, - _anchor = state.anchor, - _result = [], - following, - detected = false, - ch; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - - if (ch !== 0x2D/* - */) { - break; + if (this.listeners(eventName).length > 0) { + return this.emit.apply(this, arguments); } - - following = state.input.charCodeAt(state.position + 1); - - if (!is_WS_OR_EOL(following)) { - break; + if (error && error instanceof Error) { + console.error("[ioredis] Unhandled error event:", error.stack); } - - detected = true; - state.position++; - - if (skipSeparationSpace(state, true, -1)) { - if (state.lineIndent <= nodeIndent) { - _result.push(null); - ch = state.input.charCodeAt(state.position); - continue; - } + return false; +}; +/** + * Listen for all requests received by the server in real time. + * + * This command will create a new connection to Redis and send a + * MONITOR command via the new connection in order to avoid disturbing + * the current connection. + * + * @param {function} [callback] The callback function. If omit, a promise will be returned. + * @example + * ```js + * var redis = new Redis(); + * redis.monitor(function (err, monitor) { + * // Entering monitoring mode. + * monitor.on('monitor', function (time, args, source, database) { + * console.log(time + ": " + util.inspect(args)); + * }); + * }); + * + * // supports promise as well as other commands + * redis.monitor().then(function (monitor) { + * monitor.on('monitor', function (time, args, source, database) { + * console.log(time + ": " + util.inspect(args)); + * }); + * }); + * ``` + * @public + */ +Redis.prototype.monitor = function (callback) { + const monitorInstance = this.duplicate({ + monitor: true, + lazyConnect: false, + }); + const Promise = PromiseContainer.get(); + return standard_as_callback_1.default(new Promise(function (resolve) { + monitorInstance.once("monitoring", function () { + resolve(monitorInstance); + }); + }), callback); +}; +transaction_1.addTransactionSupport(Redis.prototype); +/** + * Send a command to Redis + * + * This method is used internally by the `Redis#set`, `Redis#lpush` etc. + * Most of the time you won't invoke this method directly. + * However when you want to send a command that is not supported by ioredis yet, + * this command will be useful. + * + * @method sendCommand + * @memberOf Redis# + * @param {Command} command - The Command instance to send. + * @see {@link Command} + * @example + * ```js + * var redis = new Redis(); + * + * // Use callback + * var get = new Command('get', ['foo'], 'utf8', function (err, result) { + * console.log(result); + * }); + * redis.sendCommand(get); + * + * // Use promise + * var set = new Command('set', ['foo', 'bar'], 'utf8'); + * set.promise.then(function (result) { + * console.log(result); + * }); + * redis.sendCommand(set); + * ``` + * @private + */ +Redis.prototype.sendCommand = function (command, stream) { + if (this.status === "wait") { + this.connect().catch(lodash_1.noop); } - - _line = state.line; - composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); - _result.push(state.result); - skipSeparationSpace(state, true, -1); - - ch = state.input.charCodeAt(state.position); - - if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { - throwError(state, 'bad indentation of a sequence entry'); - } else if (state.lineIndent < nodeIndent) { - break; + if (this.status === "end") { + command.reject(new Error(utils_1.CONNECTION_CLOSED_ERROR_MSG)); + return command.promise; } - } - - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'sequence'; - state.result = _result; - return true; - } - return false; -} - -function readBlockMapping(state, nodeIndent, flowIndent) { - var following, - allowCompact, - _line, - _pos, - _tag = state.tag, - _anchor = state.anchor, - _result = {}, - overridableKeys = {}, - keyTag = null, - keyNode = null, - valueNode = null, - atExplicitKey = false, - detected = false, - ch; - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = _result; - } - - ch = state.input.charCodeAt(state.position); - - while (ch !== 0) { - following = state.input.charCodeAt(state.position + 1); - _line = state.line; // Save the current line. - _pos = state.position; - - // - // Explicit notation case. There are two separate blocks: - // first for the key (denoted by "?") and second for the value (denoted by ":") - // - if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { - - if (ch === 0x3F/* ? */) { - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = true; - allowCompact = true; - - } else if (atExplicitKey) { - // i.e. 0x3A/* : */ === character after the explicit key. - atExplicitKey = false; - allowCompact = true; - - } else { - throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); - } - - state.position += 1; - ch = following; - - // - // Implicit notation case. Flow-style node as the key first, then ":", and the value. - // - } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - - if (state.line === _line) { - ch = state.input.charCodeAt(state.position); - - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x3A/* : */) { - ch = state.input.charCodeAt(++state.position); - - if (!is_WS_OR_EOL(ch)) { - throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); - } - - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - keyTag = keyNode = valueNode = null; - } - - detected = true; - atExplicitKey = false; - allowCompact = false; - keyTag = state.tag; - keyNode = state.result; - - } else if (detected) { - throwError(state, 'can not read an implicit mapping pair; a colon is missed'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else if (detected) { - throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); - - } else { - state.tag = _tag; - state.anchor = _anchor; - return true; // Keep the result of `composeNode`. - } - - } else { - break; // Reading is done. Go to the epilogue. + if (this.condition.subscriber && + !command_1.default.checkFlag("VALID_IN_SUBSCRIBER_MODE", command.name)) { + command.reject(new Error("Connection in subscriber mode, only subscriber commands may be used")); + return command.promise; } - - // - // Common reading code for both explicit and implicit notations. - // - if (state.line === _line || state.lineIndent > nodeIndent) { - if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { - if (atExplicitKey) { - keyNode = state.result; - } else { - valueNode = state.result; - } - } - - if (!atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); - keyTag = keyNode = valueNode = null; - } - - skipSeparationSpace(state, true, -1); - ch = state.input.charCodeAt(state.position); + if (typeof this.options.commandTimeout === "number") { + command.setTimeout(this.options.commandTimeout); } - - if (state.lineIndent > nodeIndent && (ch !== 0)) { - throwError(state, 'bad indentation of a mapping entry'); - } else if (state.lineIndent < nodeIndent) { - break; + if (command.name === "quit") { + clearInterval(this._addedScriptHashesCleanInterval); + this._addedScriptHashesCleanInterval = null; } - } - - // - // Epilogue. - // - - // Special case: last mapping's node contains only the key in explicit notation. - if (atExplicitKey) { - storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); - } - - // Expose the resulting mapping. - if (detected) { - state.tag = _tag; - state.anchor = _anchor; - state.kind = 'mapping'; - state.result = _result; - } - - return detected; -} - -function readTagProperty(state) { - var _position, - isVerbatim = false, - isNamed = false, - tagHandle, - tagName, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x21/* ! */) return false; - - if (state.tag !== null) { - throwError(state, 'duplication of a tag property'); - } - - ch = state.input.charCodeAt(++state.position); - - if (ch === 0x3C/* < */) { - isVerbatim = true; - ch = state.input.charCodeAt(++state.position); - - } else if (ch === 0x21/* ! */) { - isNamed = true; - tagHandle = '!!'; - ch = state.input.charCodeAt(++state.position); - - } else { - tagHandle = '!'; - } - - _position = state.position; - - if (isVerbatim) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && ch !== 0x3E/* > */); - - if (state.position < state.length) { - tagName = state.input.slice(_position, state.position); - ch = state.input.charCodeAt(++state.position); - } else { - throwError(state, 'unexpected end of the stream within a verbatim tag'); + let writable = this.status === "ready" || + (!stream && + this.status === "connect" && + commands.exists(command.name) && + commands.hasFlag(command.name, "loading")); + if (!this.stream) { + writable = false; } - } else { - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - - if (ch === 0x21/* ! */) { - if (!isNamed) { - tagHandle = state.input.slice(_position - 1, state.position + 1); - - if (!PATTERN_TAG_HANDLE.test(tagHandle)) { - throwError(state, 'named tag handle cannot contain such characters'); - } - - isNamed = true; - _position = state.position + 1; - } else { - throwError(state, 'tag suffix cannot contain exclamation marks'); + else if (!this.stream.writable) { + writable = false; + } + else if (this.stream._writableState && this.stream._writableState.ended) { + // https://github.com/iojs/io.js/pull/1217 + writable = false; + } + if (!writable && !this.options.enableOfflineQueue) { + command.reject(new Error("Stream isn't writeable and enableOfflineQueue options is false")); + return command.promise; + } + if (!writable && command.name === "quit" && this.offlineQueue.length === 0) { + this.disconnect(); + command.resolve(Buffer.from("OK")); + return command.promise; + } + if (writable) { + // @ts-ignore + if (debug.enabled) { + debug("write command[%s]: %d -> %s(%o)", this._getDescription(), this.condition.select, command.name, command.args); + } + (stream || this.stream).write(command.toWritable()); + this.commandQueue.push({ + command: command, + stream: stream, + select: this.condition.select, + }); + if (command_1.default.checkFlag("WILL_DISCONNECT", command.name)) { + this.manuallyClosing = true; } - } - - ch = state.input.charCodeAt(++state.position); } - - tagName = state.input.slice(_position, state.position); - - if (PATTERN_FLOW_INDICATORS.test(tagName)) { - throwError(state, 'tag suffix cannot contain flow indicator characters'); + else if (this.options.enableOfflineQueue) { + // @ts-ignore + if (debug.enabled) { + debug("queue command[%s]: %d -> %s(%o)", this._getDescription(), this.condition.select, command.name, command.args); + } + this.offlineQueue.push({ + command: command, + stream: stream, + select: this.condition.select, + }); } - } - - if (tagName && !PATTERN_TAG_URI.test(tagName)) { - throwError(state, 'tag name cannot contain such characters: ' + tagName); - } - - if (isVerbatim) { - state.tag = tagName; - - } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { - state.tag = state.tagMap[tagHandle] + tagName; - - } else if (tagHandle === '!') { - state.tag = '!' + tagName; - - } else if (tagHandle === '!!') { - state.tag = 'tag:yaml.org,2002:' + tagName; - - } else { - throwError(state, 'undeclared tag handle "' + tagHandle + '"'); - } - - return true; -} - -function readAnchorProperty(state) { - var _position, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x26/* & */) return false; - - if (state.anchor !== null) { - throwError(state, 'duplication of an anchor property'); - } - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an anchor node must contain at least one character'); - } - - state.anchor = state.input.slice(_position, state.position); - return true; -} - -function readAlias(state) { - var _position, alias, - ch; - - ch = state.input.charCodeAt(state.position); - - if (ch !== 0x2A/* * */) return false; - - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (state.position === _position) { - throwError(state, 'name of an alias node must contain at least one character'); - } - - alias = state.input.slice(_position, state.position); - - if (!_hasOwnProperty.call(state.anchorMap, alias)) { - throwError(state, 'unidentified alias "' + alias + '"'); - } - - state.result = state.anchorMap[alias]; - skipSeparationSpace(state, true, -1); - return true; -} - -function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { - var allowBlockStyles, - allowBlockScalars, - allowBlockCollections, - indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this { - if (allowToSeek) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; +"use strict"; - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const crypto_1 = __nccwpck_require__(76417); +const promiseContainer_1 = __nccwpck_require__(71475); +const command_1 = __nccwpck_require__(90803); +const standard_as_callback_1 = __nccwpck_require__(91543); +class Script { + constructor(lua, numberOfKeys = null, keyPrefix = "", readOnly = false) { + this.lua = lua; + this.numberOfKeys = numberOfKeys; + this.keyPrefix = keyPrefix; + this.readOnly = readOnly; + this.sha = crypto_1.createHash("sha1").update(lua).digest("hex"); } - } - - if (indentStatus === 1) { - while (readTagProperty(state) || readAnchorProperty(state)) { - if (skipSeparationSpace(state, true, -1)) { - atNewLine = true; - allowBlockCollections = allowBlockStyles; - - if (state.lineIndent > parentIndent) { - indentStatus = 1; - } else if (state.lineIndent === parentIndent) { - indentStatus = 0; - } else if (state.lineIndent < parentIndent) { - indentStatus = -1; + execute(container, args, options, callback) { + if (typeof this.numberOfKeys === "number") { + args.unshift(this.numberOfKeys); } - } else { - allowBlockCollections = false; - } - } - } - - if (allowBlockCollections) { - allowBlockCollections = atNewLine || allowCompact; - } - - if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { - if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { - flowIndent = parentIndent; - } else { - flowIndent = parentIndent + 1; + if (this.keyPrefix) { + options.keyPrefix = this.keyPrefix; + } + if (this.readOnly) { + options.readOnly = true; + } + const evalsha = new command_1.default("evalsha", [this.sha].concat(args), options); + evalsha.isCustomCommand = true; + const result = container.sendCommand(evalsha); + if (promiseContainer_1.isPromise(result)) { + return standard_as_callback_1.default(result.catch((err) => { + if (err.toString().indexOf("NOSCRIPT") === -1) { + throw err; + } + return container.sendCommand(new command_1.default("eval", [this.lua].concat(args), options)); + }), callback); + } + // result is not a Promise--probably returned from a pipeline chain; however, + // we still need the callback to fire when the script is evaluated + standard_as_callback_1.default(evalsha.promise, callback); + return result; } +} +exports.default = Script; - blockIndent = state.position - state.lineStart; - - if (indentStatus === 1) { - if (allowBlockCollections && - (readBlockSequence(state, blockIndent) || - readBlockMapping(state, blockIndent, flowIndent)) || - readFlowCollection(state, flowIndent)) { - hasContent = true; - } else { - if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || - readSingleQuotedScalar(state, flowIndent) || - readDoubleQuotedScalar(state, flowIndent)) { - hasContent = true; - } else if (readAlias(state)) { - hasContent = true; +/***/ }), - if (state.tag !== null || state.anchor !== null) { - throwError(state, 'alias node should not have any properties'); - } +/***/ 14645: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { - hasContent = true; +"use strict"; - if (state.tag === null) { - state.tag = '?'; - } +Object.defineProperty(exports, "__esModule", ({ value: true })); +const utils_1 = __nccwpck_require__(94832); +const standard_as_callback_1 = __nccwpck_require__(91543); +const pipeline_1 = __nccwpck_require__(42803); +function addTransactionSupport(redis) { + redis.pipeline = function (commands) { + const pipeline = new pipeline_1.default(this); + if (Array.isArray(commands)) { + pipeline.addBatch(commands); } - - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; + return pipeline; + }; + const { multi } = redis; + redis.multi = function (commands, options) { + if (typeof options === "undefined" && !Array.isArray(commands)) { + options = commands; + commands = null; } - } - } else if (indentStatus === 0) { - // Special case: block sequences are allowed to have same indentation level as the parent. - // http://www.yaml.org/spec/1.2/spec.html#id2799784 - hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); - } - } + if (options && options.pipeline === false) { + return multi.call(this); + } + const pipeline = new pipeline_1.default(this); + pipeline.multi(); + if (Array.isArray(commands)) { + pipeline.addBatch(commands); + } + const exec = pipeline.exec; + pipeline.exec = function (callback) { + // Wait for the cluster to be connected, since we need nodes information before continuing + if (this.isCluster && !this.redis.slots.length) { + return standard_as_callback_1.default(new Promise((resolve, reject) => { + this.redis.delayUntilReady((err) => { + if (err) { + reject(err); + return; + } + this.exec(pipeline).then(resolve, reject); + }); + }), callback); + } + if (this._transactions > 0) { + exec.call(pipeline); + } + // Returns directly when the pipeline + // has been called multiple times (retries). + if (this.nodeifiedPromise) { + return exec.call(pipeline); + } + const promise = exec.call(pipeline); + return standard_as_callback_1.default(promise.then(function (result) { + const execResult = result[result.length - 1]; + if (typeof execResult === "undefined") { + throw new Error("Pipeline cannot be used to send any commands when the `exec()` has been called on it."); + } + if (execResult[0]) { + execResult[0].previousErrors = []; + for (let i = 0; i < result.length - 1; ++i) { + if (result[i][0]) { + execResult[0].previousErrors.push(result[i][0]); + } + } + throw execResult[0]; + } + return utils_1.wrapMultiResult(execResult[1]); + }), callback); + }; + const { execBuffer } = pipeline; + pipeline.execBuffer = function (callback) { + if (this._transactions > 0) { + execBuffer.call(pipeline); + } + return pipeline.exec(callback); + }; + return pipeline; + }; + const { exec } = redis; + redis.exec = function (callback) { + return standard_as_callback_1.default(exec.call(this).then(function (results) { + if (Array.isArray(results)) { + results = utils_1.wrapMultiResult(results); + } + return results; + }), callback); + }; +} +exports.addTransactionSupport = addTransactionSupport; - if (state.tag !== null && state.tag !== '!') { - if (state.tag === '?') { - // Implicit resolving is not allowed for non-scalar types, and '?' - // non-specific tag is only automatically assigned to plain scalars. - // - // We only need to check kind conformity in case user explicitly assigns '?' - // tag, for example like this: "! [0]" - // - if (state.result !== null && state.kind !== 'scalar') { - throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); - } - for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { - type = state.implicitTypes[typeIndex]; +/***/ }), - if (type.resolve(state.result)) { // `state.result` updated in resolver if matched - state.result = type.construct(state.result); - state.tag = type.tag; - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; - } - break; - } - } - } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { - type = state.typeMap[state.kind || 'fallback'][state.tag]; +/***/ 85356: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - if (state.result !== null && type.kind !== state.kind) { - throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); - } +"use strict"; - if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched - throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); - } else { - state.result = type.construct(state.result); - if (state.anchor !== null) { - state.anchorMap[state.anchor] = state.result; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const debug_1 = __nccwpck_require__(38237); +const MAX_ARGUMENT_LENGTH = 200; +exports.MAX_ARGUMENT_LENGTH = MAX_ARGUMENT_LENGTH; +const NAMESPACE_PREFIX = "ioredis"; +/** + * helper function that tried to get a string value for + * arbitrary "debug" arg + */ +function getStringValue(v) { + if (v === null) { + return; + } + switch (typeof v) { + case "boolean": + return; + case "number": + return; + case "object": + if (Buffer.isBuffer(v)) { + return v.toString("hex"); + } + if (Array.isArray(v)) { + return v.join(","); + } + try { + return JSON.stringify(v); + } + catch (e) { + return; + } + case "string": + return v; + } +} +exports.getStringValue = getStringValue; +/** + * helper function that redacts a string representation of a "debug" arg + */ +function genRedactedString(str, maxLen) { + const { length } = str; + return length <= maxLen + ? str + : str.slice(0, maxLen) + ' ... '; +} +exports.genRedactedString = genRedactedString; +/** + * a wrapper for the `debug` module, used to generate + * "debug functions" that trim the values in their output + */ +function genDebugFunction(namespace) { + const fn = debug_1.default(`${NAMESPACE_PREFIX}:${namespace}`); + function wrappedDebug(...args) { + if (!fn.enabled) { + return; // no-op } - } - } else { - throwError(state, 'unknown tag !<' + state.tag + '>'); + // we skip the first arg because that is the message + for (let i = 1; i < args.length; i++) { + const str = getStringValue(args[i]); + if (typeof str === "string" && str.length > MAX_ARGUMENT_LENGTH) { + args[i] = genRedactedString(str, MAX_ARGUMENT_LENGTH); + } + } + return fn.apply(null, args); } - } - - if (state.listener !== null) { - state.listener('close', state); - } - return state.tag !== null || state.anchor !== null || hasContent; + Object.defineProperties(wrappedDebug, { + namespace: { + get() { + return fn.namespace; + }, + }, + enabled: { + get() { + return fn.enabled; + }, + }, + destroy: { + get() { + return fn.destroy; + }, + }, + log: { + get() { + return fn.log; + }, + set(l) { + fn.log = l; + }, + }, + }); + return wrappedDebug; } +exports.default = genDebugFunction; -function readDocument(state) { - var documentStart = state.position, - _position, - directiveName, - directiveArgs, - hasDirectives = false, - ch; - state.version = null; - state.checkLineBreaks = state.legacy; - state.tagMap = {}; - state.anchorMap = {}; +/***/ }), - while ((ch = state.input.charCodeAt(state.position)) !== 0) { - skipSeparationSpace(state, true, -1); +/***/ 94832: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - ch = state.input.charCodeAt(state.position); +"use strict"; - if (state.lineIndent > 0 || ch !== 0x25/* % */) { - break; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const url_1 = __nccwpck_require__(78835); +const lodash_1 = __nccwpck_require__(20961); +exports.defaults = lodash_1.defaults; +exports.noop = lodash_1.noop; +exports.flatten = lodash_1.flatten; +const debug_1 = __nccwpck_require__(85356); +exports.Debug = debug_1.default; +/** + * Test if two buffers are equal + * + * @export + * @param {Buffer} a + * @param {Buffer} b + * @returns {boolean} Whether the two buffers are equal + */ +function bufferEqual(a, b) { + if (typeof a.equals === "function") { + return a.equals(b); } - - hasDirectives = true; - ch = state.input.charCodeAt(++state.position); - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); + if (a.length !== b.length) { + return false; } - - directiveName = state.input.slice(_position, state.position); - directiveArgs = []; - - if (directiveName.length < 1) { - throwError(state, 'directive name must not be less than one character in length'); + for (let i = 0; i < a.length; ++i) { + if (a[i] !== b[i]) { + return false; + } } - - while (ch !== 0) { - while (is_WHITE_SPACE(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - if (ch === 0x23/* # */) { - do { ch = state.input.charCodeAt(++state.position); } - while (ch !== 0 && !is_EOL(ch)); - break; - } - - if (is_EOL(ch)) break; - - _position = state.position; - - while (ch !== 0 && !is_WS_OR_EOL(ch)) { - ch = state.input.charCodeAt(++state.position); - } - - directiveArgs.push(state.input.slice(_position, state.position)); + return true; +} +exports.bufferEqual = bufferEqual; +/** + * Convert a buffer to string, supports buffer array + * + * @param {*} value - The input value + * @param {string} encoding - string encoding + * @return {*} The result + * @example + * ```js + * var input = [Buffer.from('foo'), [Buffer.from('bar')]] + * var res = convertBufferToString(input, 'utf8') + * expect(res).to.eql(['foo', ['bar']]) + * ``` + * @private + */ +function convertBufferToString(value, encoding) { + if (value instanceof Buffer) { + return value.toString(encoding); } - - if (ch !== 0) readLineBreak(state); - - if (_hasOwnProperty.call(directiveHandlers, directiveName)) { - directiveHandlers[directiveName](state, directiveName, directiveArgs); - } else { - throwWarning(state, 'unknown document directive "' + directiveName + '"'); + if (Array.isArray(value)) { + const length = value.length; + const res = Array(length); + for (let i = 0; i < length; ++i) { + res[i] = + value[i] instanceof Buffer && encoding === "utf8" + ? value[i].toString() + : convertBufferToString(value[i], encoding); + } + return res; } - } - - skipSeparationSpace(state, true, -1); - - if (state.lineIndent === 0 && - state.input.charCodeAt(state.position) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && - state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { - state.position += 3; - skipSeparationSpace(state, true, -1); - - } else if (hasDirectives) { - throwError(state, 'directives end mark is expected'); - } - - composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); - skipSeparationSpace(state, true, -1); - - if (state.checkLineBreaks && - PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { - throwWarning(state, 'non-ASCII line breaks are interpreted as content'); - } - - state.documents.push(state.result); - - if (state.position === state.lineStart && testDocumentSeparator(state)) { - - if (state.input.charCodeAt(state.position) === 0x2E/* . */) { - state.position += 3; - skipSeparationSpace(state, true, -1); + return value; +} +exports.convertBufferToString = convertBufferToString; +/** + * Convert a list of results to node-style + * + * @param {Array} arr - The input value + * @return {Array} The output value + * @example + * ```js + * var input = ['a', 'b', new Error('c'), 'd'] + * var output = exports.wrapMultiResult(input) + * expect(output).to.eql([[null, 'a'], [null, 'b'], [new Error('c')], [null, 'd']) + * ``` + * @private + */ +function wrapMultiResult(arr) { + // When using WATCH/EXEC transactions, the EXEC will return + // a null instead of an array + if (!arr) { + return null; } - return; - } - - if (state.position < (state.length - 1)) { - throwError(state, 'end of the stream or a document separator is expected'); - } else { - return; - } + const result = []; + const length = arr.length; + for (let i = 0; i < length; ++i) { + const item = arr[i]; + if (item instanceof Error) { + result.push([item]); + } + else { + result.push([null, item]); + } + } + return result; } - - -function loadDocuments(input, options) { - input = String(input); - options = options || {}; - - if (input.length !== 0) { - - // Add tailing `\n` if not exists - if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && - input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { - input += '\n'; +exports.wrapMultiResult = wrapMultiResult; +/** + * Detect the argument is a int + * + * @param {string} value + * @return {boolean} Whether the value is a int + * @example + * ```js + * > isInt('123') + * true + * > isInt('123.3') + * false + * > isInt('1x') + * false + * > isInt(123) + * true + * > isInt(true) + * false + * ``` + * @private + */ +function isInt(value) { + const x = parseFloat(value); + return !isNaN(value) && (x | 0) === x; +} +exports.isInt = isInt; +/** + * Pack an array to an Object + * + * @param {array} array + * @return {object} + * @example + * ```js + * > packObject(['a', 'b', 'c', 'd']) + * { a: 'b', c: 'd' } + * ``` + */ +function packObject(array) { + const result = {}; + const length = array.length; + for (let i = 1; i < length; i += 2) { + result[array[i - 1]] = array[i]; } - - // Strip BOM - if (input.charCodeAt(0) === 0xFEFF) { - input = input.slice(1); + return result; +} +exports.packObject = packObject; +/** + * Return a callback with timeout + * + * @param {function} callback + * @param {number} timeout + * @return {function} + */ +function timeout(callback, timeout) { + let timer; + const run = function () { + if (timer) { + clearTimeout(timer); + timer = null; + callback.apply(this, arguments); + } + }; + timer = setTimeout(run, timeout, new Error("timeout")); + return run; +} +exports.timeout = timeout; +/** + * Convert an object to an array + * + * @param {object} obj + * @return {array} + * @example + * ```js + * > convertObjectToArray({ a: '1' }) + * ['a', '1'] + * ``` + */ +function convertObjectToArray(obj) { + const result = []; + const keys = Object.keys(obj); + for (let i = 0, l = keys.length; i < l; i++) { + result.push(keys[i], obj[keys[i]]); } - } - - var state = new State(input, options); - - var nullpos = input.indexOf('\0'); - - if (nullpos !== -1) { - state.position = nullpos; - throwError(state, 'null byte is not allowed in input'); - } - - // Use 0 as string terminator. That significantly simplifies bounds check. - state.input += '\0'; - - while (state.input.charCodeAt(state.position) === 0x20/* Space */) { - state.lineIndent += 1; - state.position += 1; - } - - while (state.position < (state.length - 1)) { - readDocument(state); - } - - return state.documents; + return result; } - - -function loadAll(input, iterator, options) { - if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { - options = iterator; - iterator = null; - } - - var documents = loadDocuments(input, options); - - if (typeof iterator !== 'function') { - return documents; - } - - for (var index = 0, length = documents.length; index < length; index += 1) { - iterator(documents[index]); - } +exports.convertObjectToArray = convertObjectToArray; +/** + * Convert a map to an array + * + * @param {Map} map + * @return {array} + * @example + * ```js + * > convertObjectToArray(new Map([[1, '2']])) + * [1, '2'] + * ``` + */ +function convertMapToArray(map) { + const result = []; + let pos = 0; + map.forEach(function (value, key) { + result[pos] = key; + result[pos + 1] = value; + pos += 2; + }); + return result; } - - -function load(input, options) { - var documents = loadDocuments(input, options); - - if (documents.length === 0) { - /*eslint-disable no-undefined*/ - return undefined; - } else if (documents.length === 1) { - return documents[0]; - } - throw new YAMLException('expected a single document in the stream, but found more'); +exports.convertMapToArray = convertMapToArray; +/** + * Convert a non-string arg to a string + * + * @param {*} arg + * @return {string} + */ +function toArg(arg) { + if (arg === null || typeof arg === "undefined") { + return ""; + } + return String(arg); } - - -function safeLoadAll(input, iterator, options) { - if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { - options = iterator; - iterator = null; - } - - return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +exports.toArg = toArg; +/** + * Optimize error stack + * + * @param {Error} error - actually error + * @param {string} friendlyStack - the stack that more meaningful + * @param {string} filterPath - only show stacks with the specified path + */ +function optimizeErrorStack(error, friendlyStack, filterPath) { + const stacks = friendlyStack.split("\n"); + let lines = ""; + let i; + for (i = 1; i < stacks.length; ++i) { + if (stacks[i].indexOf(filterPath) === -1) { + break; + } + } + for (let j = i; j < stacks.length; ++j) { + lines += "\n" + stacks[j]; + } + const pos = error.stack.indexOf("\n"); + error.stack = error.stack.slice(0, pos) + lines; + return error; +} +exports.optimizeErrorStack = optimizeErrorStack; +/** + * Parse the redis protocol url + * + * @param {string} url - the redis protocol url + * @return {Object} + */ +function parseURL(url) { + if (isInt(url)) { + return { port: url }; + } + let parsed = url_1.parse(url, true, true); + if (!parsed.slashes && url[0] !== "/") { + url = "//" + url; + parsed = url_1.parse(url, true, true); + } + const options = parsed.query || {}; + const allowUsernameInURI = options.allowUsernameInURI && options.allowUsernameInURI !== "false"; + delete options.allowUsernameInURI; + const result = {}; + if (parsed.auth) { + const index = parsed.auth.indexOf(":"); + if (allowUsernameInURI) { + result.username = + index === -1 ? parsed.auth : parsed.auth.slice(0, index); + } + result.password = index === -1 ? "" : parsed.auth.slice(index + 1); + } + if (parsed.pathname) { + if (parsed.protocol === "redis:" || parsed.protocol === "rediss:") { + if (parsed.pathname.length > 1) { + result.db = parsed.pathname.slice(1); + } + } + else { + result.path = parsed.pathname; + } + } + if (parsed.host) { + result.host = parsed.hostname; + } + if (parsed.port) { + result.port = parsed.port; + } + lodash_1.defaults(result, options); + return result; +} +exports.parseURL = parseURL; +/** + * Get a random element from `array` + * + * @export + * @template T + * @param {T[]} array the array + * @param {number} [from=0] start index + * @returns {T} + */ +function sample(array, from = 0) { + const length = array.length; + if (from >= length) { + return; + } + return array[from + Math.floor(Math.random() * (length - from))]; +} +exports.sample = sample; +/** + * Shuffle the array using the Fisher-Yates Shuffle. + * This method will mutate the original array. + * + * @export + * @template T + * @param {T[]} array + * @returns {T[]} + */ +function shuffle(array) { + let counter = array.length; + // While there are elements in the array + while (counter > 0) { + // Pick a random index + const index = Math.floor(Math.random() * counter); + // Decrease counter by 1 + counter--; + // And swap the last element with it + [array[counter], array[index]] = [array[index], array[counter]]; + } + return array; } - - -function safeLoad(input, options) { - return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +exports.shuffle = shuffle; +/** + * Error message for connection being disconnected + */ +exports.CONNECTION_CLOSED_ERROR_MSG = "Connection is closed."; +function zipMap(keys, values) { + const map = new Map(); + keys.forEach((key, index) => { + map.set(key, values[index]); + }); + return map; } - - -module.exports.loadAll = loadAll; -module.exports.load = load; -module.exports.safeLoadAll = safeLoadAll; -module.exports.safeLoad = safeLoad; +exports.zipMap = zipMap; /***/ }), -/***/ 55426: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 20961: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { "use strict"; +Object.defineProperty(exports, "__esModule", ({ value: true })); +const defaults = __nccwpck_require__(11289); +exports.defaults = defaults; +const flatten = __nccwpck_require__(48919); +exports.flatten = flatten; +const isArguments = __nccwpck_require__(44130); +exports.isArguments = isArguments; +function noop() { } +exports.noop = noop; -var common = __nccwpck_require__(59136); - - -function Mark(name, buffer, position, line, column) { - this.name = name; - this.buffer = buffer; - this.position = position; - this.line = line; - this.column = column; -} - +/***/ }), -Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { - var head, start, tail, end, snippet; +/***/ 37263: +/***/ (function(module, __unused_webpack_exports, __nccwpck_require__) { - if (!this.buffer) return null; +/* module decorator */ module = __nccwpck_require__.nmd(module); +(function() { + var expandIPv6, ipaddr, ipv4Part, ipv4Regexes, ipv6Part, ipv6Regexes, matchCIDR, root, zoneIndex; - indent = indent || 4; - maxLength = maxLength || 75; + ipaddr = {}; - head = ''; - start = this.position; + root = this; - while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { - start -= 1; - if (this.position - start > (maxLength / 2 - 1)) { - head = ' ... '; - start += 5; - break; - } + if (( true && module !== null) && module.exports) { + module.exports = ipaddr; + } else { + root['ipaddr'] = ipaddr; } - tail = ''; - end = this.position; - - while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { - end += 1; - if (end - this.position > (maxLength / 2 - 1)) { - tail = ' ... '; - end -= 5; - break; + matchCIDR = function(first, second, partSize, cidrBits) { + var part, shift; + if (first.length !== second.length) { + throw new Error("ipaddr: cannot match CIDR for objects with different lengths"); } - } - - snippet = this.buffer.slice(start, end); - - return common.repeat(' ', indent) + head + snippet + tail + '\n' + - common.repeat(' ', indent + this.position - start + head.length) + '^'; -}; - - -Mark.prototype.toString = function toString(compact) { - var snippet, where = ''; - - if (this.name) { - where += 'in "' + this.name + '" '; - } - - where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); - - if (!compact) { - snippet = this.getSnippet(); - - if (snippet) { - where += ':\n' + snippet; + part = 0; + while (cidrBits > 0) { + shift = partSize - cidrBits; + if (shift < 0) { + shift = 0; + } + if (first[part] >> shift !== second[part] >> shift) { + return false; + } + cidrBits -= partSize; + part += 1; } - } - - return where; -}; - - -module.exports = Mark; + return true; + }; + ipaddr.subnetMatch = function(address, rangeList, defaultName) { + var k, len, rangeName, rangeSubnets, subnet; + if (defaultName == null) { + defaultName = 'unicast'; + } + for (rangeName in rangeList) { + rangeSubnets = rangeList[rangeName]; + if (rangeSubnets[0] && !(rangeSubnets[0] instanceof Array)) { + rangeSubnets = [rangeSubnets]; + } + for (k = 0, len = rangeSubnets.length; k < len; k++) { + subnet = rangeSubnets[k]; + if (address.kind() === subnet[0].kind()) { + if (address.match.apply(address, subnet)) { + return rangeName; + } + } + } + } + return defaultName; + }; -/***/ }), + ipaddr.IPv4 = (function() { + function IPv4(octets) { + var k, len, octet; + if (octets.length !== 4) { + throw new Error("ipaddr: ipv4 octet count should be 4"); + } + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + throw new Error("ipaddr: ipv4 octet should fit in 8 bits"); + } + } + this.octets = octets; + } -/***/ 66514: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + IPv4.prototype.kind = function() { + return 'ipv4'; + }; -"use strict"; + IPv4.prototype.toString = function() { + return this.octets.join("."); + }; + IPv4.prototype.toNormalizedString = function() { + return this.toString(); + }; -/*eslint-disable max-len*/ + IPv4.prototype.toByteArray = function() { + return this.octets.slice(0); + }; -var common = __nccwpck_require__(59136); -var YAMLException = __nccwpck_require__(65199); -var Type = __nccwpck_require__(30967); + IPv4.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv4') { + throw new Error("ipaddr: cannot match ipv4 address with non-ipv4 one"); + } + return matchCIDR(this.octets, other.octets, 8, cidrRange); + }; + IPv4.prototype.SpecialRanges = { + unspecified: [[new IPv4([0, 0, 0, 0]), 8]], + broadcast: [[new IPv4([255, 255, 255, 255]), 32]], + multicast: [[new IPv4([224, 0, 0, 0]), 4]], + linkLocal: [[new IPv4([169, 254, 0, 0]), 16]], + loopback: [[new IPv4([127, 0, 0, 0]), 8]], + carrierGradeNat: [[new IPv4([100, 64, 0, 0]), 10]], + "private": [[new IPv4([10, 0, 0, 0]), 8], [new IPv4([172, 16, 0, 0]), 12], [new IPv4([192, 168, 0, 0]), 16]], + reserved: [[new IPv4([192, 0, 0, 0]), 24], [new IPv4([192, 0, 2, 0]), 24], [new IPv4([192, 88, 99, 0]), 24], [new IPv4([198, 51, 100, 0]), 24], [new IPv4([203, 0, 113, 0]), 24], [new IPv4([240, 0, 0, 0]), 4]] + }; -function compileList(schema, name, result) { - var exclude = []; + IPv4.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; - schema.include.forEach(function (includedSchema) { - result = compileList(includedSchema, name, result); - }); + IPv4.prototype.toIPv4MappedAddress = function() { + return ipaddr.IPv6.parse("::ffff:" + (this.toString())); + }; - schema[name].forEach(function (currentType) { - result.forEach(function (previousType, previousIndex) { - if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { - exclude.push(previousIndex); + IPv4.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, octet, stop, zeros, zerotable; + zerotable = { + 0: 8, + 128: 7, + 192: 6, + 224: 5, + 240: 4, + 248: 3, + 252: 2, + 254: 1, + 255: 0 + }; + cidr = 0; + stop = false; + for (i = k = 3; k >= 0; i = k += -1) { + octet = this.octets[i]; + if (octet in zerotable) { + zeros = zerotable[octet]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 8) { + stop = true; + } + cidr += zeros; + } else { + return null; + } } - }); - - result.push(currentType); - }); - - return result.filter(function (type, index) { - return exclude.indexOf(index) === -1; - }); -} - + return 32 - cidr; + }; -function compileMap(/* lists... */) { - var result = { - scalar: {}, - sequence: {}, - mapping: {}, - fallback: {} - }, index, length; + return IPv4; - function collectType(type) { - result[type.kind][type.tag] = result['fallback'][type.tag] = type; - } + })(); - for (index = 0, length = arguments.length; index < length; index += 1) { - arguments[index].forEach(collectType); - } - return result; -} + ipv4Part = "(0?\\d+|0x[a-f0-9]+)"; + ipv4Regexes = { + fourOctet: new RegExp("^" + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "$", 'i'), + longValue: new RegExp("^" + ipv4Part + "$", 'i') + }; -function Schema(definition) { - this.include = definition.include || []; - this.implicit = definition.implicit || []; - this.explicit = definition.explicit || []; + ipaddr.IPv4.parser = function(string) { + var match, parseIntAuto, part, shift, value; + parseIntAuto = function(string) { + if (string[0] === "0" && string[1] !== "x") { + return parseInt(string, 8); + } else { + return parseInt(string); + } + }; + if (match = string.match(ipv4Regexes.fourOctet)) { + return (function() { + var k, len, ref, results; + ref = match.slice(1, 6); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseIntAuto(part)); + } + return results; + })(); + } else if (match = string.match(ipv4Regexes.longValue)) { + value = parseIntAuto(match[1]); + if (value > 0xffffffff || value < 0) { + throw new Error("ipaddr: address outside defined range"); + } + return ((function() { + var k, results; + results = []; + for (shift = k = 0; k <= 24; shift = k += 8) { + results.push((value >> shift) & 0xff); + } + return results; + })()).reverse(); + } else { + return null; + } + }; - this.implicit.forEach(function (type) { - if (type.loadKind && type.loadKind !== 'scalar') { - throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + ipaddr.IPv6 = (function() { + function IPv6(parts, zoneId) { + var i, k, l, len, part, ref; + if (parts.length === 16) { + this.parts = []; + for (i = k = 0; k <= 14; i = k += 2) { + this.parts.push((parts[i] << 8) | parts[i + 1]); + } + } else if (parts.length === 8) { + this.parts = parts; + } else { + throw new Error("ipaddr: ipv6 part count should be 8 or 16"); + } + ref = this.parts; + for (l = 0, len = ref.length; l < len; l++) { + part = ref[l]; + if (!((0 <= part && part <= 0xffff))) { + throw new Error("ipaddr: ipv6 part should fit in 16 bits"); + } + } + if (zoneId) { + this.zoneId = zoneId; + } } - }); - this.compiledImplicit = compileList(this, 'implicit', []); - this.compiledExplicit = compileList(this, 'explicit', []); - this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); -} + IPv6.prototype.kind = function() { + return 'ipv6'; + }; + IPv6.prototype.toString = function() { + return this.toNormalizedString().replace(/((^|:)(0(:|$))+)/, '::'); + }; -Schema.DEFAULT = null; + IPv6.prototype.toRFC5952String = function() { + var bestMatchIndex, bestMatchLength, match, regex, string; + regex = /((^|:)(0(:|$)){2,})/g; + string = this.toNormalizedString(); + bestMatchIndex = 0; + bestMatchLength = -1; + while ((match = regex.exec(string))) { + if (match[0].length > bestMatchLength) { + bestMatchIndex = match.index; + bestMatchLength = match[0].length; + } + } + if (bestMatchLength < 0) { + return string; + } + return string.substring(0, bestMatchIndex) + '::' + string.substring(bestMatchIndex + bestMatchLength); + }; + IPv6.prototype.toByteArray = function() { + var bytes, k, len, part, ref; + bytes = []; + ref = this.parts; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + bytes.push(part >> 8); + bytes.push(part & 0xff); + } + return bytes; + }; -Schema.create = function createSchema() { - var schemas, types; + IPv6.prototype.toNormalizedString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16)); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; - switch (arguments.length) { - case 1: - schemas = Schema.DEFAULT; - types = arguments[0]; - break; + IPv6.prototype.toFixedLengthString = function() { + var addr, part, suffix; + addr = ((function() { + var k, len, ref, results; + ref = this.parts; + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(part.toString(16).padStart(4, '0')); + } + return results; + }).call(this)).join(":"); + suffix = ''; + if (this.zoneId) { + suffix = '%' + this.zoneId; + } + return addr + suffix; + }; - case 2: - schemas = arguments[0]; - types = arguments[1]; - break; + IPv6.prototype.match = function(other, cidrRange) { + var ref; + if (cidrRange === void 0) { + ref = other, other = ref[0], cidrRange = ref[1]; + } + if (other.kind() !== 'ipv6') { + throw new Error("ipaddr: cannot match ipv6 address with non-ipv6 one"); + } + return matchCIDR(this.parts, other.parts, 16, cidrRange); + }; - default: - throw new YAMLException('Wrong number of arguments for Schema.create function'); - } + IPv6.prototype.SpecialRanges = { + unspecified: [new IPv6([0, 0, 0, 0, 0, 0, 0, 0]), 128], + linkLocal: [new IPv6([0xfe80, 0, 0, 0, 0, 0, 0, 0]), 10], + multicast: [new IPv6([0xff00, 0, 0, 0, 0, 0, 0, 0]), 8], + loopback: [new IPv6([0, 0, 0, 0, 0, 0, 0, 1]), 128], + uniqueLocal: [new IPv6([0xfc00, 0, 0, 0, 0, 0, 0, 0]), 7], + ipv4Mapped: [new IPv6([0, 0, 0, 0, 0, 0xffff, 0, 0]), 96], + rfc6145: [new IPv6([0, 0, 0, 0, 0xffff, 0, 0, 0]), 96], + rfc6052: [new IPv6([0x64, 0xff9b, 0, 0, 0, 0, 0, 0]), 96], + '6to4': [new IPv6([0x2002, 0, 0, 0, 0, 0, 0, 0]), 16], + teredo: [new IPv6([0x2001, 0, 0, 0, 0, 0, 0, 0]), 32], + reserved: [[new IPv6([0x2001, 0xdb8, 0, 0, 0, 0, 0, 0]), 32]] + }; - schemas = common.toArray(schemas); - types = common.toArray(types); + IPv6.prototype.range = function() { + return ipaddr.subnetMatch(this, this.SpecialRanges); + }; - if (!schemas.every(function (schema) { return schema instanceof Schema; })) { - throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); - } + IPv6.prototype.isIPv4MappedAddress = function() { + return this.range() === 'ipv4Mapped'; + }; - if (!types.every(function (type) { return type instanceof Type; })) { - throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); - } + IPv6.prototype.toIPv4Address = function() { + var high, low, ref; + if (!this.isIPv4MappedAddress()) { + throw new Error("ipaddr: trying to convert a generic ipv6 address to ipv4"); + } + ref = this.parts.slice(-2), high = ref[0], low = ref[1]; + return new ipaddr.IPv4([high >> 8, high & 0xff, low >> 8, low & 0xff]); + }; - return new Schema({ - include: schemas, - explicit: types - }); -}; + IPv6.prototype.prefixLengthFromSubnetMask = function() { + var cidr, i, k, part, stop, zeros, zerotable; + zerotable = { + 0: 16, + 32768: 15, + 49152: 14, + 57344: 13, + 61440: 12, + 63488: 11, + 64512: 10, + 65024: 9, + 65280: 8, + 65408: 7, + 65472: 6, + 65504: 5, + 65520: 4, + 65528: 3, + 65532: 2, + 65534: 1, + 65535: 0 + }; + cidr = 0; + stop = false; + for (i = k = 7; k >= 0; i = k += -1) { + part = this.parts[i]; + if (part in zerotable) { + zeros = zerotable[part]; + if (stop && zeros !== 0) { + return null; + } + if (zeros !== 16) { + stop = true; + } + cidr += zeros; + } else { + return null; + } + } + return 128 - cidr; + }; + return IPv6; -module.exports = Schema; + })(); + ipv6Part = "(?:[0-9a-f]+::?)+"; -/***/ }), + zoneIndex = "%[0-9a-z]{1,}"; -/***/ 92183: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + ipv6Regexes = { + zoneIndex: new RegExp(zoneIndex, 'i'), + "native": new RegExp("^(::)?(" + ipv6Part + ")?([0-9a-f]+)?(::)?(" + zoneIndex + ")?$", 'i'), + transitional: new RegExp(("^((?:" + ipv6Part + ")|(?:::)(?:" + ipv6Part + ")?)") + (ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part + "\\." + ipv4Part) + ("(" + zoneIndex + ")?$"), 'i') + }; -"use strict"; -// Standard YAML's Core schema. -// http://www.yaml.org/spec/1.2/spec.html#id2804923 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, Core schema has no distinctions from JSON schema is JS-YAML. + expandIPv6 = function(string, parts) { + var colonCount, lastColon, part, replacement, replacementCount, zoneId; + if (string.indexOf('::') !== string.lastIndexOf('::')) { + return null; + } + zoneId = (string.match(ipv6Regexes['zoneIndex']) || [])[0]; + if (zoneId) { + zoneId = zoneId.substring(1); + string = string.replace(/%.+$/, ''); + } + colonCount = 0; + lastColon = -1; + while ((lastColon = string.indexOf(':', lastColon + 1)) >= 0) { + colonCount++; + } + if (string.substr(0, 2) === '::') { + colonCount--; + } + if (string.substr(-2, 2) === '::') { + colonCount--; + } + if (colonCount > parts) { + return null; + } + replacementCount = parts - colonCount; + replacement = ':'; + while (replacementCount--) { + replacement += '0:'; + } + string = string.replace('::', replacement); + if (string[0] === ':') { + string = string.slice(1); + } + if (string[string.length - 1] === ':') { + string = string.slice(0, -1); + } + parts = (function() { + var k, len, ref, results; + ref = string.split(":"); + results = []; + for (k = 0, len = ref.length; k < len; k++) { + part = ref[k]; + results.push(parseInt(part, 16)); + } + return results; + })(); + return { + parts: parts, + zoneId: zoneId + }; + }; + ipaddr.IPv6.parser = function(string) { + var addr, k, len, match, octet, octets, zoneId; + if (ipv6Regexes['native'].test(string)) { + return expandIPv6(string, 8); + } else if (match = string.match(ipv6Regexes['transitional'])) { + zoneId = match[6] || ''; + addr = expandIPv6(match[1].slice(0, -1) + zoneId, 6); + if (addr.parts) { + octets = [parseInt(match[2]), parseInt(match[3]), parseInt(match[4]), parseInt(match[5])]; + for (k = 0, len = octets.length; k < len; k++) { + octet = octets[k]; + if (!((0 <= octet && octet <= 255))) { + return null; + } + } + addr.parts.push(octets[0] << 8 | octets[1]); + addr.parts.push(octets[2] << 8 | octets[3]); + return { + parts: addr.parts, + zoneId: addr.zoneId + }; + } + } + return null; + }; + ipaddr.IPv4.isIPv4 = ipaddr.IPv6.isIPv6 = function(string) { + return this.parser(string) !== null; + }; + ipaddr.IPv4.isValid = function(string) { + var e; + try { + new this(this.parser(string)); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + ipaddr.IPv4.isValidFourPartDecimal = function(string) { + if (ipaddr.IPv4.isValid(string) && string.match(/^(0|[1-9]\d*)(\.(0|[1-9]\d*)){3}$/)) { + return true; + } else { + return false; + } + }; -var Schema = __nccwpck_require__(66514); + ipaddr.IPv6.isValid = function(string) { + var addr, e; + if (typeof string === "string" && string.indexOf(":") === -1) { + return false; + } + try { + addr = this.parser(string); + new this(addr.parts, addr.zoneId); + return true; + } catch (error1) { + e = error1; + return false; + } + }; + ipaddr.IPv4.parse = function(string) { + var parts; + parts = this.parser(string); + if (parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(parts); + }; -module.exports = new Schema({ - include: [ - __nccwpck_require__(1571) - ] -}); + ipaddr.IPv6.parse = function(string) { + var addr; + addr = this.parser(string); + if (addr.parts === null) { + throw new Error("ipaddr: string is not formatted like ip address"); + } + return new this(addr.parts, addr.zoneId); + }; + ipaddr.IPv4.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 32) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv4 CIDR range"); + }; -/***/ }), + ipaddr.IPv4.subnetMaskFromPrefixLength = function(prefix) { + var filledOctetCount, j, octets; + prefix = parseInt(prefix); + if (prefix < 0 || prefix > 32) { + throw new Error('ipaddr: invalid IPv4 prefix length'); + } + octets = [0, 0, 0, 0]; + j = 0; + filledOctetCount = Math.floor(prefix / 8); + while (j < filledOctetCount) { + octets[j] = 255; + j++; + } + if (filledOctetCount < 4) { + octets[filledOctetCount] = Math.pow(2, prefix % 8) - 1 << 8 - (prefix % 8); + } + return new this(octets); + }; -/***/ 56874: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + ipaddr.IPv4.broadcastAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) | parseInt(subnetMaskOctets[i], 10) ^ 255); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; -"use strict"; -// JS-YAML's default schema for `load` function. -// It is not described in the YAML specification. -// -// This schema is based on JS-YAML's default safe schema and includes -// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. -// -// Also this schema is used as default base schema at `Schema.create` function. + ipaddr.IPv4.networkAddressFromCIDR = function(string) { + var cidr, error, i, ipInterfaceOctets, octets, subnetMaskOctets; + try { + cidr = this.parseCIDR(string); + ipInterfaceOctets = cidr[0].toByteArray(); + subnetMaskOctets = this.subnetMaskFromPrefixLength(cidr[1]).toByteArray(); + octets = []; + i = 0; + while (i < 4) { + octets.push(parseInt(ipInterfaceOctets[i], 10) & parseInt(subnetMaskOctets[i], 10)); + i++; + } + return new this(octets); + } catch (error1) { + error = error1; + throw new Error('ipaddr: the address does not have IPv4 CIDR format'); + } + }; + ipaddr.IPv6.parseCIDR = function(string) { + var maskLength, match, parsed; + if (match = string.match(/^(.+)\/(\d+)$/)) { + maskLength = parseInt(match[2]); + if (maskLength >= 0 && maskLength <= 128) { + parsed = [this.parse(match[1]), maskLength]; + Object.defineProperty(parsed, 'toString', { + value: function() { + return this.join('/'); + } + }); + return parsed; + } + } + throw new Error("ipaddr: string is not formatted like an IPv6 CIDR range"); + }; + ipaddr.isValid = function(string) { + return ipaddr.IPv6.isValid(string) || ipaddr.IPv4.isValid(string); + }; + ipaddr.parse = function(string) { + if (ipaddr.IPv6.isValid(string)) { + return ipaddr.IPv6.parse(string); + } else if (ipaddr.IPv4.isValid(string)) { + return ipaddr.IPv4.parse(string); + } else { + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 format"); + } + }; + ipaddr.parseCIDR = function(string) { + var e; + try { + return ipaddr.IPv6.parseCIDR(string); + } catch (error1) { + e = error1; + try { + return ipaddr.IPv4.parseCIDR(string); + } catch (error1) { + e = error1; + throw new Error("ipaddr: the address has neither IPv6 nor IPv4 CIDR format"); + } + } + }; -var Schema = __nccwpck_require__(66514); + ipaddr.fromByteArray = function(bytes) { + var length; + length = bytes.length; + if (length === 4) { + return new ipaddr.IPv4(bytes); + } else if (length === 16) { + return new ipaddr.IPv6(bytes); + } else { + throw new Error("ipaddr: the binary input is neither an IPv6 nor IPv4 address"); + } + }; + ipaddr.process = function(string) { + var addr; + addr = this.parse(string); + if (addr.kind() === 'ipv6' && addr.isIPv4MappedAddress()) { + return addr.toIPv4Address(); + } else { + return addr; + } + }; -module.exports = Schema.DEFAULT = new Schema({ - include: [ - __nccwpck_require__(48949) - ], - explicit: [ - __nccwpck_require__(25914), - __nccwpck_require__(69242), - __nccwpck_require__(27278) - ] -}); +}).call(this); /***/ }), -/***/ 48949: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 7604: +/***/ ((module) => { "use strict"; -// JS-YAML's default schema for `safeLoad` function. -// It is not described in the YAML specification. -// -// This schema is based on standard YAML's Core schema and includes most of -// extra types described at YAML tag repository. (http://yaml.org/type/) - - - -var Schema = __nccwpck_require__(66514); - +module.exports = function isArrayish(obj) { + if (!obj) { + return false; + } -module.exports = new Schema({ - include: [ - __nccwpck_require__(92183) - ], - implicit: [ - __nccwpck_require__(83714), - __nccwpck_require__(81393) - ], - explicit: [ - __nccwpck_require__(32551), - __nccwpck_require__(96668), - __nccwpck_require__(76039), - __nccwpck_require__(69237) - ] -}); + return obj instanceof Array || Array.isArray(obj) || + (obj.length >= 0 && obj.splice instanceof Function); +}; /***/ }), -/***/ 66037: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +/***/ 31310: +/***/ (function(module, exports) { -"use strict"; -// Standard YAML's Failsafe schema. -// http://www.yaml.org/spec/1.2/spec.html#id2802346 +;(function(root) { + 'use strict'; + + function isBase64(v, opts) { + if (v instanceof Boolean || typeof v === 'boolean') { + return false + } + if (!(opts instanceof Object)) { + opts = {} + } + if (opts.allowEmpty === false && v === '') { + return false + } + var regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}==|[A-Za-z0-9+\/]{3}=)?' + var mimeRegex = '(data:\\w+\\/[a-zA-Z\\+\\-\\.]+;base64,)' + if (opts.mimeRequired === true) { + regex = mimeRegex + regex + } else if (opts.allowMime === true) { + regex = mimeRegex + '?' + regex + } -var Schema = __nccwpck_require__(66514); + if (opts.paddingRequired === false) { + regex = '(?:[A-Za-z0-9+\\/]{4})*(?:[A-Za-z0-9+\\/]{2}(==)?|[A-Za-z0-9+\\/]{3}=?)?' + } + return (new RegExp('^' + regex + '$', 'gi')).test(v) + } -module.exports = new Schema({ - explicit: [ - __nccwpck_require__(52672), - __nccwpck_require__(5490), - __nccwpck_require__(31173) - ] -}); + if (true) { + if ( true && module.exports) { + exports = module.exports = isBase64 + } + exports.isBase64 = isBase64 + } else {} +})(this); /***/ }), -/***/ 1571: +/***/ 56873: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -// Standard YAML's JSON schema. -// http://www.yaml.org/spec/1.2/spec.html#id2803231 -// -// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. -// So, this schema is not such strict as defined in the YAML specification. -// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. +var has = __nccwpck_require__(76339); +function specifierIncluded(current, specifier) { + var nodeParts = current.split('.'); + var parts = specifier.split(' '); + var op = parts.length > 1 ? parts[0] : '='; + var versionParts = (parts.length > 1 ? parts[1] : parts[0]).split('.'); + for (var i = 0; i < 3; ++i) { + var cur = parseInt(nodeParts[i] || 0, 10); + var ver = parseInt(versionParts[i] || 0, 10); + if (cur === ver) { + continue; // eslint-disable-line no-restricted-syntax, no-continue + } + if (op === '<') { + return cur < ver; + } + if (op === '>=') { + return cur >= ver; + } + return false; + } + return op === '>='; +} -var Schema = __nccwpck_require__(66514); +function matchesRange(current, range) { + var specifiers = range.split(/ ?&& ?/); + if (specifiers.length === 0) { + return false; + } + for (var i = 0; i < specifiers.length; ++i) { + if (!specifierIncluded(current, specifiers[i])) { + return false; + } + } + return true; +} +function versionIncluded(nodeVersion, specifierValue) { + if (typeof specifierValue === 'boolean') { + return specifierValue; + } -module.exports = new Schema({ - include: [ - __nccwpck_require__(66037) - ], - implicit: [ - __nccwpck_require__(22671), - __nccwpck_require__(94675), - __nccwpck_require__(89963), - __nccwpck_require__(15564) - ] -}); + var current = typeof nodeVersion === 'undefined' + ? process.versions && process.versions.node + : nodeVersion; + if (typeof current !== 'string') { + throw new TypeError(typeof nodeVersion === 'undefined' ? 'Unable to determine current node version' : 'If provided, a valid node version is required'); + } -/***/ }), + if (specifierValue && typeof specifierValue === 'object') { + for (var i = 0; i < specifierValue.length; ++i) { + if (matchesRange(current, specifierValue[i])) { + return true; + } + } + return false; + } + return matchesRange(current, specifierValue); +} -/***/ 30967: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var data = __nccwpck_require__(93991); -"use strict"; +module.exports = function isCore(x, nodeVersion) { + return has(data, x) && versionIncluded(nodeVersion, data[x]); +}; -var YAMLException = __nccwpck_require__(65199); +/***/ }), -var TYPE_CONSTRUCTOR_OPTIONS = [ - 'kind', - 'resolve', - 'construct', - 'instanceOf', - 'predicate', - 'represent', - 'defaultStyle', - 'styleAliases' -]; +/***/ 63287: +/***/ ((__unused_webpack_module, exports) => { -var YAML_NODE_KINDS = [ - 'scalar', - 'sequence', - 'mapping' -]; +"use strict"; -function compileStyleAliases(map) { - var result = {}; - if (map !== null) { - Object.keys(map).forEach(function (style) { - map[style].forEach(function (alias) { - result[String(alias)] = style; - }); - }); - } +Object.defineProperty(exports, "__esModule", ({ value: true })); - return result; +/*! + * is-plain-object + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +function isObject(o) { + return Object.prototype.toString.call(o) === '[object Object]'; } -function Type(tag, options) { - options = options || {}; +function isPlainObject(o) { + var ctor,prot; - Object.keys(options).forEach(function (name) { - if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { - throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); - } - }); + if (isObject(o) === false) return false; - // TODO: Add tag format check. - this.tag = tag; - this.kind = options['kind'] || null; - this.resolve = options['resolve'] || function () { return true; }; - this.construct = options['construct'] || function (data) { return data; }; - this.instanceOf = options['instanceOf'] || null; - this.predicate = options['predicate'] || null; - this.represent = options['represent'] || null; - this.defaultStyle = options['defaultStyle'] || null; - this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + // If has modified constructor + ctor = o.constructor; + if (ctor === undefined) return true; - if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { - throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + // 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; } + + // Most likely a plain Object + return true; } -module.exports = Type; +exports.isPlainObject = isPlainObject; /***/ }), -/***/ 32551: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; +/***/ 87783: +/***/ ((__unused_webpack_module, exports) => { +(function(exports) { + "use strict"; -/*eslint-disable no-bitwise*/ + function isArray(obj) { + if (obj !== null) { + return Object.prototype.toString.call(obj) === "[object Array]"; + } else { + return false; + } + } -var NodeBuffer; + function isObject(obj) { + if (obj !== null) { + return Object.prototype.toString.call(obj) === "[object Object]"; + } else { + return false; + } + } -try { - // A trick for browserified version, to not include `Buffer` shim - var _require = require; - NodeBuffer = _require('buffer').Buffer; -} catch (__) {} + function strictDeepEqual(first, second) { + // Check the scalar case first. + if (first === second) { + return true; + } -var Type = __nccwpck_require__(30967); + // Check if they are the same type. + var firstType = Object.prototype.toString.call(first); + if (firstType !== Object.prototype.toString.call(second)) { + return false; + } + // We know that first and second have the same type so we can just check the + // first type from now on. + if (isArray(first) === true) { + // Short circuit if they're not the same length; + if (first.length !== second.length) { + return false; + } + for (var i = 0; i < first.length; i++) { + if (strictDeepEqual(first[i], second[i]) === false) { + return false; + } + } + return true; + } + if (isObject(first) === true) { + // An object is equal if it has the same key/value pairs. + var keysSeen = {}; + for (var key in first) { + if (hasOwnProperty.call(first, key)) { + if (strictDeepEqual(first[key], second[key]) === false) { + return false; + } + keysSeen[key] = true; + } + } + // Now check that there aren't any keys in second that weren't + // in first. + for (var key2 in second) { + if (hasOwnProperty.call(second, key2)) { + if (keysSeen[key2] !== true) { + return false; + } + } + } + return true; + } + return false; + } + function isFalse(obj) { + // From the spec: + // A false value corresponds to the following values: + // Empty list + // Empty object + // Empty string + // False boolean + // null value -// [ 64, 65, 66 ] -> [ padding, CR, LF ] -var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; + // First check the scalar values. + if (obj === "" || obj === false || obj === null) { + return true; + } else if (isArray(obj) && obj.length === 0) { + // Check for an empty array. + return true; + } else if (isObject(obj)) { + // Check for an empty object. + for (var key in obj) { + // If there are any keys, then + // the object is not empty so the object + // is not false. + if (obj.hasOwnProperty(key)) { + return false; + } + } + return true; + } else { + return false; + } + } + function objValues(obj) { + var keys = Object.keys(obj); + var values = []; + for (var i = 0; i < keys.length; i++) { + values.push(obj[keys[i]]); + } + return values; + } -function resolveYamlBinary(data) { - if (data === null) return false; + function merge(a, b) { + var merged = {}; + for (var key in a) { + merged[key] = a[key]; + } + for (var key2 in b) { + merged[key2] = b[key2]; + } + return merged; + } - var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + var trimLeft; + if (typeof String.prototype.trimLeft === "function") { + trimLeft = function(str) { + return str.trimLeft(); + }; + } else { + trimLeft = function(str) { + return str.match(/^\s*(.*)/)[1]; + }; + } - // Convert one by one. - for (idx = 0; idx < max; idx++) { - code = map.indexOf(data.charAt(idx)); + // Type constants used to define functions. + var TYPE_NUMBER = 0; + var TYPE_ANY = 1; + var TYPE_STRING = 2; + var TYPE_ARRAY = 3; + var TYPE_OBJECT = 4; + var TYPE_BOOLEAN = 5; + var TYPE_EXPREF = 6; + var TYPE_NULL = 7; + var TYPE_ARRAY_NUMBER = 8; + var TYPE_ARRAY_STRING = 9; - // Skip CR/LF - if (code > 64) continue; + var TOK_EOF = "EOF"; + var TOK_UNQUOTEDIDENTIFIER = "UnquotedIdentifier"; + var TOK_QUOTEDIDENTIFIER = "QuotedIdentifier"; + var TOK_RBRACKET = "Rbracket"; + var TOK_RPAREN = "Rparen"; + var TOK_COMMA = "Comma"; + var TOK_COLON = "Colon"; + var TOK_RBRACE = "Rbrace"; + var TOK_NUMBER = "Number"; + var TOK_CURRENT = "Current"; + var TOK_EXPREF = "Expref"; + var TOK_PIPE = "Pipe"; + var TOK_OR = "Or"; + var TOK_AND = "And"; + var TOK_EQ = "EQ"; + var TOK_GT = "GT"; + var TOK_LT = "LT"; + var TOK_GTE = "GTE"; + var TOK_LTE = "LTE"; + var TOK_NE = "NE"; + var TOK_FLATTEN = "Flatten"; + var TOK_STAR = "Star"; + var TOK_FILTER = "Filter"; + var TOK_DOT = "Dot"; + var TOK_NOT = "Not"; + var TOK_LBRACE = "Lbrace"; + var TOK_LBRACKET = "Lbracket"; + var TOK_LPAREN= "Lparen"; + var TOK_LITERAL= "Literal"; - // Fail on illegal characters - if (code < 0) return false; + // The "&", "[", "<", ">" tokens + // are not in basicToken because + // there are two token variants + // ("&&", "[?", "<=", ">="). This is specially handled + // below. - bitlen += 6; - } + var basicTokens = { + ".": TOK_DOT, + "*": TOK_STAR, + ",": TOK_COMMA, + ":": TOK_COLON, + "{": TOK_LBRACE, + "}": TOK_RBRACE, + "]": TOK_RBRACKET, + "(": TOK_LPAREN, + ")": TOK_RPAREN, + "@": TOK_CURRENT + }; - // If there are any bits left, source was corrupted - return (bitlen % 8) === 0; -} + var operatorStartToken = { + "<": true, + ">": true, + "=": true, + "!": true + }; -function constructYamlBinary(data) { - var idx, tailbits, - input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan - max = input.length, - map = BASE64_MAP, - bits = 0, - result = []; + var skipChars = { + " ": true, + "\t": true, + "\n": true + }; - // Collect by 6*4 bits (3 bytes) - for (idx = 0; idx < max; idx++) { - if ((idx % 4 === 0) && idx) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } + function isAlpha(ch) { + return (ch >= "a" && ch <= "z") || + (ch >= "A" && ch <= "Z") || + ch === "_"; + } - bits = (bits << 6) | map.indexOf(input.charAt(idx)); + function isNum(ch) { + return (ch >= "0" && ch <= "9") || + ch === "-"; + } + function isAlphaNum(ch) { + return (ch >= "a" && ch <= "z") || + (ch >= "A" && ch <= "Z") || + (ch >= "0" && ch <= "9") || + ch === "_"; } - // Dump tail + function Lexer() { + } + Lexer.prototype = { + tokenize: function(stream) { + var tokens = []; + this._current = 0; + var start; + var identifier; + var token; + while (this._current < stream.length) { + if (isAlpha(stream[this._current])) { + start = this._current; + identifier = this._consumeUnquotedIdentifier(stream); + tokens.push({type: TOK_UNQUOTEDIDENTIFIER, + value: identifier, + start: start}); + } else if (basicTokens[stream[this._current]] !== undefined) { + tokens.push({type: basicTokens[stream[this._current]], + value: stream[this._current], + start: this._current}); + this._current++; + } else if (isNum(stream[this._current])) { + token = this._consumeNumber(stream); + tokens.push(token); + } else if (stream[this._current] === "[") { + // No need to increment this._current. This happens + // in _consumeLBracket + token = this._consumeLBracket(stream); + tokens.push(token); + } else if (stream[this._current] === "\"") { + start = this._current; + identifier = this._consumeQuotedIdentifier(stream); + tokens.push({type: TOK_QUOTEDIDENTIFIER, + value: identifier, + start: start}); + } else if (stream[this._current] === "'") { + start = this._current; + identifier = this._consumeRawStringLiteral(stream); + tokens.push({type: TOK_LITERAL, + value: identifier, + start: start}); + } else if (stream[this._current] === "`") { + start = this._current; + var literal = this._consumeLiteral(stream); + tokens.push({type: TOK_LITERAL, + value: literal, + start: start}); + } else if (operatorStartToken[stream[this._current]] !== undefined) { + tokens.push(this._consumeOperator(stream)); + } else if (skipChars[stream[this._current]] !== undefined) { + // Ignore whitespace. + this._current++; + } else if (stream[this._current] === "&") { + start = this._current; + this._current++; + if (stream[this._current] === "&") { + this._current++; + tokens.push({type: TOK_AND, value: "&&", start: start}); + } else { + tokens.push({type: TOK_EXPREF, value: "&", start: start}); + } + } else if (stream[this._current] === "|") { + start = this._current; + this._current++; + if (stream[this._current] === "|") { + this._current++; + tokens.push({type: TOK_OR, value: "||", start: start}); + } else { + tokens.push({type: TOK_PIPE, value: "|", start: start}); + } + } else { + var error = new Error("Unknown character:" + stream[this._current]); + error.name = "LexerError"; + throw error; + } + } + return tokens; + }, - tailbits = (max % 4) * 6; + _consumeUnquotedIdentifier: function(stream) { + var start = this._current; + this._current++; + while (this._current < stream.length && isAlphaNum(stream[this._current])) { + this._current++; + } + return stream.slice(start, this._current); + }, - if (tailbits === 0) { - result.push((bits >> 16) & 0xFF); - result.push((bits >> 8) & 0xFF); - result.push(bits & 0xFF); - } else if (tailbits === 18) { - result.push((bits >> 10) & 0xFF); - result.push((bits >> 2) & 0xFF); - } else if (tailbits === 12) { - result.push((bits >> 4) & 0xFF); - } + _consumeQuotedIdentifier: function(stream) { + var start = this._current; + this._current++; + var maxLength = stream.length; + while (stream[this._current] !== "\"" && this._current < maxLength) { + // You can escape a double quote and you can escape an escape. + var current = this._current; + if (stream[current] === "\\" && (stream[current + 1] === "\\" || + stream[current + 1] === "\"")) { + current += 2; + } else { + current++; + } + this._current = current; + } + this._current++; + return JSON.parse(stream.slice(start, this._current)); + }, - // Wrap into Buffer for NodeJS and leave Array for browser - if (NodeBuffer) { - // Support node 6.+ Buffer API when available - return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); - } + _consumeRawStringLiteral: function(stream) { + var start = this._current; + this._current++; + var maxLength = stream.length; + while (stream[this._current] !== "'" && this._current < maxLength) { + // You can escape a single quote and you can escape an escape. + var current = this._current; + if (stream[current] === "\\" && (stream[current + 1] === "\\" || + stream[current + 1] === "'")) { + current += 2; + } else { + current++; + } + this._current = current; + } + this._current++; + var literal = stream.slice(start + 1, this._current - 1); + return literal.replace("\\'", "'"); + }, - return result; -} + _consumeNumber: function(stream) { + var start = this._current; + this._current++; + var maxLength = stream.length; + while (isNum(stream[this._current]) && this._current < maxLength) { + this._current++; + } + var value = parseInt(stream.slice(start, this._current)); + return {type: TOK_NUMBER, value: value, start: start}; + }, -function representYamlBinary(object /*, style*/) { - var result = '', bits = 0, idx, tail, - max = object.length, - map = BASE64_MAP; + _consumeLBracket: function(stream) { + var start = this._current; + this._current++; + if (stream[this._current] === "?") { + this._current++; + return {type: TOK_FILTER, value: "[?", start: start}; + } else if (stream[this._current] === "]") { + this._current++; + return {type: TOK_FLATTEN, value: "[]", start: start}; + } else { + return {type: TOK_LBRACKET, value: "[", start: start}; + } + }, - // Convert every three bytes to 4 ASCII characters. + _consumeOperator: function(stream) { + var start = this._current; + var startingChar = stream[start]; + this._current++; + if (startingChar === "!") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_NE, value: "!=", start: start}; + } else { + return {type: TOK_NOT, value: "!", start: start}; + } + } else if (startingChar === "<") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_LTE, value: "<=", start: start}; + } else { + return {type: TOK_LT, value: "<", start: start}; + } + } else if (startingChar === ">") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_GTE, value: ">=", start: start}; + } else { + return {type: TOK_GT, value: ">", start: start}; + } + } else if (startingChar === "=") { + if (stream[this._current] === "=") { + this._current++; + return {type: TOK_EQ, value: "==", start: start}; + } + } + }, - for (idx = 0; idx < max; idx++) { - if ((idx % 3 === 0) && idx) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } + _consumeLiteral: function(stream) { + this._current++; + var start = this._current; + var maxLength = stream.length; + var literal; + while(stream[this._current] !== "`" && this._current < maxLength) { + // You can escape a literal char or you can escape the escape. + var current = this._current; + if (stream[current] === "\\" && (stream[current + 1] === "\\" || + stream[current + 1] === "`")) { + current += 2; + } else { + current++; + } + this._current = current; + } + var literalString = trimLeft(stream.slice(start, this._current)); + literalString = literalString.replace("\\`", "`"); + if (this._looksLikeJSON(literalString)) { + literal = JSON.parse(literalString); + } else { + // Try to JSON parse it as "" + literal = JSON.parse("\"" + literalString + "\""); + } + // +1 gets us to the ending "`", +1 to move on to the next char. + this._current++; + return literal; + }, - bits = (bits << 8) + object[idx]; - } + _looksLikeJSON: function(literalString) { + var startingChars = "[{\""; + var jsonLiterals = ["true", "false", "null"]; + var numberLooking = "-0123456789"; - // Dump tail + if (literalString === "") { + return false; + } else if (startingChars.indexOf(literalString[0]) >= 0) { + return true; + } else if (jsonLiterals.indexOf(literalString) >= 0) { + return true; + } else if (numberLooking.indexOf(literalString[0]) >= 0) { + try { + JSON.parse(literalString); + return true; + } catch (ex) { + return false; + } + } else { + return false; + } + } + }; - tail = max % 3; + var bindingPower = {}; + bindingPower[TOK_EOF] = 0; + bindingPower[TOK_UNQUOTEDIDENTIFIER] = 0; + bindingPower[TOK_QUOTEDIDENTIFIER] = 0; + bindingPower[TOK_RBRACKET] = 0; + bindingPower[TOK_RPAREN] = 0; + bindingPower[TOK_COMMA] = 0; + bindingPower[TOK_RBRACE] = 0; + bindingPower[TOK_NUMBER] = 0; + bindingPower[TOK_CURRENT] = 0; + bindingPower[TOK_EXPREF] = 0; + bindingPower[TOK_PIPE] = 1; + bindingPower[TOK_OR] = 2; + bindingPower[TOK_AND] = 3; + bindingPower[TOK_EQ] = 5; + bindingPower[TOK_GT] = 5; + bindingPower[TOK_LT] = 5; + bindingPower[TOK_GTE] = 5; + bindingPower[TOK_LTE] = 5; + bindingPower[TOK_NE] = 5; + bindingPower[TOK_FLATTEN] = 9; + bindingPower[TOK_STAR] = 20; + bindingPower[TOK_FILTER] = 21; + bindingPower[TOK_DOT] = 40; + bindingPower[TOK_NOT] = 45; + bindingPower[TOK_LBRACE] = 50; + bindingPower[TOK_LBRACKET] = 55; + bindingPower[TOK_LPAREN] = 60; - if (tail === 0) { - result += map[(bits >> 18) & 0x3F]; - result += map[(bits >> 12) & 0x3F]; - result += map[(bits >> 6) & 0x3F]; - result += map[bits & 0x3F]; - } else if (tail === 2) { - result += map[(bits >> 10) & 0x3F]; - result += map[(bits >> 4) & 0x3F]; - result += map[(bits << 2) & 0x3F]; - result += map[64]; - } else if (tail === 1) { - result += map[(bits >> 2) & 0x3F]; - result += map[(bits << 4) & 0x3F]; - result += map[64]; - result += map[64]; + function Parser() { } - return result; -} - -function isBinary(object) { - return NodeBuffer && NodeBuffer.isBuffer(object); -} - -module.exports = new Type('tag:yaml.org,2002:binary', { - kind: 'scalar', - resolve: resolveYamlBinary, - construct: constructYamlBinary, - predicate: isBinary, - represent: representYamlBinary -}); - + Parser.prototype = { + parse: function(expression) { + this._loadTokens(expression); + this.index = 0; + var ast = this.expression(0); + if (this._lookahead(0) !== TOK_EOF) { + var t = this._lookaheadToken(0); + var error = new Error( + "Unexpected token type: " + t.type + ", value: " + t.value); + error.name = "ParserError"; + throw error; + } + return ast; + }, -/***/ }), + _loadTokens: function(expression) { + var lexer = new Lexer(); + var tokens = lexer.tokenize(expression); + tokens.push({type: TOK_EOF, value: "", start: expression.length}); + this.tokens = tokens; + }, -/***/ 94675: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + expression: function(rbp) { + var leftToken = this._lookaheadToken(0); + this._advance(); + var left = this.nud(leftToken); + var currentToken = this._lookahead(0); + while (rbp < bindingPower[currentToken]) { + this._advance(); + left = this.led(currentToken, left); + currentToken = this._lookahead(0); + } + return left; + }, -"use strict"; + _lookahead: function(number) { + return this.tokens[this.index + number].type; + }, + _lookaheadToken: function(number) { + return this.tokens[this.index + number]; + }, -var Type = __nccwpck_require__(30967); + _advance: function() { + this.index++; + }, -function resolveYamlBoolean(data) { - if (data === null) return false; + nud: function(token) { + var left; + var right; + var expression; + switch (token.type) { + case TOK_LITERAL: + return {type: "Literal", value: token.value}; + case TOK_UNQUOTEDIDENTIFIER: + return {type: "Field", name: token.value}; + case TOK_QUOTEDIDENTIFIER: + var node = {type: "Field", name: token.value}; + if (this._lookahead(0) === TOK_LPAREN) { + throw new Error("Quoted identifier not allowed for function names."); + } else { + return node; + } + break; + case TOK_NOT: + right = this.expression(bindingPower.Not); + return {type: "NotExpression", children: [right]}; + case TOK_STAR: + left = {type: "Identity"}; + right = null; + if (this._lookahead(0) === TOK_RBRACKET) { + // This can happen in a multiselect, + // [a, b, *] + right = {type: "Identity"}; + } else { + right = this._parseProjectionRHS(bindingPower.Star); + } + return {type: "ValueProjection", children: [left, right]}; + case TOK_FILTER: + return this.led(token.type, {type: "Identity"}); + case TOK_LBRACE: + return this._parseMultiselectHash(); + case TOK_FLATTEN: + left = {type: TOK_FLATTEN, children: [{type: "Identity"}]}; + right = this._parseProjectionRHS(bindingPower.Flatten); + return {type: "Projection", children: [left, right]}; + case TOK_LBRACKET: + if (this._lookahead(0) === TOK_NUMBER || this._lookahead(0) === TOK_COLON) { + right = this._parseIndexExpression(); + return this._projectIfSlice({type: "Identity"}, right); + } else if (this._lookahead(0) === TOK_STAR && + this._lookahead(1) === TOK_RBRACKET) { + this._advance(); + this._advance(); + right = this._parseProjectionRHS(bindingPower.Star); + return {type: "Projection", + children: [{type: "Identity"}, right]}; + } else { + return this._parseMultiselectList(); + } + break; + case TOK_CURRENT: + return {type: TOK_CURRENT}; + case TOK_EXPREF: + expression = this.expression(bindingPower.Expref); + return {type: "ExpressionReference", children: [expression]}; + case TOK_LPAREN: + var args = []; + while (this._lookahead(0) !== TOK_RPAREN) { + if (this._lookahead(0) === TOK_CURRENT) { + expression = {type: TOK_CURRENT}; + this._advance(); + } else { + expression = this.expression(0); + } + args.push(expression); + } + this._match(TOK_RPAREN); + return args[0]; + default: + this._errorToken(token); + } + }, - var max = data.length; + led: function(tokenName, left) { + var right; + switch(tokenName) { + case TOK_DOT: + var rbp = bindingPower.Dot; + if (this._lookahead(0) !== TOK_STAR) { + right = this._parseDotRHS(rbp); + return {type: "Subexpression", children: [left, right]}; + } else { + // Creating a projection. + this._advance(); + right = this._parseProjectionRHS(rbp); + return {type: "ValueProjection", children: [left, right]}; + } + break; + case TOK_PIPE: + right = this.expression(bindingPower.Pipe); + return {type: TOK_PIPE, children: [left, right]}; + case TOK_OR: + right = this.expression(bindingPower.Or); + return {type: "OrExpression", children: [left, right]}; + case TOK_AND: + right = this.expression(bindingPower.And); + return {type: "AndExpression", children: [left, right]}; + case TOK_LPAREN: + var name = left.name; + var args = []; + var expression, node; + while (this._lookahead(0) !== TOK_RPAREN) { + if (this._lookahead(0) === TOK_CURRENT) { + expression = {type: TOK_CURRENT}; + this._advance(); + } else { + expression = this.expression(0); + } + if (this._lookahead(0) === TOK_COMMA) { + this._match(TOK_COMMA); + } + args.push(expression); + } + this._match(TOK_RPAREN); + node = {type: "Function", name: name, children: args}; + return node; + case TOK_FILTER: + var condition = this.expression(0); + this._match(TOK_RBRACKET); + if (this._lookahead(0) === TOK_FLATTEN) { + right = {type: "Identity"}; + } else { + right = this._parseProjectionRHS(bindingPower.Filter); + } + return {type: "FilterProjection", children: [left, right, condition]}; + case TOK_FLATTEN: + var leftNode = {type: TOK_FLATTEN, children: [left]}; + var rightNode = this._parseProjectionRHS(bindingPower.Flatten); + return {type: "Projection", children: [leftNode, rightNode]}; + case TOK_EQ: + case TOK_NE: + case TOK_GT: + case TOK_GTE: + case TOK_LT: + case TOK_LTE: + return this._parseComparator(left, tokenName); + case TOK_LBRACKET: + var token = this._lookaheadToken(0); + if (token.type === TOK_NUMBER || token.type === TOK_COLON) { + right = this._parseIndexExpression(); + return this._projectIfSlice(left, right); + } else { + this._match(TOK_STAR); + this._match(TOK_RBRACKET); + right = this._parseProjectionRHS(bindingPower.Star); + return {type: "Projection", children: [left, right]}; + } + break; + default: + this._errorToken(this._lookaheadToken(0)); + } + }, - return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || - (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); -} + _match: function(tokenType) { + if (this._lookahead(0) === tokenType) { + this._advance(); + } else { + var t = this._lookaheadToken(0); + var error = new Error("Expected " + tokenType + ", got: " + t.type); + error.name = "ParserError"; + throw error; + } + }, -function constructYamlBoolean(data) { - return data === 'true' || - data === 'True' || - data === 'TRUE'; -} + _errorToken: function(token) { + var error = new Error("Invalid token (" + + token.type + "): \"" + + token.value + "\""); + error.name = "ParserError"; + throw error; + }, -function isBoolean(object) { - return Object.prototype.toString.call(object) === '[object Boolean]'; -} -module.exports = new Type('tag:yaml.org,2002:bool', { - kind: 'scalar', - resolve: resolveYamlBoolean, - construct: constructYamlBoolean, - predicate: isBoolean, - represent: { - lowercase: function (object) { return object ? 'true' : 'false'; }, - uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, - camelcase: function (object) { return object ? 'True' : 'False'; } - }, - defaultStyle: 'lowercase' -}); + _parseIndexExpression: function() { + if (this._lookahead(0) === TOK_COLON || this._lookahead(1) === TOK_COLON) { + return this._parseSliceExpression(); + } else { + var node = { + type: "Index", + value: this._lookaheadToken(0).value}; + this._advance(); + this._match(TOK_RBRACKET); + return node; + } + }, + _projectIfSlice: function(left, right) { + var indexExpr = {type: "IndexExpression", children: [left, right]}; + if (right.type === "Slice") { + return { + type: "Projection", + children: [indexExpr, this._parseProjectionRHS(bindingPower.Star)] + }; + } else { + return indexExpr; + } + }, -/***/ }), + _parseSliceExpression: function() { + // [start:end:step] where each part is optional, as well as the last + // colon. + var parts = [null, null, null]; + var index = 0; + var currentToken = this._lookahead(0); + while (currentToken !== TOK_RBRACKET && index < 3) { + if (currentToken === TOK_COLON) { + index++; + this._advance(); + } else if (currentToken === TOK_NUMBER) { + parts[index] = this._lookaheadToken(0).value; + this._advance(); + } else { + var t = this._lookahead(0); + var error = new Error("Syntax error, unexpected token: " + + t.value + "(" + t.type + ")"); + error.name = "Parsererror"; + throw error; + } + currentToken = this._lookahead(0); + } + this._match(TOK_RBRACKET); + return { + type: "Slice", + children: parts + }; + }, -/***/ 15564: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + _parseComparator: function(left, comparator) { + var right = this.expression(bindingPower[comparator]); + return {type: "Comparator", name: comparator, children: [left, right]}; + }, -"use strict"; + _parseDotRHS: function(rbp) { + var lookahead = this._lookahead(0); + var exprTokens = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER, TOK_STAR]; + if (exprTokens.indexOf(lookahead) >= 0) { + return this.expression(rbp); + } else if (lookahead === TOK_LBRACKET) { + this._match(TOK_LBRACKET); + return this._parseMultiselectList(); + } else if (lookahead === TOK_LBRACE) { + this._match(TOK_LBRACE); + return this._parseMultiselectHash(); + } + }, + _parseProjectionRHS: function(rbp) { + var right; + if (bindingPower[this._lookahead(0)] < 10) { + right = {type: "Identity"}; + } else if (this._lookahead(0) === TOK_LBRACKET) { + right = this.expression(rbp); + } else if (this._lookahead(0) === TOK_FILTER) { + right = this.expression(rbp); + } else if (this._lookahead(0) === TOK_DOT) { + this._match(TOK_DOT); + right = this._parseDotRHS(rbp); + } else { + var t = this._lookaheadToken(0); + var error = new Error("Sytanx error, unexpected token: " + + t.value + "(" + t.type + ")"); + error.name = "ParserError"; + throw error; + } + return right; + }, -var common = __nccwpck_require__(59136); -var Type = __nccwpck_require__(30967); + _parseMultiselectList: function() { + var expressions = []; + while (this._lookahead(0) !== TOK_RBRACKET) { + var expression = this.expression(0); + expressions.push(expression); + if (this._lookahead(0) === TOK_COMMA) { + this._match(TOK_COMMA); + if (this._lookahead(0) === TOK_RBRACKET) { + throw new Error("Unexpected token Rbracket"); + } + } + } + this._match(TOK_RBRACKET); + return {type: "MultiSelectList", children: expressions}; + }, -var YAML_FLOAT_PATTERN = new RegExp( - // 2.5e4, 2.5 and integers - '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + - // .2e4, .2 - // special case, seems not from spec - '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + - // 20:59 - '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + - // .inf - '|[-+]?\\.(?:inf|Inf|INF)' + - // .nan - '|\\.(?:nan|NaN|NAN))$'); + _parseMultiselectHash: function() { + var pairs = []; + var identifierTypes = [TOK_UNQUOTEDIDENTIFIER, TOK_QUOTEDIDENTIFIER]; + var keyToken, keyName, value, node; + for (;;) { + keyToken = this._lookaheadToken(0); + if (identifierTypes.indexOf(keyToken.type) < 0) { + throw new Error("Expecting an identifier token, got: " + + keyToken.type); + } + keyName = keyToken.value; + this._advance(); + this._match(TOK_COLON); + value = this.expression(0); + node = {type: "KeyValuePair", name: keyName, value: value}; + pairs.push(node); + if (this._lookahead(0) === TOK_COMMA) { + this._match(TOK_COMMA); + } else if (this._lookahead(0) === TOK_RBRACE) { + this._match(TOK_RBRACE); + break; + } + } + return {type: "MultiSelectHash", children: pairs}; + } + }; -function resolveYamlFloat(data) { - if (data === null) return false; - if (!YAML_FLOAT_PATTERN.test(data) || - // Quick hack to not allow integers end with `_` - // Probably should update regexp & check speed - data[data.length - 1] === '_') { - return false; + function TreeInterpreter(runtime) { + this.runtime = runtime; } - return true; -} - -function constructYamlFloat(data) { - var value, sign, base, digits; - - value = data.replace(/_/g, '').toLowerCase(); - sign = value[0] === '-' ? -1 : 1; - digits = []; + TreeInterpreter.prototype = { + search: function(node, value) { + return this.visit(node, value); + }, - if ('+-'.indexOf(value[0]) >= 0) { - value = value.slice(1); - } + visit: function(node, value) { + var matched, current, result, first, second, field, left, right, collected, i; + switch (node.type) { + case "Field": + if (value === null ) { + return null; + } else if (isObject(value)) { + field = value[node.name]; + if (field === undefined) { + return null; + } else { + return field; + } + } else { + return null; + } + break; + case "Subexpression": + result = this.visit(node.children[0], value); + for (i = 1; i < node.children.length; i++) { + result = this.visit(node.children[1], result); + if (result === null) { + return null; + } + } + return result; + case "IndexExpression": + left = this.visit(node.children[0], value); + right = this.visit(node.children[1], left); + return right; + case "Index": + if (!isArray(value)) { + return null; + } + var index = node.value; + if (index < 0) { + index = value.length + index; + } + result = value[index]; + if (result === undefined) { + result = null; + } + return result; + case "Slice": + if (!isArray(value)) { + return null; + } + var sliceParams = node.children.slice(0); + var computed = this.computeSliceParams(value.length, sliceParams); + var start = computed[0]; + var stop = computed[1]; + var step = computed[2]; + result = []; + if (step > 0) { + for (i = start; i < stop; i += step) { + result.push(value[i]); + } + } else { + for (i = start; i > stop; i += step) { + result.push(value[i]); + } + } + return result; + case "Projection": + // Evaluate left child. + var base = this.visit(node.children[0], value); + if (!isArray(base)) { + return null; + } + collected = []; + for (i = 0; i < base.length; i++) { + current = this.visit(node.children[1], base[i]); + if (current !== null) { + collected.push(current); + } + } + return collected; + case "ValueProjection": + // Evaluate left child. + base = this.visit(node.children[0], value); + if (!isObject(base)) { + return null; + } + collected = []; + var values = objValues(base); + for (i = 0; i < values.length; i++) { + current = this.visit(node.children[1], values[i]); + if (current !== null) { + collected.push(current); + } + } + return collected; + case "FilterProjection": + base = this.visit(node.children[0], value); + if (!isArray(base)) { + return null; + } + var filtered = []; + var finalResults = []; + for (i = 0; i < base.length; i++) { + matched = this.visit(node.children[2], base[i]); + if (!isFalse(matched)) { + filtered.push(base[i]); + } + } + for (var j = 0; j < filtered.length; j++) { + current = this.visit(node.children[1], filtered[j]); + if (current !== null) { + finalResults.push(current); + } + } + return finalResults; + case "Comparator": + first = this.visit(node.children[0], value); + second = this.visit(node.children[1], value); + switch(node.name) { + case TOK_EQ: + result = strictDeepEqual(first, second); + break; + case TOK_NE: + result = !strictDeepEqual(first, second); + break; + case TOK_GT: + result = first > second; + break; + case TOK_GTE: + result = first >= second; + break; + case TOK_LT: + result = first < second; + break; + case TOK_LTE: + result = first <= second; + break; + default: + throw new Error("Unknown comparator: " + node.name); + } + return result; + case TOK_FLATTEN: + var original = this.visit(node.children[0], value); + if (!isArray(original)) { + return null; + } + var merged = []; + for (i = 0; i < original.length; i++) { + current = original[i]; + if (isArray(current)) { + merged.push.apply(merged, current); + } else { + merged.push(current); + } + } + return merged; + case "Identity": + return value; + case "MultiSelectList": + if (value === null) { + return null; + } + collected = []; + for (i = 0; i < node.children.length; i++) { + collected.push(this.visit(node.children[i], value)); + } + return collected; + case "MultiSelectHash": + if (value === null) { + return null; + } + collected = {}; + var child; + for (i = 0; i < node.children.length; i++) { + child = node.children[i]; + collected[child.name] = this.visit(child.value, value); + } + return collected; + case "OrExpression": + matched = this.visit(node.children[0], value); + if (isFalse(matched)) { + matched = this.visit(node.children[1], value); + } + return matched; + case "AndExpression": + first = this.visit(node.children[0], value); - if (value === '.inf') { - return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; + if (isFalse(first) === true) { + return first; + } + return this.visit(node.children[1], value); + case "NotExpression": + first = this.visit(node.children[0], value); + return isFalse(first); + case "Literal": + return node.value; + case TOK_PIPE: + left = this.visit(node.children[0], value); + return this.visit(node.children[1], left); + case TOK_CURRENT: + return value; + case "Function": + var resolvedArgs = []; + for (i = 0; i < node.children.length; i++) { + resolvedArgs.push(this.visit(node.children[i], value)); + } + return this.runtime.callFunction(node.name, resolvedArgs); + case "ExpressionReference": + var refNode = node.children[0]; + // Tag the node with a specific attribute so the type + // checker verify the type. + refNode.jmespathType = TOK_EXPREF; + return refNode; + default: + throw new Error("Unknown node type: " + node.type); + } + }, - } else if (value === '.nan') { - return NaN; + computeSliceParams: function(arrayLength, sliceParams) { + var start = sliceParams[0]; + var stop = sliceParams[1]; + var step = sliceParams[2]; + var computed = [null, null, null]; + if (step === null) { + step = 1; + } else if (step === 0) { + var error = new Error("Invalid slice, step cannot be 0"); + error.name = "RuntimeError"; + throw error; + } + var stepValueNegative = step < 0 ? true : false; - } else if (value.indexOf(':') >= 0) { - value.split(':').forEach(function (v) { - digits.unshift(parseFloat(v, 10)); - }); + if (start === null) { + start = stepValueNegative ? arrayLength - 1 : 0; + } else { + start = this.capSliceRange(arrayLength, start, step); + } - value = 0.0; - base = 1; + if (stop === null) { + stop = stepValueNegative ? -1 : arrayLength; + } else { + stop = this.capSliceRange(arrayLength, stop, step); + } + computed[0] = start; + computed[1] = stop; + computed[2] = step; + return computed; + }, - digits.forEach(function (d) { - value += d * base; - base *= 60; - }); + capSliceRange: function(arrayLength, actualValue, step) { + if (actualValue < 0) { + actualValue += arrayLength; + if (actualValue < 0) { + actualValue = step < 0 ? -1 : 0; + } + } else if (actualValue >= arrayLength) { + actualValue = step < 0 ? arrayLength - 1 : arrayLength; + } + return actualValue; + } - return sign * value; + }; + function Runtime(interpreter) { + this._interpreter = interpreter; + this.functionTable = { + // name: [function, ] + // The can be: + // + // { + // args: [[type1, type2], [type1, type2]], + // variadic: true|false + // } + // + // Each arg in the arg list is a list of valid types + // (if the function is overloaded and supports multiple + // types. If the type is "any" then no type checking + // occurs on the argument. Variadic is optional + // and if not provided is assumed to be false. + abs: {_func: this._functionAbs, _signature: [{types: [TYPE_NUMBER]}]}, + avg: {_func: this._functionAvg, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, + ceil: {_func: this._functionCeil, _signature: [{types: [TYPE_NUMBER]}]}, + contains: { + _func: this._functionContains, + _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}, + {types: [TYPE_ANY]}]}, + "ends_with": { + _func: this._functionEndsWith, + _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, + floor: {_func: this._functionFloor, _signature: [{types: [TYPE_NUMBER]}]}, + length: { + _func: this._functionLength, + _signature: [{types: [TYPE_STRING, TYPE_ARRAY, TYPE_OBJECT]}]}, + map: { + _func: this._functionMap, + _signature: [{types: [TYPE_EXPREF]}, {types: [TYPE_ARRAY]}]}, + max: { + _func: this._functionMax, + _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, + "merge": { + _func: this._functionMerge, + _signature: [{types: [TYPE_OBJECT], variadic: true}] + }, + "max_by": { + _func: this._functionMaxBy, + _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] + }, + sum: {_func: this._functionSum, _signature: [{types: [TYPE_ARRAY_NUMBER]}]}, + "starts_with": { + _func: this._functionStartsWith, + _signature: [{types: [TYPE_STRING]}, {types: [TYPE_STRING]}]}, + min: { + _func: this._functionMin, + _signature: [{types: [TYPE_ARRAY_NUMBER, TYPE_ARRAY_STRING]}]}, + "min_by": { + _func: this._functionMinBy, + _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] + }, + type: {_func: this._functionType, _signature: [{types: [TYPE_ANY]}]}, + keys: {_func: this._functionKeys, _signature: [{types: [TYPE_OBJECT]}]}, + values: {_func: this._functionValues, _signature: [{types: [TYPE_OBJECT]}]}, + sort: {_func: this._functionSort, _signature: [{types: [TYPE_ARRAY_STRING, TYPE_ARRAY_NUMBER]}]}, + "sort_by": { + _func: this._functionSortBy, + _signature: [{types: [TYPE_ARRAY]}, {types: [TYPE_EXPREF]}] + }, + join: { + _func: this._functionJoin, + _signature: [ + {types: [TYPE_STRING]}, + {types: [TYPE_ARRAY_STRING]} + ] + }, + reverse: { + _func: this._functionReverse, + _signature: [{types: [TYPE_STRING, TYPE_ARRAY]}]}, + "to_array": {_func: this._functionToArray, _signature: [{types: [TYPE_ANY]}]}, + "to_string": {_func: this._functionToString, _signature: [{types: [TYPE_ANY]}]}, + "to_number": {_func: this._functionToNumber, _signature: [{types: [TYPE_ANY]}]}, + "not_null": { + _func: this._functionNotNull, + _signature: [{types: [TYPE_ANY], variadic: true}] + } + }; } - return sign * parseFloat(value, 10); -} + Runtime.prototype = { + callFunction: function(name, resolvedArgs) { + var functionEntry = this.functionTable[name]; + if (functionEntry === undefined) { + throw new Error("Unknown function: " + name + "()"); + } + this._validateArgs(name, resolvedArgs, functionEntry._signature); + return functionEntry._func.call(this, resolvedArgs); + }, -var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; + _validateArgs: function(name, args, signature) { + // Validating the args requires validating + // the correct arity and the correct type of each arg. + // If the last argument is declared as variadic, then we need + // a minimum number of args to be required. Otherwise it has to + // be an exact amount. + var pluralized; + if (signature[signature.length - 1].variadic) { + if (args.length < signature.length) { + pluralized = signature.length === 1 ? " argument" : " arguments"; + throw new Error("ArgumentError: " + name + "() " + + "takes at least" + signature.length + pluralized + + " but received " + args.length); + } + } else if (args.length !== signature.length) { + pluralized = signature.length === 1 ? " argument" : " arguments"; + throw new Error("ArgumentError: " + name + "() " + + "takes " + signature.length + pluralized + + " but received " + args.length); + } + var currentSpec; + var actualType; + var typeMatched; + for (var i = 0; i < signature.length; i++) { + typeMatched = false; + currentSpec = signature[i].types; + actualType = this._getTypeName(args[i]); + for (var j = 0; j < currentSpec.length; j++) { + if (this._typeMatches(actualType, currentSpec[j], args[i])) { + typeMatched = true; + break; + } + } + if (!typeMatched) { + throw new Error("TypeError: " + name + "() " + + "expected argument " + (i + 1) + + " to be type " + currentSpec + + " but received type " + actualType + + " instead."); + } + } + }, -function representYamlFloat(object, style) { - var res; + _typeMatches: function(actual, expected, argValue) { + if (expected === TYPE_ANY) { + return true; + } + if (expected === TYPE_ARRAY_STRING || + expected === TYPE_ARRAY_NUMBER || + expected === TYPE_ARRAY) { + // The expected type can either just be array, + // or it can require a specific subtype (array of numbers). + // + // The simplest case is if "array" with no subtype is specified. + if (expected === TYPE_ARRAY) { + return actual === TYPE_ARRAY; + } else if (actual === TYPE_ARRAY) { + // Otherwise we need to check subtypes. + // I think this has potential to be improved. + var subtype; + if (expected === TYPE_ARRAY_NUMBER) { + subtype = TYPE_NUMBER; + } else if (expected === TYPE_ARRAY_STRING) { + subtype = TYPE_STRING; + } + for (var i = 0; i < argValue.length; i++) { + if (!this._typeMatches( + this._getTypeName(argValue[i]), subtype, + argValue[i])) { + return false; + } + } + return true; + } + } else { + return actual === expected; + } + }, + _getTypeName: function(obj) { + switch (Object.prototype.toString.call(obj)) { + case "[object String]": + return TYPE_STRING; + case "[object Number]": + return TYPE_NUMBER; + case "[object Array]": + return TYPE_ARRAY; + case "[object Boolean]": + return TYPE_BOOLEAN; + case "[object Null]": + return TYPE_NULL; + case "[object Object]": + // Check if it's an expref. If it has, it's been + // tagged with a jmespathType attr of 'Expref'; + if (obj.jmespathType === TOK_EXPREF) { + return TYPE_EXPREF; + } else { + return TYPE_OBJECT; + } + } + }, - if (isNaN(object)) { - switch (style) { - case 'lowercase': return '.nan'; - case 'uppercase': return '.NAN'; - case 'camelcase': return '.NaN'; - } - } else if (Number.POSITIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '.inf'; - case 'uppercase': return '.INF'; - case 'camelcase': return '.Inf'; - } - } else if (Number.NEGATIVE_INFINITY === object) { - switch (style) { - case 'lowercase': return '-.inf'; - case 'uppercase': return '-.INF'; - case 'camelcase': return '-.Inf'; - } - } else if (common.isNegativeZero(object)) { - return '-0.0'; - } + _functionStartsWith: function(resolvedArgs) { + return resolvedArgs[0].lastIndexOf(resolvedArgs[1]) === 0; + }, - res = object.toString(10); + _functionEndsWith: function(resolvedArgs) { + var searchStr = resolvedArgs[0]; + var suffix = resolvedArgs[1]; + return searchStr.indexOf(suffix, searchStr.length - suffix.length) !== -1; + }, - // JS stringifier can build scientific format without dots: 5e-100, - // while YAML requres dot: 5.e-100. Fix it with simple hack + _functionReverse: function(resolvedArgs) { + var typeName = this._getTypeName(resolvedArgs[0]); + if (typeName === TYPE_STRING) { + var originalStr = resolvedArgs[0]; + var reversedStr = ""; + for (var i = originalStr.length - 1; i >= 0; i--) { + reversedStr += originalStr[i]; + } + return reversedStr; + } else { + var reversedArray = resolvedArgs[0].slice(0); + reversedArray.reverse(); + return reversedArray; + } + }, - return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; -} + _functionAbs: function(resolvedArgs) { + return Math.abs(resolvedArgs[0]); + }, -function isFloat(object) { - return (Object.prototype.toString.call(object) === '[object Number]') && - (object % 1 !== 0 || common.isNegativeZero(object)); -} + _functionCeil: function(resolvedArgs) { + return Math.ceil(resolvedArgs[0]); + }, -module.exports = new Type('tag:yaml.org,2002:float', { - kind: 'scalar', - resolve: resolveYamlFloat, - construct: constructYamlFloat, - predicate: isFloat, - represent: representYamlFloat, - defaultStyle: 'lowercase' -}); + _functionAvg: function(resolvedArgs) { + var sum = 0; + var inputArray = resolvedArgs[0]; + for (var i = 0; i < inputArray.length; i++) { + sum += inputArray[i]; + } + return sum / inputArray.length; + }, + _functionContains: function(resolvedArgs) { + return resolvedArgs[0].indexOf(resolvedArgs[1]) >= 0; + }, -/***/ }), + _functionFloor: function(resolvedArgs) { + return Math.floor(resolvedArgs[0]); + }, -/***/ 89963: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + _functionLength: function(resolvedArgs) { + if (!isObject(resolvedArgs[0])) { + return resolvedArgs[0].length; + } else { + // As far as I can tell, there's no way to get the length + // of an object without O(n) iteration through the object. + return Object.keys(resolvedArgs[0]).length; + } + }, -"use strict"; + _functionMap: function(resolvedArgs) { + var mapped = []; + var interpreter = this._interpreter; + var exprefNode = resolvedArgs[0]; + var elements = resolvedArgs[1]; + for (var i = 0; i < elements.length; i++) { + mapped.push(interpreter.visit(exprefNode, elements[i])); + } + return mapped; + }, + _functionMerge: function(resolvedArgs) { + var merged = {}; + for (var i = 0; i < resolvedArgs.length; i++) { + var current = resolvedArgs[i]; + for (var key in current) { + merged[key] = current[key]; + } + } + return merged; + }, -var common = __nccwpck_require__(59136); -var Type = __nccwpck_require__(30967); + _functionMax: function(resolvedArgs) { + if (resolvedArgs[0].length > 0) { + var typeName = this._getTypeName(resolvedArgs[0][0]); + if (typeName === TYPE_NUMBER) { + return Math.max.apply(Math, resolvedArgs[0]); + } else { + var elements = resolvedArgs[0]; + var maxElement = elements[0]; + for (var i = 1; i < elements.length; i++) { + if (maxElement.localeCompare(elements[i]) < 0) { + maxElement = elements[i]; + } + } + return maxElement; + } + } else { + return null; + } + }, -function isHexCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || - ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || - ((0x61/* a */ <= c) && (c <= 0x66/* f */)); -} + _functionMin: function(resolvedArgs) { + if (resolvedArgs[0].length > 0) { + var typeName = this._getTypeName(resolvedArgs[0][0]); + if (typeName === TYPE_NUMBER) { + return Math.min.apply(Math, resolvedArgs[0]); + } else { + var elements = resolvedArgs[0]; + var minElement = elements[0]; + for (var i = 1; i < elements.length; i++) { + if (elements[i].localeCompare(minElement) < 0) { + minElement = elements[i]; + } + } + return minElement; + } + } else { + return null; + } + }, -function isOctCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); -} + _functionSum: function(resolvedArgs) { + var sum = 0; + var listToSum = resolvedArgs[0]; + for (var i = 0; i < listToSum.length; i++) { + sum += listToSum[i]; + } + return sum; + }, -function isDecCode(c) { - return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); -} + _functionType: function(resolvedArgs) { + switch (this._getTypeName(resolvedArgs[0])) { + case TYPE_NUMBER: + return "number"; + case TYPE_STRING: + return "string"; + case TYPE_ARRAY: + return "array"; + case TYPE_OBJECT: + return "object"; + case TYPE_BOOLEAN: + return "boolean"; + case TYPE_EXPREF: + return "expref"; + case TYPE_NULL: + return "null"; + } + }, -function resolveYamlInteger(data) { - if (data === null) return false; + _functionKeys: function(resolvedArgs) { + return Object.keys(resolvedArgs[0]); + }, - var max = data.length, - index = 0, - hasDigits = false, - ch; + _functionValues: function(resolvedArgs) { + var obj = resolvedArgs[0]; + var keys = Object.keys(obj); + var values = []; + for (var i = 0; i < keys.length; i++) { + values.push(obj[keys[i]]); + } + return values; + }, - if (!max) return false; + _functionJoin: function(resolvedArgs) { + var joinChar = resolvedArgs[0]; + var listJoin = resolvedArgs[1]; + return listJoin.join(joinChar); + }, - ch = data[index]; + _functionToArray: function(resolvedArgs) { + if (this._getTypeName(resolvedArgs[0]) === TYPE_ARRAY) { + return resolvedArgs[0]; + } else { + return [resolvedArgs[0]]; + } + }, - // sign - if (ch === '-' || ch === '+') { - ch = data[++index]; - } + _functionToString: function(resolvedArgs) { + if (this._getTypeName(resolvedArgs[0]) === TYPE_STRING) { + return resolvedArgs[0]; + } else { + return JSON.stringify(resolvedArgs[0]); + } + }, - if (ch === '0') { - // 0 - if (index + 1 === max) return true; - ch = data[++index]; + _functionToNumber: function(resolvedArgs) { + var typeName = this._getTypeName(resolvedArgs[0]); + var convertedValue; + if (typeName === TYPE_NUMBER) { + return resolvedArgs[0]; + } else if (typeName === TYPE_STRING) { + convertedValue = +resolvedArgs[0]; + if (!isNaN(convertedValue)) { + return convertedValue; + } + } + return null; + }, - // base 2, base 8, base 16 + _functionNotNull: function(resolvedArgs) { + for (var i = 0; i < resolvedArgs.length; i++) { + if (this._getTypeName(resolvedArgs[i]) !== TYPE_NULL) { + return resolvedArgs[i]; + } + } + return null; + }, - if (ch === 'b') { - // base 2 - index++; + _functionSort: function(resolvedArgs) { + var sortedArray = resolvedArgs[0].slice(0); + sortedArray.sort(); + return sortedArray; + }, - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch !== '0' && ch !== '1') return false; - hasDigits = true; + _functionSortBy: function(resolvedArgs) { + var sortedArray = resolvedArgs[0].slice(0); + if (sortedArray.length === 0) { + return sortedArray; + } + var interpreter = this._interpreter; + var exprefNode = resolvedArgs[1]; + var requiredType = this._getTypeName( + interpreter.visit(exprefNode, sortedArray[0])); + if ([TYPE_NUMBER, TYPE_STRING].indexOf(requiredType) < 0) { + throw new Error("TypeError"); + } + var that = this; + // In order to get a stable sort out of an unstable + // sort algorithm, we decorate/sort/undecorate (DSU) + // by creating a new list of [index, element] pairs. + // In the cmp function, if the evaluated elements are + // equal, then the index will be used as the tiebreaker. + // After the decorated list has been sorted, it will be + // undecorated to extract the original elements. + var decorated = []; + for (var i = 0; i < sortedArray.length; i++) { + decorated.push([i, sortedArray[i]]); + } + decorated.sort(function(a, b) { + var exprA = interpreter.visit(exprefNode, a[1]); + var exprB = interpreter.visit(exprefNode, b[1]); + if (that._getTypeName(exprA) !== requiredType) { + throw new Error( + "TypeError: expected " + requiredType + ", received " + + that._getTypeName(exprA)); + } else if (that._getTypeName(exprB) !== requiredType) { + throw new Error( + "TypeError: expected " + requiredType + ", received " + + that._getTypeName(exprB)); + } + if (exprA > exprB) { + return 1; + } else if (exprA < exprB) { + return -1; + } else { + // If they're equal compare the items by their + // order to maintain relative order of equal keys + // (i.e. to get a stable sort). + return a[0] - b[0]; + } + }); + // Undecorate: extract out the original list elements. + for (var j = 0; j < decorated.length; j++) { + sortedArray[j] = decorated[j][1]; + } + return sortedArray; + }, + + _functionMaxBy: function(resolvedArgs) { + var exprefNode = resolvedArgs[1]; + var resolvedArray = resolvedArgs[0]; + var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); + var maxNumber = -Infinity; + var maxRecord; + var current; + for (var i = 0; i < resolvedArray.length; i++) { + current = keyFunction(resolvedArray[i]); + if (current > maxNumber) { + maxNumber = current; + maxRecord = resolvedArray[i]; + } } - return hasDigits && ch !== '_'; + return maxRecord; + }, + + _functionMinBy: function(resolvedArgs) { + var exprefNode = resolvedArgs[1]; + var resolvedArray = resolvedArgs[0]; + var keyFunction = this.createKeyFunction(exprefNode, [TYPE_NUMBER, TYPE_STRING]); + var minNumber = Infinity; + var minRecord; + var current; + for (var i = 0; i < resolvedArray.length; i++) { + current = keyFunction(resolvedArray[i]); + if (current < minNumber) { + minNumber = current; + minRecord = resolvedArray[i]; + } + } + return minRecord; + }, + + createKeyFunction: function(exprefNode, allowedTypes) { + var that = this; + var interpreter = this._interpreter; + var keyFunc = function(x) { + var current = interpreter.visit(exprefNode, x); + if (allowedTypes.indexOf(that._getTypeName(current)) < 0) { + var msg = "TypeError: expected one of " + allowedTypes + + ", received " + that._getTypeName(current); + throw new Error(msg); + } + return current; + }; + return keyFunc; } + }; - if (ch === 'x') { - // base 16 - index++; + function compile(stream) { + var parser = new Parser(); + var ast = parser.parse(stream); + return ast; + } - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isHexCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; - } + function tokenize(stream) { + var lexer = new Lexer(); + return lexer.tokenize(stream); + } - // base 8 - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (!isOctCode(data.charCodeAt(index))) return false; - hasDigits = true; - } - return hasDigits && ch !== '_'; + function search(data, expression) { + var parser = new Parser(); + // This needs to be improved. Both the interpreter and runtime depend on + // each other. The runtime needs the interpreter to support exprefs. + // There's likely a clean way to avoid the cyclic dependency. + var runtime = new Runtime(); + var interpreter = new TreeInterpreter(runtime); + runtime._interpreter = interpreter; + var node = parser.parse(expression); + return interpreter.search(node, data); } - // base 10 (except 0) or base 60 + exports.tokenize = tokenize; + exports.compile = compile; + exports.search = search; + exports.strictDeepEqual = strictDeepEqual; +})( false ? 0 : exports); - // value should not start with `_`; - if (ch === '_') return false; - for (; index < max; index++) { - ch = data[index]; - if (ch === '_') continue; - if (ch === ':') break; - if (!isDecCode(data.charCodeAt(index))) { - return false; - } - hasDigits = true; - } +/***/ }), - // Should have digits and should not end with `_` - if (!hasDigits || ch === '_') return false; +/***/ 21917: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - // if !base60 - done; - if (ch !== ':') return true; +"use strict"; - // base60 almost not used, no needs to optimize - return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); -} -function constructYamlInteger(data) { - var value = data, sign = 1, ch, base, digits = []; - if (value.indexOf('_') !== -1) { - value = value.replace(/_/g, ''); - } +var yaml = __nccwpck_require__(40916); - ch = value[0]; - if (ch === '-' || ch === '+') { - if (ch === '-') sign = -1; - value = value.slice(1); - ch = value[0]; - } +module.exports = yaml; - if (value === '0') return 0; - if (ch === '0') { - if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); - if (value[1] === 'x') return sign * parseInt(value, 16); - return sign * parseInt(value, 8); - } +/***/ }), - if (value.indexOf(':') !== -1) { - value.split(':').forEach(function (v) { - digits.unshift(parseInt(v, 10)); - }); +/***/ 40916: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - value = 0; - base = 1; +"use strict"; - digits.forEach(function (d) { - value += (d * base); - base *= 60; - }); - return sign * value; - } +var loader = __nccwpck_require__(45190); +var dumper = __nccwpck_require__(73034); - return sign * parseInt(value, 10); -} -function isInteger(object) { - return (Object.prototype.toString.call(object)) === '[object Number]' && - (object % 1 === 0 && !common.isNegativeZero(object)); +function deprecated(name) { + return function () { + throw new Error('Function ' + name + ' is deprecated and cannot be used.'); + }; } -module.exports = new Type('tag:yaml.org,2002:int', { - kind: 'scalar', - resolve: resolveYamlInteger, - construct: constructYamlInteger, - predicate: isInteger, - represent: { - binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, - octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, - decimal: function (obj) { return obj.toString(10); }, - /* eslint-disable max-len */ - hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } - }, - defaultStyle: 'decimal', - styleAliases: { - binary: [ 2, 'bin' ], - octal: [ 8, 'oct' ], - decimal: [ 10, 'dec' ], - hexadecimal: [ 16, 'hex' ] - } -}); +module.exports.Type = __nccwpck_require__(30967); +module.exports.Schema = __nccwpck_require__(66514); +module.exports.FAILSAFE_SCHEMA = __nccwpck_require__(66037); +module.exports.JSON_SCHEMA = __nccwpck_require__(1571); +module.exports.CORE_SCHEMA = __nccwpck_require__(92183); +module.exports.DEFAULT_SAFE_SCHEMA = __nccwpck_require__(48949); +module.exports.DEFAULT_FULL_SCHEMA = __nccwpck_require__(56874); +module.exports.load = loader.load; +module.exports.loadAll = loader.loadAll; +module.exports.safeLoad = loader.safeLoad; +module.exports.safeLoadAll = loader.safeLoadAll; +module.exports.dump = dumper.dump; +module.exports.safeDump = dumper.safeDump; +module.exports.YAMLException = __nccwpck_require__(65199); + +// Deprecated schema names from JS-YAML 2.0.x +module.exports.MINIMAL_SCHEMA = __nccwpck_require__(66037); +module.exports.SAFE_SCHEMA = __nccwpck_require__(48949); +module.exports.DEFAULT_SCHEMA = __nccwpck_require__(56874); -/***/ }), +// Deprecated functions from JS-YAML 1.x.x +module.exports.scan = deprecated('scan'); +module.exports.parse = deprecated('parse'); +module.exports.compose = deprecated('compose'); +module.exports.addConstructor = deprecated('addConstructor'); -/***/ 27278: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/***/ }), + +/***/ 59136: +/***/ ((module) => { "use strict"; -var esprima; -// Browserified version does not have esprima -// -// 1. For node.js just require module as deps -// 2. For browser try to require mudule via external AMD system. -// If not found - try to fallback to window.esprima. If not -// found too - then fail to parse. -// -try { - // workaround to exclude package from browserify list. - var _require = require; - esprima = _require('esprima'); -} catch (_) { - /* eslint-disable no-redeclare */ - /* global window */ - if (typeof window !== 'undefined') esprima = window.esprima; +function isNothing(subject) { + return (typeof subject === 'undefined') || (subject === null); } -var Type = __nccwpck_require__(30967); -function resolveJavascriptFunction(data) { - if (data === null) return false; +function isObject(subject) { + return (typeof subject === 'object') && (subject !== null); +} - try { - var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }); - if (ast.type !== 'Program' || - ast.body.length !== 1 || - ast.body[0].type !== 'ExpressionStatement' || - (ast.body[0].expression.type !== 'ArrowFunctionExpression' && - ast.body[0].expression.type !== 'FunctionExpression')) { - return false; - } +function toArray(sequence) { + if (Array.isArray(sequence)) return sequence; + else if (isNothing(sequence)) return []; - return true; - } catch (err) { - return false; - } + return [ sequence ]; } -function constructJavascriptFunction(data) { - /*jslint evil:true*/ - var source = '(' + data + ')', - ast = esprima.parse(source, { range: true }), - params = [], - body; +function extend(target, source) { + var index, length, key, sourceKeys; - if (ast.type !== 'Program' || - ast.body.length !== 1 || - ast.body[0].type !== 'ExpressionStatement' || - (ast.body[0].expression.type !== 'ArrowFunctionExpression' && - ast.body[0].expression.type !== 'FunctionExpression')) { - throw new Error('Failed to resolve function'); + if (source) { + sourceKeys = Object.keys(source); + + for (index = 0, length = sourceKeys.length; index < length; index += 1) { + key = sourceKeys[index]; + target[key] = source[key]; + } } - ast.body[0].expression.params.forEach(function (param) { - params.push(param.name); - }); + return target; +} - body = ast.body[0].expression.body.range; - // Esprima's ranges include the first '{' and the last '}' characters on - // function expressions. So cut them out. - if (ast.body[0].expression.body.type === 'BlockStatement') { - /*eslint-disable no-new-func*/ - return new Function(params, source.slice(body[0] + 1, body[1] - 1)); +function repeat(string, count) { + var result = '', cycle; + + for (cycle = 0; cycle < count; cycle += 1) { + result += string; } - // ES6 arrow functions can omit the BlockStatement. In that case, just return - // the body. - /*eslint-disable no-new-func*/ - return new Function(params, 'return ' + source.slice(body[0], body[1])); -} -function representJavascriptFunction(object /*, style*/) { - return object.toString(); + return result; } -function isFunction(object) { - return Object.prototype.toString.call(object) === '[object Function]'; + +function isNegativeZero(number) { + return (number === 0) && (Number.NEGATIVE_INFINITY === 1 / number); } -module.exports = new Type('tag:yaml.org,2002:js/function', { - kind: 'scalar', - resolve: resolveJavascriptFunction, - construct: constructJavascriptFunction, - predicate: isFunction, - represent: representJavascriptFunction -}); + +module.exports.isNothing = isNothing; +module.exports.isObject = isObject; +module.exports.toArray = toArray; +module.exports.repeat = repeat; +module.exports.isNegativeZero = isNegativeZero; +module.exports.extend = extend; /***/ }), -/***/ 69242: +/***/ 73034: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -var Type = __nccwpck_require__(30967); - -function resolveJavascriptRegExp(data) { - if (data === null) return false; - if (data.length === 0) return false; - - var regexp = data, - tail = /\/([gim]*)$/.exec(data), - modifiers = ''; +/*eslint-disable no-use-before-define*/ - // if regexp starts with '/' it can have modifiers and must be properly closed - // `/foo/gim` - modifiers tail can be maximum 3 chars - if (regexp[0] === '/') { - if (tail) modifiers = tail[1]; +var common = __nccwpck_require__(59136); +var YAMLException = __nccwpck_require__(65199); +var DEFAULT_FULL_SCHEMA = __nccwpck_require__(56874); +var DEFAULT_SAFE_SCHEMA = __nccwpck_require__(48949); - if (modifiers.length > 3) return false; - // if expression starts with /, is should be properly terminated - if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; - } +var _toString = Object.prototype.toString; +var _hasOwnProperty = Object.prototype.hasOwnProperty; - return true; -} +var CHAR_TAB = 0x09; /* Tab */ +var CHAR_LINE_FEED = 0x0A; /* LF */ +var CHAR_CARRIAGE_RETURN = 0x0D; /* CR */ +var CHAR_SPACE = 0x20; /* Space */ +var CHAR_EXCLAMATION = 0x21; /* ! */ +var CHAR_DOUBLE_QUOTE = 0x22; /* " */ +var CHAR_SHARP = 0x23; /* # */ +var CHAR_PERCENT = 0x25; /* % */ +var CHAR_AMPERSAND = 0x26; /* & */ +var CHAR_SINGLE_QUOTE = 0x27; /* ' */ +var CHAR_ASTERISK = 0x2A; /* * */ +var CHAR_COMMA = 0x2C; /* , */ +var CHAR_MINUS = 0x2D; /* - */ +var CHAR_COLON = 0x3A; /* : */ +var CHAR_EQUALS = 0x3D; /* = */ +var CHAR_GREATER_THAN = 0x3E; /* > */ +var CHAR_QUESTION = 0x3F; /* ? */ +var CHAR_COMMERCIAL_AT = 0x40; /* @ */ +var CHAR_LEFT_SQUARE_BRACKET = 0x5B; /* [ */ +var CHAR_RIGHT_SQUARE_BRACKET = 0x5D; /* ] */ +var CHAR_GRAVE_ACCENT = 0x60; /* ` */ +var CHAR_LEFT_CURLY_BRACKET = 0x7B; /* { */ +var CHAR_VERTICAL_LINE = 0x7C; /* | */ +var CHAR_RIGHT_CURLY_BRACKET = 0x7D; /* } */ -function constructJavascriptRegExp(data) { - var regexp = data, - tail = /\/([gim]*)$/.exec(data), - modifiers = ''; +var ESCAPE_SEQUENCES = {}; - // `/foo/gim` - tail can be maximum 4 chars - if (regexp[0] === '/') { - if (tail) modifiers = tail[1]; - regexp = regexp.slice(1, regexp.length - modifiers.length - 1); - } +ESCAPE_SEQUENCES[0x00] = '\\0'; +ESCAPE_SEQUENCES[0x07] = '\\a'; +ESCAPE_SEQUENCES[0x08] = '\\b'; +ESCAPE_SEQUENCES[0x09] = '\\t'; +ESCAPE_SEQUENCES[0x0A] = '\\n'; +ESCAPE_SEQUENCES[0x0B] = '\\v'; +ESCAPE_SEQUENCES[0x0C] = '\\f'; +ESCAPE_SEQUENCES[0x0D] = '\\r'; +ESCAPE_SEQUENCES[0x1B] = '\\e'; +ESCAPE_SEQUENCES[0x22] = '\\"'; +ESCAPE_SEQUENCES[0x5C] = '\\\\'; +ESCAPE_SEQUENCES[0x85] = '\\N'; +ESCAPE_SEQUENCES[0xA0] = '\\_'; +ESCAPE_SEQUENCES[0x2028] = '\\L'; +ESCAPE_SEQUENCES[0x2029] = '\\P'; - return new RegExp(regexp, modifiers); -} +var DEPRECATED_BOOLEANS_SYNTAX = [ + 'y', 'Y', 'yes', 'Yes', 'YES', 'on', 'On', 'ON', + 'n', 'N', 'no', 'No', 'NO', 'off', 'Off', 'OFF' +]; -function representJavascriptRegExp(object /*, style*/) { - var result = '/' + object.source + '/'; +function compileStyleMap(schema, map) { + var result, keys, index, length, tag, style, type; - if (object.global) result += 'g'; - if (object.multiline) result += 'm'; - if (object.ignoreCase) result += 'i'; + if (map === null) return {}; - return result; -} + result = {}; + keys = Object.keys(map); -function isRegExp(object) { - return Object.prototype.toString.call(object) === '[object RegExp]'; -} + for (index = 0, length = keys.length; index < length; index += 1) { + tag = keys[index]; + style = String(map[tag]); -module.exports = new Type('tag:yaml.org,2002:js/regexp', { - kind: 'scalar', - resolve: resolveJavascriptRegExp, - construct: constructJavascriptRegExp, - predicate: isRegExp, - represent: representJavascriptRegExp -}); + if (tag.slice(0, 2) === '!!') { + tag = 'tag:yaml.org,2002:' + tag.slice(2); + } + type = schema.compiledTypeMap['fallback'][tag]; + if (type && _hasOwnProperty.call(type.styleAliases, style)) { + style = type.styleAliases[style]; + } -/***/ }), + result[tag] = style; + } -/***/ 25914: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + return result; +} -"use strict"; +function encodeHex(character) { + var string, handle, length; + string = character.toString(16).toUpperCase(); -var Type = __nccwpck_require__(30967); + if (character <= 0xFF) { + handle = 'x'; + length = 2; + } else if (character <= 0xFFFF) { + handle = 'u'; + length = 4; + } else if (character <= 0xFFFFFFFF) { + handle = 'U'; + length = 8; + } else { + throw new YAMLException('code point within a string may not be greater than 0xFFFFFFFF'); + } -function resolveJavascriptUndefined() { - return true; + return '\\' + handle + common.repeat('0', length - string.length) + string; } -function constructJavascriptUndefined() { - /*eslint-disable no-undefined*/ - return undefined; -} +function State(options) { + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.indent = Math.max(1, (options['indent'] || 2)); + this.noArrayIndent = options['noArrayIndent'] || false; + this.skipInvalid = options['skipInvalid'] || false; + this.flowLevel = (common.isNothing(options['flowLevel']) ? -1 : options['flowLevel']); + this.styleMap = compileStyleMap(this.schema, options['styles'] || null); + this.sortKeys = options['sortKeys'] || false; + this.lineWidth = options['lineWidth'] || 80; + this.noRefs = options['noRefs'] || false; + this.noCompatMode = options['noCompatMode'] || false; + this.condenseFlow = options['condenseFlow'] || false; -function representJavascriptUndefined() { - return ''; -} + this.implicitTypes = this.schema.compiledImplicit; + this.explicitTypes = this.schema.compiledExplicit; -function isUndefined(object) { - return typeof object === 'undefined'; + this.tag = null; + this.result = ''; + + this.duplicates = []; + this.usedDuplicates = null; } -module.exports = new Type('tag:yaml.org,2002:js/undefined', { - kind: 'scalar', - resolve: resolveJavascriptUndefined, - construct: constructJavascriptUndefined, - predicate: isUndefined, - represent: representJavascriptUndefined -}); +// Indents every line in a string. Empty lines (\n only) are not indented. +function indentString(string, spaces) { + var ind = common.repeat(' ', spaces), + position = 0, + next = -1, + result = '', + line, + length = string.length; + while (position < length) { + next = string.indexOf('\n', position); + if (next === -1) { + line = string.slice(position); + position = length; + } else { + line = string.slice(position, next + 1); + position = next + 1; + } -/***/ }), + if (line.length && line !== '\n') result += ind; -/***/ 31173: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + result += line; + } -"use strict"; + return result; +} +function generateNextLine(state, level) { + return '\n' + common.repeat(' ', state.indent * level); +} -var Type = __nccwpck_require__(30967); +function testImplicitResolving(state, str) { + var index, length, type; -module.exports = new Type('tag:yaml.org,2002:map', { - kind: 'mapping', - construct: function (data) { return data !== null ? data : {}; } -}); + for (index = 0, length = state.implicitTypes.length; index < length; index += 1) { + type = state.implicitTypes[index]; + if (type.resolve(str)) { + return true; + } + } -/***/ }), + return false; +} -/***/ 81393: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +// [33] s-white ::= s-space | s-tab +function isWhitespace(c) { + return c === CHAR_SPACE || c === CHAR_TAB; +} -"use strict"; +// Returns true if the character can be printed without escaping. +// From YAML 1.2: "any allowed characters known to be non-printable +// should also be escaped. [However,] This isn’t mandatory" +// Derived from nb-char - \t - #x85 - #xA0 - #x2028 - #x2029. +function isPrintable(c) { + return (0x00020 <= c && c <= 0x00007E) + || ((0x000A1 <= c && c <= 0x00D7FF) && c !== 0x2028 && c !== 0x2029) + || ((0x0E000 <= c && c <= 0x00FFFD) && c !== 0xFEFF /* BOM */) + || (0x10000 <= c && c <= 0x10FFFF); +} +// [34] ns-char ::= nb-char - s-white +// [27] nb-char ::= c-printable - b-char - c-byte-order-mark +// [26] b-char ::= b-line-feed | b-carriage-return +// [24] b-line-feed ::= #xA /* LF */ +// [25] b-carriage-return ::= #xD /* CR */ +// [3] c-byte-order-mark ::= #xFEFF +function isNsChar(c) { + return isPrintable(c) && !isWhitespace(c) + // byte-order-mark + && c !== 0xFEFF + // b-char + && c !== CHAR_CARRIAGE_RETURN + && c !== CHAR_LINE_FEED; +} -var Type = __nccwpck_require__(30967); +// Simplified test for values allowed after the first character in plain style. +function isPlainSafe(c, prev) { + // Uses a subset of nb-char - c-flow-indicator - ":" - "#" + // where nb-char ::= c-printable - b-char - c-byte-order-mark. + return isPrintable(c) && c !== 0xFEFF + // - c-flow-indicator + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // - ":" - "#" + // /* An ns-char preceding */ "#" + && c !== CHAR_COLON + && ((c !== CHAR_SHARP) || (prev && isNsChar(prev))); +} -function resolveYamlMerge(data) { - return data === '<<' || data === null; +// Simplified test for values allowed as the first character in plain style. +function isPlainSafeFirst(c) { + // Uses a subset of ns-char - c-indicator + // where ns-char = nb-char - s-white. + return isPrintable(c) && c !== 0xFEFF + && !isWhitespace(c) // - s-white + // - (c-indicator ::= + // “-” | “?” | “:” | “,” | “[” | “]” | “{” | “}” + && c !== CHAR_MINUS + && c !== CHAR_QUESTION + && c !== CHAR_COLON + && c !== CHAR_COMMA + && c !== CHAR_LEFT_SQUARE_BRACKET + && c !== CHAR_RIGHT_SQUARE_BRACKET + && c !== CHAR_LEFT_CURLY_BRACKET + && c !== CHAR_RIGHT_CURLY_BRACKET + // | “#” | “&” | “*” | “!” | “|” | “=” | “>” | “'” | “"” + && c !== CHAR_SHARP + && c !== CHAR_AMPERSAND + && c !== CHAR_ASTERISK + && c !== CHAR_EXCLAMATION + && c !== CHAR_VERTICAL_LINE + && c !== CHAR_EQUALS + && c !== CHAR_GREATER_THAN + && c !== CHAR_SINGLE_QUOTE + && c !== CHAR_DOUBLE_QUOTE + // | “%” | “@” | “`”) + && c !== CHAR_PERCENT + && c !== CHAR_COMMERCIAL_AT + && c !== CHAR_GRAVE_ACCENT; } -module.exports = new Type('tag:yaml.org,2002:merge', { - kind: 'scalar', - resolve: resolveYamlMerge -}); +// Determines whether block indentation indicator is required. +function needIndentIndicator(string) { + var leadingSpaceRe = /^\n* /; + return leadingSpaceRe.test(string); +} +var STYLE_PLAIN = 1, + STYLE_SINGLE = 2, + STYLE_LITERAL = 3, + STYLE_FOLDED = 4, + STYLE_DOUBLE = 5; -/***/ }), +// Determines which scalar styles are possible and returns the preferred style. +// lineWidth = -1 => no limit. +// Pre-conditions: str.length > 0. +// Post-conditions: +// STYLE_PLAIN or STYLE_SINGLE => no \n are in the string. +// STYLE_LITERAL => no lines are suitable for folding (or lineWidth is -1). +// STYLE_FOLDED => a line > lineWidth and can be folded (and lineWidth != -1). +function chooseScalarStyle(string, singleLineOnly, indentPerLevel, lineWidth, testAmbiguousType) { + var i; + var char, prev_char; + var hasLineBreak = false; + var hasFoldableLine = false; // only checked if shouldTrackWidth + var shouldTrackWidth = lineWidth !== -1; + var previousLineBreak = -1; // count the first line correctly + var plain = isPlainSafeFirst(string.charCodeAt(0)) + && !isWhitespace(string.charCodeAt(string.length - 1)); -/***/ 22671: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (singleLineOnly) { + // Case: no block styles. + // Check for disallowed characters to rule out plain and single. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + } else { + // Case: block styles permitted. + for (i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + if (char === CHAR_LINE_FEED) { + hasLineBreak = true; + // Check if any line can be folded. + if (shouldTrackWidth) { + hasFoldableLine = hasFoldableLine || + // Foldable line = too long, and not more-indented. + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' '); + previousLineBreak = i; + } + } else if (!isPrintable(char)) { + return STYLE_DOUBLE; + } + prev_char = i > 0 ? string.charCodeAt(i - 1) : null; + plain = plain && isPlainSafe(char, prev_char); + } + // in case the end is missing a \n + hasFoldableLine = hasFoldableLine || (shouldTrackWidth && + (i - previousLineBreak - 1 > lineWidth && + string[previousLineBreak + 1] !== ' ')); + } + // Although every style can represent \n without escaping, prefer block styles + // for multiline, since they're more readable and they don't add empty lines. + // Also prefer folding a super-long line. + if (!hasLineBreak && !hasFoldableLine) { + // Strings interpretable as another type have to be quoted; + // e.g. the string 'true' vs. the boolean true. + return plain && !testAmbiguousType(string) + ? STYLE_PLAIN : STYLE_SINGLE; + } + // Edge case: block indentation indicator can only have one digit. + if (indentPerLevel > 9 && needIndentIndicator(string)) { + return STYLE_DOUBLE; + } + // At this point we know block styles are valid. + // Prefer literal style unless we want to fold. + return hasFoldableLine ? STYLE_FOLDED : STYLE_LITERAL; +} -"use strict"; +// Note: line breaking/folding is implemented for only the folded style. +// NB. We drop the last trailing newline (if any) of a returned block scalar +// since the dumper adds its own newline. This always works: +// • No ending newline => unaffected; already using strip "-" chomping. +// • Ending newline => removed then restored. +// Importantly, this keeps the "+" chomp indicator from gaining an extra line. +function writeScalar(state, string, level, iskey) { + state.dump = (function () { + if (string.length === 0) { + return "''"; + } + if (!state.noCompatMode && + DEPRECATED_BOOLEANS_SYNTAX.indexOf(string) !== -1) { + return "'" + string + "'"; + } + var indent = state.indent * Math.max(1, level); // no 0-indent scalars + // As indentation gets deeper, let the width decrease monotonically + // to the lower bound min(state.lineWidth, 40). + // Note that this implies + // state.lineWidth ≤ 40 + state.indent: width is fixed at the lower bound. + // state.lineWidth > 40 + state.indent: width decreases until the lower bound. + // This behaves better than a constant minimum width which disallows narrower options, + // or an indent threshold which causes the width to suddenly increase. + var lineWidth = state.lineWidth === -1 + ? -1 : Math.max(Math.min(state.lineWidth, 40), state.lineWidth - indent); -var Type = __nccwpck_require__(30967); + // Without knowing if keys are implicit/explicit, assume implicit for safety. + var singleLineOnly = iskey + // No block styles in flow mode. + || (state.flowLevel > -1 && level >= state.flowLevel); + function testAmbiguity(string) { + return testImplicitResolving(state, string); + } -function resolveYamlNull(data) { - if (data === null) return true; + switch (chooseScalarStyle(string, singleLineOnly, state.indent, lineWidth, testAmbiguity)) { + case STYLE_PLAIN: + return string; + case STYLE_SINGLE: + return "'" + string.replace(/'/g, "''") + "'"; + case STYLE_LITERAL: + return '|' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(string, indent)); + case STYLE_FOLDED: + return '>' + blockHeader(string, state.indent) + + dropEndingNewline(indentString(foldString(string, lineWidth), indent)); + case STYLE_DOUBLE: + return '"' + escapeString(string, lineWidth) + '"'; + default: + throw new YAMLException('impossible error: invalid scalar style'); + } + }()); +} - var max = data.length; +// Pre-conditions: string is valid for a block scalar, 1 <= indentPerLevel <= 9. +function blockHeader(string, indentPerLevel) { + var indentIndicator = needIndentIndicator(string) ? String(indentPerLevel) : ''; - return (max === 1 && data === '~') || - (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); -} + // note the special case: the string '\n' counts as a "trailing" empty line. + var clip = string[string.length - 1] === '\n'; + var keep = clip && (string[string.length - 2] === '\n' || string === '\n'); + var chomp = keep ? '+' : (clip ? '' : '-'); -function constructYamlNull() { - return null; + return indentIndicator + chomp + '\n'; } -function isNull(object) { - return object === null; +// (See the note for writeScalar.) +function dropEndingNewline(string) { + return string[string.length - 1] === '\n' ? string.slice(0, -1) : string; } -module.exports = new Type('tag:yaml.org,2002:null', { - kind: 'scalar', - resolve: resolveYamlNull, - construct: constructYamlNull, - predicate: isNull, - represent: { - canonical: function () { return '~'; }, - lowercase: function () { return 'null'; }, - uppercase: function () { return 'NULL'; }, - camelcase: function () { return 'Null'; } - }, - defaultStyle: 'lowercase' -}); - - -/***/ }), +// Note: a long line without a suitable break point will exceed the width limit. +// Pre-conditions: every char in str isPrintable, str.length > 0, width > 0. +function foldString(string, width) { + // In folded style, $k$ consecutive newlines output as $k+1$ newlines— + // unless they're before or after a more-indented line, or at the very + // beginning or end, in which case $k$ maps to $k$. + // Therefore, parse each chunk as newline(s) followed by a content line. + var lineRe = /(\n+)([^\n]*)/g; -/***/ 96668: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // first line (possibly an empty line) + var result = (function () { + var nextLF = string.indexOf('\n'); + nextLF = nextLF !== -1 ? nextLF : string.length; + lineRe.lastIndex = nextLF; + return foldLine(string.slice(0, nextLF), width); + }()); + // If we haven't reached the first content line yet, don't add an extra \n. + var prevMoreIndented = string[0] === '\n' || string[0] === ' '; + var moreIndented; -"use strict"; + // rest of the lines + var match; + while ((match = lineRe.exec(string))) { + var prefix = match[1], line = match[2]; + moreIndented = (line[0] === ' '); + result += prefix + + (!prevMoreIndented && !moreIndented && line !== '' + ? '\n' : '') + + foldLine(line, width); + prevMoreIndented = moreIndented; + } + return result; +} -var Type = __nccwpck_require__(30967); +// Greedy line breaking. +// Picks the longest line under the limit each time, +// otherwise settles for the shortest line over the limit. +// NB. More-indented lines *cannot* be folded, as that would add an extra \n. +function foldLine(line, width) { + if (line === '' || line[0] === ' ') return line; -var _hasOwnProperty = Object.prototype.hasOwnProperty; -var _toString = Object.prototype.toString; + // Since a more-indented line adds a \n, breaks can't be followed by a space. + var breakRe = / [^ ]/g; // note: the match index will always be <= length-2. + var match; + // start is an inclusive index. end, curr, and next are exclusive. + var start = 0, end, curr = 0, next = 0; + var result = ''; -function resolveYamlOmap(data) { - if (data === null) return true; + // Invariants: 0 <= start <= length-1. + // 0 <= curr <= next <= max(0, length-2). curr - start <= width. + // Inside the loop: + // A match implies length >= 2, so curr and next are <= length-2. + while ((match = breakRe.exec(line))) { + next = match.index; + // maintain invariant: curr - start <= width + if (next - start > width) { + end = (curr > start) ? curr : next; // derive end <= length-2 + result += '\n' + line.slice(start, end); + // skip the space that was output as \n + start = end + 1; // derive start <= length-1 + } + curr = next; + } - var objectKeys = [], index, length, pair, pairKey, pairHasKey, - object = data; + // By the invariants, start <= length-1, so there is something left over. + // It is either the whole string or a part starting from non-whitespace. + result += '\n'; + // Insert a break if the remainder is too long and there is a break available. + if (line.length - start > width && curr > start) { + result += line.slice(start, curr) + '\n' + line.slice(curr + 1); + } else { + result += line.slice(start); + } - for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - pairHasKey = false; + return result.slice(1); // drop extra \n joiner +} - if (_toString.call(pair) !== '[object Object]') return false; +// Escapes a double-quoted string. +function escapeString(string) { + var result = ''; + var char, nextChar; + var escapeSeq; - for (pairKey in pair) { - if (_hasOwnProperty.call(pair, pairKey)) { - if (!pairHasKey) pairHasKey = true; - else return false; + for (var i = 0; i < string.length; i++) { + char = string.charCodeAt(i); + // Check for surrogate pairs (reference Unicode 3.0 section "3.7 Surrogates"). + if (char >= 0xD800 && char <= 0xDBFF/* high surrogate */) { + nextChar = string.charCodeAt(i + 1); + if (nextChar >= 0xDC00 && nextChar <= 0xDFFF/* low surrogate */) { + // Combine the surrogate pair and store it escaped. + result += encodeHex((char - 0xD800) * 0x400 + nextChar - 0xDC00 + 0x10000); + // Advance index one extra since we already used that char here. + i++; continue; } } - - if (!pairHasKey) return false; - - if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); - else return false; + escapeSeq = ESCAPE_SEQUENCES[char]; + result += !escapeSeq && isPrintable(char) + ? string[i] + : escapeSeq || encodeHex(char); } - return true; -} - -function constructYamlOmap(data) { - return data !== null ? data : []; + return result; } -module.exports = new Type('tag:yaml.org,2002:omap', { - kind: 'sequence', - resolve: resolveYamlOmap, - construct: constructYamlOmap -}); - - -/***/ }), - -/***/ 76039: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(30967); - -var _toString = Object.prototype.toString; - -function resolveYamlPairs(data) { - if (data === null) return true; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); +function writeFlowSequence(state, level, object) { + var _result = '', + _tag = state.tag, + index, + length; for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; - - if (_toString.call(pair) !== '[object Object]') return false; - - keys = Object.keys(pair); - - if (keys.length !== 1) return false; - - result[index] = [ keys[0], pair[keys[0]] ]; + // Write only valid elements. + if (writeNode(state, level, object[index], false, false)) { + if (index !== 0) _result += ',' + (!state.condenseFlow ? ' ' : ''); + _result += state.dump; + } } - return true; + state.tag = _tag; + state.dump = '[' + _result + ']'; } -function constructYamlPairs(data) { - if (data === null) return []; - - var index, length, pair, keys, result, - object = data; - - result = new Array(object.length); +function writeBlockSequence(state, level, object, compact) { + var _result = '', + _tag = state.tag, + index, + length; for (index = 0, length = object.length; index < length; index += 1) { - pair = object[index]; + // Write only valid elements. + if (writeNode(state, level + 1, object[index], true, true)) { + if (!compact || index !== 0) { + _result += generateNextLine(state, level); + } - keys = Object.keys(pair); + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + _result += '-'; + } else { + _result += '- '; + } - result[index] = [ keys[0], pair[keys[0]] ]; + _result += state.dump; + } } - return result; + state.tag = _tag; + state.dump = _result || '[]'; // Empty sequence if no valid values. } -module.exports = new Type('tag:yaml.org,2002:pairs', { - kind: 'sequence', - resolve: resolveYamlPairs, - construct: constructYamlPairs -}); - - -/***/ }), - -/***/ 5490: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -"use strict"; - - -var Type = __nccwpck_require__(30967); - -module.exports = new Type('tag:yaml.org,2002:seq', { - kind: 'sequence', - construct: function (data) { return data !== null ? data : []; } -}); +function writeFlowMapping(state, level, object) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + pairBuffer; + for (index = 0, length = objectKeyList.length; index < length; index += 1) { -/***/ }), + pairBuffer = ''; + if (index !== 0) pairBuffer += ', '; -/***/ 69237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (state.condenseFlow) pairBuffer += '"'; -"use strict"; + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; + if (!writeNode(state, level, objectKey, false, false)) { + continue; // Skip this pair because of invalid key; + } -var Type = __nccwpck_require__(30967); + if (state.dump.length > 1024) pairBuffer += '? '; -var _hasOwnProperty = Object.prototype.hasOwnProperty; + pairBuffer += state.dump + (state.condenseFlow ? '"' : '') + ':' + (state.condenseFlow ? '' : ' '); -function resolveYamlSet(data) { - if (data === null) return true; + if (!writeNode(state, level, objectValue, false, false)) { + continue; // Skip this pair because of invalid value. + } - var key, object = data; + pairBuffer += state.dump; - for (key in object) { - if (_hasOwnProperty.call(object, key)) { - if (object[key] !== null) return false; - } + // Both key and value are valid. + _result += pairBuffer; } - return true; -} - -function constructYamlSet(data) { - return data !== null ? data : {}; + state.tag = _tag; + state.dump = '{' + _result + '}'; } -module.exports = new Type('tag:yaml.org,2002:set', { - kind: 'mapping', - resolve: resolveYamlSet, - construct: constructYamlSet -}); - - -/***/ }), +function writeBlockMapping(state, level, object, compact) { + var _result = '', + _tag = state.tag, + objectKeyList = Object.keys(object), + index, + length, + objectKey, + objectValue, + explicitPair, + pairBuffer; -/***/ 52672: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + // Allow sorting keys so that the output file is deterministic + if (state.sortKeys === true) { + // Default sorting + objectKeyList.sort(); + } else if (typeof state.sortKeys === 'function') { + // Custom sort function + objectKeyList.sort(state.sortKeys); + } else if (state.sortKeys) { + // Something is wrong + throw new YAMLException('sortKeys must be a boolean or a function'); + } -"use strict"; + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + pairBuffer = ''; + if (!compact || index !== 0) { + pairBuffer += generateNextLine(state, level); + } -var Type = __nccwpck_require__(30967); + objectKey = objectKeyList[index]; + objectValue = object[objectKey]; -module.exports = new Type('tag:yaml.org,2002:str', { - kind: 'scalar', - construct: function (data) { return data !== null ? data : ''; } -}); + if (!writeNode(state, level + 1, objectKey, true, true, true)) { + continue; // Skip this pair because of invalid key. + } + explicitPair = (state.tag !== null && state.tag !== '?') || + (state.dump && state.dump.length > 1024); -/***/ }), + if (explicitPair) { + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += '?'; + } else { + pairBuffer += '? '; + } + } -/***/ 83714: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + pairBuffer += state.dump; -"use strict"; + if (explicitPair) { + pairBuffer += generateNextLine(state, level); + } + if (!writeNode(state, level + 1, objectValue, true, explicitPair)) { + continue; // Skip this pair because of invalid value. + } -var Type = __nccwpck_require__(30967); + if (state.dump && CHAR_LINE_FEED === state.dump.charCodeAt(0)) { + pairBuffer += ':'; + } else { + pairBuffer += ': '; + } -var YAML_DATE_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9])' + // [2] month - '-([0-9][0-9])$'); // [3] day + pairBuffer += state.dump; -var YAML_TIMESTAMP_REGEXP = new RegExp( - '^([0-9][0-9][0-9][0-9])' + // [1] year - '-([0-9][0-9]?)' + // [2] month - '-([0-9][0-9]?)' + // [3] day - '(?:[Tt]|[ \\t]+)' + // ... - '([0-9][0-9]?)' + // [4] hour - ':([0-9][0-9])' + // [5] minute - ':([0-9][0-9])' + // [6] second - '(?:\\.([0-9]*))?' + // [7] fraction - '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour - '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + // Both key and value are valid. + _result += pairBuffer; + } -function resolveYamlTimestamp(data) { - if (data === null) return false; - if (YAML_DATE_REGEXP.exec(data) !== null) return true; - if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; - return false; + state.tag = _tag; + state.dump = _result || '{}'; // Empty mapping if no valid pairs. } -function constructYamlTimestamp(data) { - var match, year, month, day, hour, minute, second, fraction = 0, - delta = null, tz_hour, tz_minute, date; +function detectType(state, object, explicit) { + var _result, typeList, index, length, type, style; - match = YAML_DATE_REGEXP.exec(data); - if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); + typeList = explicit ? state.explicitTypes : state.implicitTypes; - if (match === null) throw new Error('Date resolve error'); + for (index = 0, length = typeList.length; index < length; index += 1) { + type = typeList[index]; - // match: [1] year [2] month [3] day + if ((type.instanceOf || type.predicate) && + (!type.instanceOf || ((typeof object === 'object') && (object instanceof type.instanceOf))) && + (!type.predicate || type.predicate(object))) { - year = +(match[1]); - month = +(match[2]) - 1; // JS month starts with 0 - day = +(match[3]); + state.tag = explicit ? type.tag : '?'; - if (!match[4]) { // no hour - return new Date(Date.UTC(year, month, day)); - } + if (type.represent) { + style = state.styleMap[type.tag] || type.defaultStyle; - // match: [4] hour [5] minute [6] second [7] fraction + if (_toString.call(type.represent) === '[object Function]') { + _result = type.represent(object, style); + } else if (_hasOwnProperty.call(type.represent, style)) { + _result = type.represent[style](object, style); + } else { + throw new YAMLException('!<' + type.tag + '> tag resolver accepts not "' + style + '" style'); + } - hour = +(match[4]); - minute = +(match[5]); - second = +(match[6]); + state.dump = _result; + } - if (match[7]) { - fraction = match[7].slice(0, 3); - while (fraction.length < 3) { // milli-seconds - fraction += '0'; + return true; } - fraction = +fraction; - } - - // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute - - if (match[9]) { - tz_hour = +(match[10]); - tz_minute = +(match[11] || 0); - delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds - if (match[9] === '-') delta = -delta; } - date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); - - if (delta) date.setTime(date.getTime() - delta); - - return date; + return false; } -function representYamlTimestamp(object /*, style*/) { - return object.toISOString(); -} +// Serializes `object` and writes it to global `result`. +// Returns true on success, or false on invalid object. +// +function writeNode(state, level, object, block, compact, iskey) { + state.tag = null; + state.dump = object; -module.exports = new Type('tag:yaml.org,2002:timestamp', { - kind: 'scalar', - resolve: resolveYamlTimestamp, - construct: constructYamlTimestamp, - instanceOf: Date, - represent: representYamlTimestamp -}); + if (!detectType(state, object, false)) { + detectType(state, object, true); + } + var type = _toString.call(state.dump); -/***/ }), + if (block) { + block = (state.flowLevel < 0 || state.flowLevel > level); + } -/***/ 55586: -/***/ ((module) => { + var objectOrArray = type === '[object Object]' || type === '[object Array]', + duplicateIndex, + duplicate; -"use strict"; + if (objectOrArray) { + duplicateIndex = state.duplicates.indexOf(object); + duplicate = duplicateIndex !== -1; + } + if ((state.tag !== null && state.tag !== '?') || duplicate || (state.indent !== 2 && level > 0)) { + compact = false; + } -module.exports = parseJson -function parseJson (txt, reviver, context) { - context = context || 20 - try { - return JSON.parse(txt, reviver) - } catch (e) { - if (typeof txt !== 'string') { - const isEmptyArray = Array.isArray(txt) && txt.length === 0 - const errorMessage = 'Cannot parse ' + - (isEmptyArray ? 'an empty array' : String(txt)) - throw new TypeError(errorMessage) + if (duplicate && state.usedDuplicates[duplicateIndex]) { + state.dump = '*ref_' + duplicateIndex; + } else { + if (objectOrArray && duplicate && !state.usedDuplicates[duplicateIndex]) { + state.usedDuplicates[duplicateIndex] = true; } - const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i) - const errIdx = syntaxErr - ? +syntaxErr[1] - : e.message.match(/^Unexpected end of JSON.*/i) - ? txt.length - 1 - : null - if (errIdx != null) { - const start = errIdx <= context - ? 0 - : errIdx - context - const end = errIdx + context >= txt.length - ? txt.length - : errIdx + context - e.message += ` while parsing near '${ - start === 0 ? '' : '...' - }${txt.slice(start, end)}${ - end === txt.length ? '' : '...' - }'` + if (type === '[object Object]') { + if (block && (Object.keys(state.dump).length !== 0)) { + writeBlockMapping(state, level, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowMapping(state, level, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object Array]') { + var arrayLevel = (state.noArrayIndent && (level > 0)) ? level - 1 : level; + if (block && (state.dump.length !== 0)) { + writeBlockSequence(state, arrayLevel, state.dump, compact); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + state.dump; + } + } else { + writeFlowSequence(state, arrayLevel, state.dump); + if (duplicate) { + state.dump = '&ref_' + duplicateIndex + ' ' + state.dump; + } + } + } else if (type === '[object String]') { + if (state.tag !== '?') { + writeScalar(state, state.dump, level, iskey); + } } else { - e.message += ` while parsing '${txt.slice(0, context * 2)}'` + if (state.skipInvalid) return false; + throw new YAMLException('unacceptable kind of an object to dump ' + type); + } + + if (state.tag !== null && state.tag !== '?') { + state.dump = '!<' + state.tag + '> ' + state.dump; } - throw e } -} + return true; +} -/***/ }), +function getDuplicateReferences(object, state) { + var objects = [], + duplicatesIndexes = [], + index, + length; -/***/ 53359: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + inspectNode(object, objects, duplicatesIndexes); -var jws = __nccwpck_require__(4636); + for (index = 0, length = duplicatesIndexes.length; index < length; index += 1) { + state.duplicates.push(objects[duplicatesIndexes[index]]); + } + state.usedDuplicates = new Array(length); +} -module.exports = function (jwt, options) { - options = options || {}; - var decoded = jws.decode(jwt, options); - if (!decoded) { return null; } - var payload = decoded.payload; +function inspectNode(object, objects, duplicatesIndexes) { + var objectKeyList, + index, + length; - //try parse the payload - if(typeof payload === 'string') { - try { - var obj = JSON.parse(payload); - if(obj !== null && typeof obj === 'object') { - payload = obj; + if (object !== null && typeof object === 'object') { + index = objects.indexOf(object); + if (index !== -1) { + if (duplicatesIndexes.indexOf(index) === -1) { + duplicatesIndexes.push(index); } - } catch (e) { } - } + } else { + objects.push(object); - //return header if `complete` option is enabled. header includes claims - //such as `kid` and `alg` used to select the key within a JWKS needed to - //verify the signature - if (options.complete === true) { - return { - header: decoded.header, - payload: payload, - signature: decoded.signature - }; + if (Array.isArray(object)) { + for (index = 0, length = object.length; index < length; index += 1) { + inspectNode(object[index], objects, duplicatesIndexes); + } + } else { + objectKeyList = Object.keys(object); + + for (index = 0, length = objectKeyList.length; index < length; index += 1) { + inspectNode(object[objectKeyList[index]], objects, duplicatesIndexes); + } + } + } } - return payload; -}; +} +function dump(input, options) { + options = options || {}; -/***/ }), + var state = new State(options); -/***/ 77486: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (!state.noRefs) getDuplicateReferences(input, state); -module.exports = { - decode: __nccwpck_require__(53359), - verify: __nccwpck_require__(12327), - sign: __nccwpck_require__(82022), - JsonWebTokenError: __nccwpck_require__(405), - NotBeforeError: __nccwpck_require__(4383), - TokenExpiredError: __nccwpck_require__(46637), -}; + if (writeNode(state, 0, input, true, true)) return state.dump + '\n'; + return ''; +} -/***/ }), +function safeDump(input, options) { + return dump(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} -/***/ 405: -/***/ ((module) => { +module.exports.dump = dump; +module.exports.safeDump = safeDump; -var JsonWebTokenError = function (message, error) { - Error.call(this, message); - if(Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.name = 'JsonWebTokenError'; - this.message = message; - if (error) this.inner = error; -}; -JsonWebTokenError.prototype = Object.create(Error.prototype); -JsonWebTokenError.prototype.constructor = JsonWebTokenError; +/***/ }), -module.exports = JsonWebTokenError; +/***/ 65199: +/***/ ((module) => { +"use strict"; +// YAML error class. http://stackoverflow.com/questions/8458984 +// -/***/ }), -/***/ 4383: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +function YAMLException(reason, mark) { + // Super constructor + Error.call(this); -var JsonWebTokenError = __nccwpck_require__(405); + this.name = 'YAMLException'; + this.reason = reason; + this.mark = mark; + this.message = (this.reason || '(unknown reason)') + (this.mark ? ' ' + this.mark.toString() : ''); -var NotBeforeError = function (message, date) { - JsonWebTokenError.call(this, message); - this.name = 'NotBeforeError'; - this.date = date; -}; + // Include stack trace in error object + if (Error.captureStackTrace) { + // Chrome and NodeJS + Error.captureStackTrace(this, this.constructor); + } else { + // FF, IE 10+ and Safari 6+. Fallback for others + this.stack = (new Error()).stack || ''; + } +} -NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype); -NotBeforeError.prototype.constructor = NotBeforeError; +// Inherit from Error +YAMLException.prototype = Object.create(Error.prototype); +YAMLException.prototype.constructor = YAMLException; -module.exports = NotBeforeError; -/***/ }), +YAMLException.prototype.toString = function toString(compact) { + var result = this.name + ': '; -/***/ 46637: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + result += this.reason || '(unknown reason)'; -var JsonWebTokenError = __nccwpck_require__(405); + if (!compact && this.mark) { + result += ' ' + this.mark.toString(); + } -var TokenExpiredError = function (message, expiredAt) { - JsonWebTokenError.call(this, message); - this.name = 'TokenExpiredError'; - this.expiredAt = expiredAt; + return result; }; -TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype); -TokenExpiredError.prototype.constructor = TokenExpiredError; +module.exports = YAMLException; -module.exports = TokenExpiredError; /***/ }), -/***/ 59085: +/***/ 45190: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var semver = __nccwpck_require__(27174); +"use strict"; -module.exports = semver.satisfies(process.version, '^6.12.0 || >=8.0.0'); +/*eslint-disable max-len,no-use-before-define*/ -/***/ }), +var common = __nccwpck_require__(59136); +var YAMLException = __nccwpck_require__(65199); +var Mark = __nccwpck_require__(55426); +var DEFAULT_SAFE_SCHEMA = __nccwpck_require__(48949); +var DEFAULT_FULL_SCHEMA = __nccwpck_require__(56874); -/***/ 46098: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var ms = __nccwpck_require__(80900); +var _hasOwnProperty = Object.prototype.hasOwnProperty; -module.exports = function (time, iat) { - var timestamp = iat || Math.floor(Date.now() / 1000); - if (typeof time === 'string') { - var milliseconds = ms(time); - if (typeof milliseconds === 'undefined') { - return; - } - return Math.floor(timestamp + milliseconds / 1000); - } else if (typeof time === 'number') { - return timestamp + time; - } else { - return; - } +var CONTEXT_FLOW_IN = 1; +var CONTEXT_FLOW_OUT = 2; +var CONTEXT_BLOCK_IN = 3; +var CONTEXT_BLOCK_OUT = 4; -}; -/***/ }), +var CHOMPING_CLIP = 1; +var CHOMPING_STRIP = 2; +var CHOMPING_KEEP = 3; -/***/ 27174: -/***/ ((module, exports) => { -exports = module.exports = SemVer +var PATTERN_NON_PRINTABLE = /[\x00-\x08\x0B\x0C\x0E-\x1F\x7F-\x84\x86-\x9F\uFFFE\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]/; +var PATTERN_NON_ASCII_LINE_BREAKS = /[\x85\u2028\u2029]/; +var PATTERN_FLOW_INDICATORS = /[,\[\]\{\}]/; +var PATTERN_TAG_HANDLE = /^(?:!|!!|![a-z\-]+!)$/i; +var PATTERN_TAG_URI = /^(?:!|[^,\[\]\{\}])(?:%[0-9a-f]{2}|[0-9a-z\-#;\/\?:@&=\+\$,_\.!~\*'\(\)\[\]])*$/i; -var debug -/* istanbul ignore next */ -if (typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG)) { - debug = function () { - var args = Array.prototype.slice.call(arguments, 0) - args.unshift('SEMVER') - console.log.apply(console, args) - } -} else { - debug = function () {} -} -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -exports.SEMVER_SPEC_VERSION = '2.0.0' +function _class(obj) { return Object.prototype.toString.call(obj); } -var MAX_LENGTH = 256 -var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || - /* istanbul ignore next */ 9007199254740991 +function is_EOL(c) { + return (c === 0x0A/* LF */) || (c === 0x0D/* CR */); +} -// Max safe segment length for coercion. -var MAX_SAFE_COMPONENT_LENGTH = 16 +function is_WHITE_SPACE(c) { + return (c === 0x09/* Tab */) || (c === 0x20/* Space */); +} -// The actual regexps go on exports.re -var re = exports.re = [] -var src = exports.src = [] -var R = 0 +function is_WS_OR_EOL(c) { + return (c === 0x09/* Tab */) || + (c === 0x20/* Space */) || + (c === 0x0A/* LF */) || + (c === 0x0D/* CR */); +} -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. +function is_FLOW_INDICATOR(c) { + return c === 0x2C/* , */ || + c === 0x5B/* [ */ || + c === 0x5D/* ] */ || + c === 0x7B/* { */ || + c === 0x7D/* } */; +} -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. +function fromHexCode(c) { + var lc; -var NUMERICIDENTIFIER = R++ -src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' -var NUMERICIDENTIFIERLOOSE = R++ -src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. + /*eslint-disable no-bitwise*/ + lc = c | 0x20; -var NONNUMERICIDENTIFIER = R++ -src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' + if ((0x61/* a */ <= lc) && (lc <= 0x66/* f */)) { + return lc - 0x61 + 10; + } -// ## Main Version -// Three dot-separated numeric identifiers. + return -1; +} -var MAINVERSION = R++ -src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')\\.' + - '(' + src[NUMERICIDENTIFIER] + ')' +function escapedHexLen(c) { + if (c === 0x78/* x */) { return 2; } + if (c === 0x75/* u */) { return 4; } + if (c === 0x55/* U */) { return 8; } + return 0; +} -var MAINVERSIONLOOSE = R++ -src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + - '(' + src[NUMERICIDENTIFIERLOOSE] + ')' +function fromDecimalCode(c) { + if ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) { + return c - 0x30; + } -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. + return -1; +} -var PRERELEASEIDENTIFIER = R++ -src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + - '|' + src[NONNUMERICIDENTIFIER] + ')' +function simpleEscapeSequence(c) { + /* eslint-disable indent */ + return (c === 0x30/* 0 */) ? '\x00' : + (c === 0x61/* a */) ? '\x07' : + (c === 0x62/* b */) ? '\x08' : + (c === 0x74/* t */) ? '\x09' : + (c === 0x09/* Tab */) ? '\x09' : + (c === 0x6E/* n */) ? '\x0A' : + (c === 0x76/* v */) ? '\x0B' : + (c === 0x66/* f */) ? '\x0C' : + (c === 0x72/* r */) ? '\x0D' : + (c === 0x65/* e */) ? '\x1B' : + (c === 0x20/* Space */) ? ' ' : + (c === 0x22/* " */) ? '\x22' : + (c === 0x2F/* / */) ? '/' : + (c === 0x5C/* \ */) ? '\x5C' : + (c === 0x4E/* N */) ? '\x85' : + (c === 0x5F/* _ */) ? '\xA0' : + (c === 0x4C/* L */) ? '\u2028' : + (c === 0x50/* P */) ? '\u2029' : ''; +} -var PRERELEASEIDENTIFIERLOOSE = R++ -src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + - '|' + src[NONNUMERICIDENTIFIER] + ')' +function charFromCodepoint(c) { + if (c <= 0xFFFF) { + return String.fromCharCode(c); + } + // Encode UTF-16 surrogate pair + // https://en.wikipedia.org/wiki/UTF-16#Code_points_U.2B010000_to_U.2B10FFFF + return String.fromCharCode( + ((c - 0x010000) >> 10) + 0xD800, + ((c - 0x010000) & 0x03FF) + 0xDC00 + ); +} -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. +var simpleEscapeCheck = new Array(256); // integer, for fast access +var simpleEscapeMap = new Array(256); +for (var i = 0; i < 256; i++) { + simpleEscapeCheck[i] = simpleEscapeSequence(i) ? 1 : 0; + simpleEscapeMap[i] = simpleEscapeSequence(i); +} -var PRERELEASE = R++ -src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + - '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' -var PRERELEASELOOSE = R++ -src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + - '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' +function State(input, options) { + this.input = input; -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. + this.filename = options['filename'] || null; + this.schema = options['schema'] || DEFAULT_FULL_SCHEMA; + this.onWarning = options['onWarning'] || null; + this.legacy = options['legacy'] || false; + this.json = options['json'] || false; + this.listener = options['listener'] || null; -var BUILDIDENTIFIER = R++ -src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' + this.implicitTypes = this.schema.compiledImplicit; + this.typeMap = this.schema.compiledTypeMap; -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. + this.length = input.length; + this.position = 0; + this.line = 0; + this.lineStart = 0; + this.lineIndent = 0; -var BUILD = R++ -src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + - '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' + this.documents = []; -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. + /* + this.version; + this.checkLineBreaks; + this.tagMap; + this.anchorMap; + this.tag; + this.anchor; + this.kind; + this.result;*/ -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. +} -var FULL = R++ -var FULLPLAIN = 'v?' + src[MAINVERSION] + - src[PRERELEASE] + '?' + - src[BUILD] + '?' -src[FULL] = '^' + FULLPLAIN + '$' +function generateError(state, message) { + return new YAMLException( + message, + new Mark(state.filename, state.input, state.position, state.line, (state.position - state.lineStart))); +} -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + - src[PRERELEASELOOSE] + '?' + - src[BUILD] + '?' +function throwError(state, message) { + throw generateError(state, message); +} -var LOOSE = R++ -src[LOOSE] = '^' + LOOSEPLAIN + '$' +function throwWarning(state, message) { + if (state.onWarning) { + state.onWarning.call(null, generateError(state, message)); + } +} -var GTLT = R++ -src[GTLT] = '((?:<|>)?=?)' -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -var XRANGEIDENTIFIERLOOSE = R++ -src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' -var XRANGEIDENTIFIER = R++ -src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' +var directiveHandlers = { -var XRANGEPLAIN = R++ -src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + - '(?:' + src[PRERELEASE] + ')?' + - src[BUILD] + '?' + - ')?)?' + YAML: function handleYamlDirective(state, name, args) { -var XRANGEPLAINLOOSE = R++ -src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + - '(?:' + src[PRERELEASELOOSE] + ')?' + - src[BUILD] + '?' + - ')?)?' + var match, major, minor; -var XRANGE = R++ -src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' -var XRANGELOOSE = R++ -src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' + if (state.version !== null) { + throwError(state, 'duplication of %YAML directive'); + } -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -var COERCE = R++ -src[COERCE] = '(?:^|[^\\d])' + - '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + - '(?:$|[^\\d])' + if (args.length !== 1) { + throwError(state, 'YAML directive accepts exactly one argument'); + } -// Tilde ranges. -// Meaning is "reasonably at or greater than" -var LONETILDE = R++ -src[LONETILDE] = '(?:~>?)' + match = /^([0-9]+)\.([0-9]+)$/.exec(args[0]); -var TILDETRIM = R++ -src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' -re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') -var tildeTrimReplace = '$1~' + if (match === null) { + throwError(state, 'ill-formed argument of the YAML directive'); + } -var TILDE = R++ -src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' -var TILDELOOSE = R++ -src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' + major = parseInt(match[1], 10); + minor = parseInt(match[2], 10); -// Caret ranges. -// Meaning is "at least and backwards compatible with" -var LONECARET = R++ -src[LONECARET] = '(?:\\^)' + if (major !== 1) { + throwError(state, 'unacceptable YAML version of the document'); + } -var CARETTRIM = R++ -src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' -re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') -var caretTrimReplace = '$1^' + state.version = args[0]; + state.checkLineBreaks = (minor < 2); -var CARET = R++ -src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' -var CARETLOOSE = R++ -src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' + if (minor !== 1 && minor !== 2) { + throwWarning(state, 'unsupported YAML version of the document'); + } + }, -// A simple gt/lt/eq thing, or just "" to indicate "any version" -var COMPARATORLOOSE = R++ -src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' -var COMPARATOR = R++ -src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' + TAG: function handleTagDirective(state, name, args) { -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -var COMPARATORTRIM = R++ -src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + - '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' + var handle, prefix; -// this one has to use the /g flag -re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') -var comparatorTrimReplace = '$1$2$3' + if (args.length !== 2) { + throwError(state, 'TAG directive accepts exactly two arguments'); + } -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -var HYPHENRANGE = R++ -src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAIN] + ')' + - '\\s*$' + handle = args[0]; + prefix = args[1]; -var HYPHENRANGELOOSE = R++ -src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s+-\\s+' + - '(' + src[XRANGEPLAINLOOSE] + ')' + - '\\s*$' + if (!PATTERN_TAG_HANDLE.test(handle)) { + throwError(state, 'ill-formed tag handle (first argument) of the TAG directive'); + } -// Star ranges basically just allow anything at all. -var STAR = R++ -src[STAR] = '(<|>)?=?\\s*\\*' + if (_hasOwnProperty.call(state.tagMap, handle)) { + throwError(state, 'there is a previously declared suffix for "' + handle + '" tag handle'); + } -// Compile to actual regexp objects. -// All are flag-free, unless they were created above with a flag. -for (var i = 0; i < R; i++) { - debug(i, src[i]) - if (!re[i]) { - re[i] = new RegExp(src[i]) + if (!PATTERN_TAG_URI.test(prefix)) { + throwError(state, 'ill-formed tag prefix (second argument) of the TAG directive'); + } + + state.tagMap[handle] = prefix; } -} +}; -exports.parse = parse -function parse (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false + +function captureSegment(state, start, end, checkJson) { + var _position, _length, _character, _result; + + if (start < end) { + _result = state.input.slice(start, end); + + if (checkJson) { + for (_position = 0, _length = _result.length; _position < _length; _position += 1) { + _character = _result.charCodeAt(_position); + if (!(_character === 0x09 || + (0x20 <= _character && _character <= 0x10FFFF))) { + throwError(state, 'expected valid JSON character'); + } + } + } else if (PATTERN_NON_PRINTABLE.test(_result)) { + throwError(state, 'the stream contains non-printable characters'); } - } - if (version instanceof SemVer) { - return version + state.result += _result; } +} - if (typeof version !== 'string') { - return null - } +function mergeMappings(state, destination, source, overridableKeys) { + var sourceKeys, key, index, quantity; - if (version.length > MAX_LENGTH) { - return null + if (!common.isObject(source)) { + throwError(state, 'cannot merge mappings; the provided source object is unacceptable'); } - var r = options.loose ? re[LOOSE] : re[FULL] - if (!r.test(version)) { - return null - } + sourceKeys = Object.keys(source); - try { - return new SemVer(version, options) - } catch (er) { - return null + for (index = 0, quantity = sourceKeys.length; index < quantity; index += 1) { + key = sourceKeys[index]; + + if (!_hasOwnProperty.call(destination, key)) { + destination[key] = source[key]; + overridableKeys[key] = true; + } } } -exports.valid = valid -function valid (version, options) { - var v = parse(version, options) - return v ? v.version : null -} +function storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, startLine, startPos) { + var index, quantity; -exports.clean = clean -function clean (version, options) { - var s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} + // The output is a plain object here, so keys can only be strings. + // We need to convert keyNode to a string, but doing so can hang the process + // (deeply nested arrays that explode exponentially using aliases). + if (Array.isArray(keyNode)) { + keyNode = Array.prototype.slice.call(keyNode); -exports.SemVer = SemVer + for (index = 0, quantity = keyNode.length; index < quantity; index += 1) { + if (Array.isArray(keyNode[index])) { + throwError(state, 'nested arrays are not supported inside keys'); + } -function SemVer (version, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false + if (typeof keyNode === 'object' && _class(keyNode[index]) === '[object Object]') { + keyNode[index] = '[object Object]'; + } } } - if (version instanceof SemVer) { - if (version.loose === options.loose) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError('Invalid Version: ' + version) + + // Avoid code execution in load() via toString property + // (still use its own toString for arrays, timestamps, + // and whatever user schema extensions happen to have @@toStringTag) + if (typeof keyNode === 'object' && _class(keyNode) === '[object Object]') { + keyNode = '[object Object]'; } - if (version.length > MAX_LENGTH) { - throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + + keyNode = String(keyNode); + + if (_result === null) { + _result = {}; } - if (!(this instanceof SemVer)) { - return new SemVer(version, options) + if (keyTag === 'tag:yaml.org,2002:merge') { + if (Array.isArray(valueNode)) { + for (index = 0, quantity = valueNode.length; index < quantity; index += 1) { + mergeMappings(state, _result, valueNode[index], overridableKeys); + } + } else { + mergeMappings(state, _result, valueNode, overridableKeys); + } + } else { + if (!state.json && + !_hasOwnProperty.call(overridableKeys, keyNode) && + _hasOwnProperty.call(_result, keyNode)) { + state.line = startLine || state.line; + state.position = startPos || state.position; + throwError(state, 'duplicated mapping key'); + } + _result[keyNode] = valueNode; + delete overridableKeys[keyNode]; } - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose + return _result; +} - var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) +function readLineBreak(state) { + var ch; - if (!m) { - throw new TypeError('Invalid Version: ' + version) + ch = state.input.charCodeAt(state.position); + + if (ch === 0x0A/* LF */) { + state.position++; + } else if (ch === 0x0D/* CR */) { + state.position++; + if (state.input.charCodeAt(state.position) === 0x0A/* LF */) { + state.position++; + } + } else { + throwError(state, 'a line break is expected'); } - this.raw = version + state.line += 1; + state.lineStart = state.position; +} - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] +function skipSeparationSpace(state, allowComments, checkIndent) { + var lineBreaks = 0, + ch = state.input.charCodeAt(state.position); - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } + if (allowComments && ch === 0x23/* # */) { + do { + ch = state.input.charCodeAt(++state.position); + } while (ch !== 0x0A/* LF */ && ch !== 0x0D/* CR */ && ch !== 0); + } - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } + if (is_EOL(ch)) { + readLineBreak(state); - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map(function (id) { - if (/^[0-9]+$/.test(id)) { - var num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } + ch = state.input.charCodeAt(state.position); + lineBreaks++; + state.lineIndent = 0; + + while (ch === 0x20/* Space */) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); } - return id - }) + } else { + break; + } } - this.build = m[5] ? m[5].split('.') : [] - this.format() -} - -SemVer.prototype.format = function () { - this.version = this.major + '.' + this.minor + '.' + this.patch - if (this.prerelease.length) { - this.version += '-' + this.prerelease.join('.') + if (checkIndent !== -1 && lineBreaks !== 0 && state.lineIndent < checkIndent) { + throwWarning(state, 'deficient indentation'); } - return this.version -} -SemVer.prototype.toString = function () { - return this.version + return lineBreaks; } -SemVer.prototype.compare = function (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } +function testDocumentSeparator(state) { + var _position = state.position, + ch; - return this.compareMain(other) || this.comparePre(other) -} + ch = state.input.charCodeAt(_position); -SemVer.prototype.compareMain = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) + // Condition state.position === state.lineStart is tested + // in parent on each call, for efficiency. No needs to test here again. + if ((ch === 0x2D/* - */ || ch === 0x2E/* . */) && + ch === state.input.charCodeAt(_position + 1) && + ch === state.input.charCodeAt(_position + 2)) { + + _position += 3; + + ch = state.input.charCodeAt(_position); + + if (ch === 0 || is_WS_OR_EOL(ch)) { + return true; + } } - return compareIdentifiers(this.major, other.major) || - compareIdentifiers(this.minor, other.minor) || - compareIdentifiers(this.patch, other.patch) + return false; } -SemVer.prototype.comparePre = function (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) +function writeFoldedLines(state, count) { + if (count === 1) { + state.result += ' '; + } else if (count > 1) { + state.result += common.repeat('\n', count - 1); } +} - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 + +function readPlainScalar(state, nodeIndent, withinFlowCollection) { + var preceding, + following, + captureStart, + captureEnd, + hasPendingContent, + _line, + _lineStart, + _lineIndent, + _kind = state.kind, + _result = state.result, + ch; + + ch = state.input.charCodeAt(state.position); + + if (is_WS_OR_EOL(ch) || + is_FLOW_INDICATOR(ch) || + ch === 0x23/* # */ || + ch === 0x26/* & */ || + ch === 0x2A/* * */ || + ch === 0x21/* ! */ || + ch === 0x7C/* | */ || + ch === 0x3E/* > */ || + ch === 0x27/* ' */ || + ch === 0x22/* " */ || + ch === 0x25/* % */ || + ch === 0x40/* @ */ || + ch === 0x60/* ` */) { + return false; } - var i = 0 - do { - var a = this.prerelease[i] - var b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) -} + if (ch === 0x3F/* ? */ || ch === 0x2D/* - */) { + following = state.input.charCodeAt(state.position + 1); -// preminor will bump the version up to the next minor release, and immediately -// down to pre-release. premajor and prepatch work the same way. -SemVer.prototype.inc = function (release, identifier) { - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier) - this.inc('pre', identifier) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier) - } - this.inc('pre', identifier) - break + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + return false; + } + } - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if (this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ + state.kind = 'scalar'; + state.result = ''; + captureStart = captureEnd = state.position; + hasPendingContent = false; + + while (ch !== 0) { + if (ch === 0x3A/* : */) { + following = state.input.charCodeAt(state.position + 1); + + if (is_WS_OR_EOL(following) || + withinFlowCollection && is_FLOW_INDICATOR(following)) { + break; } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ + + } else if (ch === 0x23/* # */) { + preceding = state.input.charCodeAt(state.position - 1); + + if (is_WS_OR_EOL(preceding)) { + break; } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. - case 'pre': - if (this.prerelease.length === 0) { - this.prerelease = [0] + + } else if ((state.position === state.lineStart && testDocumentSeparator(state)) || + withinFlowCollection && is_FLOW_INDICATOR(ch)) { + break; + + } else if (is_EOL(ch)) { + _line = state.line; + _lineStart = state.lineStart; + _lineIndent = state.lineIndent; + skipSeparationSpace(state, false, -1); + + if (state.lineIndent >= nodeIndent) { + hasPendingContent = true; + ch = state.input.charCodeAt(state.position); + continue; } else { - var i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - this.prerelease.push(0) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - if (this.prerelease[0] === identifier) { - if (isNaN(this.prerelease[1])) { - this.prerelease = [identifier, 0] - } - } else { - this.prerelease = [identifier, 0] - } + state.position = captureEnd; + state.line = _line; + state.lineStart = _lineStart; + state.lineIndent = _lineIndent; + break; } - break + } - default: - throw new Error('invalid increment argument: ' + release) - } - this.format() - this.raw = this.version - return this -} + if (hasPendingContent) { + captureSegment(state, captureStart, captureEnd, false); + writeFoldedLines(state, state.line - _line); + captureStart = captureEnd = state.position; + hasPendingContent = false; + } -exports.inc = inc -function inc (version, release, loose, identifier) { - if (typeof (loose) === 'string') { - identifier = loose - loose = undefined + if (!is_WHITE_SPACE(ch)) { + captureEnd = state.position + 1; + } + + ch = state.input.charCodeAt(++state.position); } - try { - return new SemVer(version, loose).inc(release, identifier).version - } catch (er) { - return null + captureSegment(state, captureStart, captureEnd, false); + + if (state.result) { + return true; } + + state.kind = _kind; + state.result = _result; + return false; } -exports.diff = diff -function diff (version1, version2) { - if (eq(version1, version2)) { - return null - } else { - var v1 = parse(version1) - var v2 = parse(version2) - var prefix = '' - if (v1.prerelease.length || v2.prerelease.length) { - prefix = 'pre' - var defaultResult = 'prerelease' - } - for (var key in v1) { - if (key === 'major' || key === 'minor' || key === 'patch') { - if (v1[key] !== v2[key]) { - return prefix + key - } +function readSingleQuotedScalar(state, nodeIndent) { + var ch, + captureStart, captureEnd; + + ch = state.input.charCodeAt(state.position); + + if (ch !== 0x27/* ' */) { + return false; + } + + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; + + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x27/* ' */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); + + if (ch === 0x27/* ' */) { + captureStart = state.position; + state.position++; + captureEnd = state.position; + } else { + return true; } + + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; + + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a single quoted scalar'); + + } else { + state.position++; + captureEnd = state.position; } - return defaultResult // may be undefined } + + throwError(state, 'unexpected end of the stream within a single quoted scalar'); } -exports.compareIdentifiers = compareIdentifiers +function readDoubleQuotedScalar(state, nodeIndent) { + var captureStart, + captureEnd, + hexLength, + hexResult, + tmp, + ch; -var numeric = /^[0-9]+$/ -function compareIdentifiers (a, b) { - var anum = numeric.test(a) - var bnum = numeric.test(b) + ch = state.input.charCodeAt(state.position); - if (anum && bnum) { - a = +a - b = +b + if (ch !== 0x22/* " */) { + return false; } - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} + state.kind = 'scalar'; + state.result = ''; + state.position++; + captureStart = captureEnd = state.position; -exports.rcompareIdentifiers = rcompareIdentifiers -function rcompareIdentifiers (a, b) { - return compareIdentifiers(b, a) -} + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + if (ch === 0x22/* " */) { + captureSegment(state, captureStart, state.position, true); + state.position++; + return true; -exports.major = major -function major (a, loose) { - return new SemVer(a, loose).major -} + } else if (ch === 0x5C/* \ */) { + captureSegment(state, captureStart, state.position, true); + ch = state.input.charCodeAt(++state.position); -exports.minor = minor -function minor (a, loose) { - return new SemVer(a, loose).minor -} + if (is_EOL(ch)) { + skipSeparationSpace(state, false, nodeIndent); -exports.patch = patch -function patch (a, loose) { - return new SemVer(a, loose).patch -} + // TODO: rework to inline fn with no type cast? + } else if (ch < 256 && simpleEscapeCheck[ch]) { + state.result += simpleEscapeMap[ch]; + state.position++; -exports.compare = compare -function compare (a, b, loose) { - return new SemVer(a, loose).compare(new SemVer(b, loose)) -} + } else if ((tmp = escapedHexLen(ch)) > 0) { + hexLength = tmp; + hexResult = 0; -exports.compareLoose = compareLoose -function compareLoose (a, b) { - return compare(a, b, true) -} + for (; hexLength > 0; hexLength--) { + ch = state.input.charCodeAt(++state.position); -exports.rcompare = rcompare -function rcompare (a, b, loose) { - return compare(b, a, loose) -} + if ((tmp = fromHexCode(ch)) >= 0) { + hexResult = (hexResult << 4) + tmp; -exports.sort = sort -function sort (list, loose) { - return list.sort(function (a, b) { - return exports.compare(a, b, loose) - }) -} + } else { + throwError(state, 'expected hexadecimal character'); + } + } -exports.rsort = rsort -function rsort (list, loose) { - return list.sort(function (a, b) { - return exports.rcompare(a, b, loose) - }) -} + state.result += charFromCodepoint(hexResult); -exports.gt = gt -function gt (a, b, loose) { - return compare(a, b, loose) > 0 -} + state.position++; -exports.lt = lt -function lt (a, b, loose) { - return compare(a, b, loose) < 0 -} + } else { + throwError(state, 'unknown escape sequence'); + } -exports.eq = eq -function eq (a, b, loose) { - return compare(a, b, loose) === 0 -} + captureStart = captureEnd = state.position; -exports.neq = neq -function neq (a, b, loose) { - return compare(a, b, loose) !== 0 -} + } else if (is_EOL(ch)) { + captureSegment(state, captureStart, captureEnd, true); + writeFoldedLines(state, skipSeparationSpace(state, false, nodeIndent)); + captureStart = captureEnd = state.position; -exports.gte = gte -function gte (a, b, loose) { - return compare(a, b, loose) >= 0 -} + } else if (state.position === state.lineStart && testDocumentSeparator(state)) { + throwError(state, 'unexpected end of the document within a double quoted scalar'); -exports.lte = lte -function lte (a, b, loose) { - return compare(a, b, loose) <= 0 + } else { + state.position++; + captureEnd = state.position; + } + } + + throwError(state, 'unexpected end of the stream within a double quoted scalar'); } -exports.cmp = cmp -function cmp (a, op, b, loose) { - switch (op) { - case '===': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a === b +function readFlowCollection(state, nodeIndent) { + var readNext = true, + _line, + _tag = state.tag, + _result, + _anchor = state.anchor, + following, + terminator, + isPair, + isExplicitPair, + isMapping, + overridableKeys = {}, + keyNode, + keyTag, + valueNode, + ch; - case '!==': - if (typeof a === 'object') - a = a.version - if (typeof b === 'object') - b = b.version - return a !== b + ch = state.input.charCodeAt(state.position); - case '': - case '=': - case '==': - return eq(a, b, loose) + if (ch === 0x5B/* [ */) { + terminator = 0x5D;/* ] */ + isMapping = false; + _result = []; + } else if (ch === 0x7B/* { */) { + terminator = 0x7D;/* } */ + isMapping = true; + _result = {}; + } else { + return false; + } - case '!=': - return neq(a, b, loose) + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } - case '>': - return gt(a, b, loose) + ch = state.input.charCodeAt(++state.position); - case '>=': - return gte(a, b, loose) + while (ch !== 0) { + skipSeparationSpace(state, true, nodeIndent); - case '<': - return lt(a, b, loose) + ch = state.input.charCodeAt(state.position); - case '<=': - return lte(a, b, loose) + if (ch === terminator) { + state.position++; + state.tag = _tag; + state.anchor = _anchor; + state.kind = isMapping ? 'mapping' : 'sequence'; + state.result = _result; + return true; + } else if (!readNext) { + throwError(state, 'missed comma between flow collection entries'); + } - default: - throw new TypeError('Invalid operator: ' + op) - } -} + keyTag = keyNode = valueNode = null; + isPair = isExplicitPair = false; -exports.Comparator = Comparator -function Comparator (comp, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false - } - } + if (ch === 0x3F/* ? */) { + following = state.input.charCodeAt(state.position + 1); - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value + if (is_WS_OR_EOL(following)) { + isPair = isExplicitPair = true; + state.position++; + skipSeparationSpace(state, true, nodeIndent); + } } - } - if (!(this instanceof Comparator)) { - return new Comparator(comp, options) - } + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + keyTag = state.tag; + keyNode = state.result; + skipSeparationSpace(state, true, nodeIndent); - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) + ch = state.input.charCodeAt(state.position); - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } + if ((isExplicitPair || state.line === _line) && ch === 0x3A/* : */) { + isPair = true; + ch = state.input.charCodeAt(++state.position); + skipSeparationSpace(state, true, nodeIndent); + composeNode(state, nodeIndent, CONTEXT_FLOW_IN, false, true); + valueNode = state.result; + } - debug('comp', this) -} + if (isMapping) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode); + } else if (isPair) { + _result.push(storeMappingPair(state, null, overridableKeys, keyTag, keyNode, valueNode)); + } else { + _result.push(keyNode); + } -var ANY = {} -Comparator.prototype.parse = function (comp) { - var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var m = comp.match(r) + skipSeparationSpace(state, true, nodeIndent); - if (!m) { - throw new TypeError('Invalid comparator: ' + comp) - } + ch = state.input.charCodeAt(state.position); - this.operator = m[1] - if (this.operator === '=') { - this.operator = '' + if (ch === 0x2C/* , */) { + readNext = true; + ch = state.input.charCodeAt(++state.position); + } else { + readNext = false; + } } - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } + throwError(state, 'unexpected end of the stream within a flow collection'); } -Comparator.prototype.toString = function () { - return this.value -} +function readBlockScalar(state, nodeIndent) { + var captureStart, + folding, + chomping = CHOMPING_CLIP, + didReadContent = false, + detectedIndent = false, + textIndent = nodeIndent, + emptyLines = 0, + atMoreIndented = false, + tmp, + ch; -Comparator.prototype.test = function (version) { - debug('Comparator.test', version, this.options.loose) + ch = state.input.charCodeAt(state.position); - if (this.semver === ANY) { - return true + if (ch === 0x7C/* | */) { + folding = false; + } else if (ch === 0x3E/* > */) { + folding = true; + } else { + return false; } - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } + state.kind = 'scalar'; + state.result = ''; - return cmp(version, this.operator, this.semver, this.options) -} + while (ch !== 0) { + ch = state.input.charCodeAt(++state.position); -Comparator.prototype.intersects = function (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } + if (ch === 0x2B/* + */ || ch === 0x2D/* - */) { + if (CHOMPING_CLIP === chomping) { + chomping = (ch === 0x2B/* + */) ? CHOMPING_KEEP : CHOMPING_STRIP; + } else { + throwError(state, 'repeat of a chomping mode identifier'); + } + + } else if ((tmp = fromDecimalCode(ch)) >= 0) { + if (tmp === 0) { + throwError(state, 'bad explicit indentation width of a block scalar; it cannot be less than one'); + } else if (!detectedIndent) { + textIndent = nodeIndent + tmp - 1; + detectedIndent = true; + } else { + throwError(state, 'repeat of an indentation width identifier'); + } - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false + } else { + break; } } - var rangeTmp + if (is_WHITE_SPACE(ch)) { + do { ch = state.input.charCodeAt(++state.position); } + while (is_WHITE_SPACE(ch)); - if (this.operator === '') { - rangeTmp = new Range(comp.value, options) - return satisfies(this.value, rangeTmp, options) - } else if (comp.operator === '') { - rangeTmp = new Range(this.value, options) - return satisfies(comp.semver, rangeTmp, options) + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (!is_EOL(ch) && (ch !== 0)); + } } - var sameDirectionIncreasing = - (this.operator === '>=' || this.operator === '>') && - (comp.operator === '>=' || comp.operator === '>') - var sameDirectionDecreasing = - (this.operator === '<=' || this.operator === '<') && - (comp.operator === '<=' || comp.operator === '<') - var sameSemVer = this.semver.version === comp.semver.version - var differentDirectionsInclusive = - (this.operator === '>=' || this.operator === '<=') && - (comp.operator === '>=' || comp.operator === '<=') - var oppositeDirectionsLessThan = - cmp(this.semver, '<', comp.semver, options) && - ((this.operator === '>=' || this.operator === '>') && - (comp.operator === '<=' || comp.operator === '<')) - var oppositeDirectionsGreaterThan = - cmp(this.semver, '>', comp.semver, options) && - ((this.operator === '<=' || this.operator === '<') && - (comp.operator === '>=' || comp.operator === '>')) + while (ch !== 0) { + readLineBreak(state); + state.lineIndent = 0; - return sameDirectionIncreasing || sameDirectionDecreasing || - (sameSemVer && differentDirectionsInclusive) || - oppositeDirectionsLessThan || oppositeDirectionsGreaterThan -} + ch = state.input.charCodeAt(state.position); -exports.Range = Range -function Range (range, options) { - if (!options || typeof options !== 'object') { - options = { - loose: !!options, - includePrerelease: false + while ((!detectedIndent || state.lineIndent < textIndent) && + (ch === 0x20/* Space */)) { + state.lineIndent++; + ch = state.input.charCodeAt(++state.position); } - } - if (range instanceof Range) { - if (range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease) { - return range - } else { - return new Range(range.raw, options) + if (!detectedIndent && state.lineIndent > textIndent) { + textIndent = state.lineIndent; } - } - - if (range instanceof Comparator) { - return new Range(range.value, options) - } - if (!(this instanceof Range)) { - return new Range(range, options) - } + if (is_EOL(ch)) { + emptyLines++; + continue; + } - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease + // End of the scalar. + if (state.lineIndent < textIndent) { - // First, split based on boolean or || - this.raw = range - this.set = range.split(/\s*\|\|\s*/).map(function (range) { - return this.parseRange(range.trim()) - }, this).filter(function (c) { - // throw out any that are not relevant for whatever reason - return c.length - }) + // Perform the chomping. + if (chomping === CHOMPING_KEEP) { + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } else if (chomping === CHOMPING_CLIP) { + if (didReadContent) { // i.e. only if the scalar is not empty. + state.result += '\n'; + } + } - if (!this.set.length) { - throw new TypeError('Invalid SemVer Range: ' + range) - } + // Break this `while` cycle and go to the funciton's epilogue. + break; + } - this.format() -} + // Folded style: use fancy rules to handle line breaks. + if (folding) { -Range.prototype.format = function () { - this.range = this.set.map(function (comps) { - return comps.join(' ').trim() - }).join('||').trim() - return this.range -} + // Lines starting with white space characters (more-indented lines) are not folded. + if (is_WHITE_SPACE(ch)) { + atMoreIndented = true; + // except for the first content line (cf. Example 8.1) + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); -Range.prototype.toString = function () { - return this.range -} + // End of more-indented block. + } else if (atMoreIndented) { + atMoreIndented = false; + state.result += common.repeat('\n', emptyLines + 1); -Range.prototype.parseRange = function (range) { - var loose = this.options.loose - range = range.trim() - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] - range = range.replace(hr, hyphenReplace) - debug('hyphen replace', range) - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range, re[COMPARATORTRIM]) + // Just one line break - perceive as the same line. + } else if (emptyLines === 0) { + if (didReadContent) { // i.e. only if we have already read some scalar content. + state.result += ' '; + } - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[TILDETRIM], tildeTrimReplace) + // Several line breaks - perceive as different lines. + } else { + state.result += common.repeat('\n', emptyLines); + } - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[CARETTRIM], caretTrimReplace) + // Literal style: just add exact number of line breaks between content lines. + } else { + // Keep all line breaks except the header line break. + state.result += common.repeat('\n', didReadContent ? 1 + emptyLines : emptyLines); + } - // normalize spaces - range = range.split(/\s+/).join(' ') + didReadContent = true; + detectedIndent = true; + emptyLines = 0; + captureStart = state.position; - // At this point, the range is completely trimmed and - // ready to be split into comparators. + while (!is_EOL(ch) && (ch !== 0)) { + ch = state.input.charCodeAt(++state.position); + } - var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] - var set = range.split(' ').map(function (comp) { - return parseComparator(comp, this.options) - }, this).join(' ').split(/\s+/) - if (this.options.loose) { - // in loose mode, throw out any that are not valid comparators - set = set.filter(function (comp) { - return !!comp.match(compRe) - }) + captureSegment(state, captureStart, state.position, false); } - set = set.map(function (comp) { - return new Comparator(comp, this.options) - }, this) - return set + return true; } -Range.prototype.intersects = function (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') +function readBlockSequence(state, nodeIndent) { + var _line, + _tag = state.tag, + _anchor = state.anchor, + _result = [], + following, + detected = false, + ch; + + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; } - return this.set.some(function (thisComparators) { - return thisComparators.every(function (thisComparator) { - return range.set.some(function (rangeComparators) { - return rangeComparators.every(function (rangeComparator) { - return thisComparator.intersects(rangeComparator, options) - }) - }) - }) - }) -} + ch = state.input.charCodeAt(state.position); -// Mostly just for testing and legacy API reasons -exports.toComparators = toComparators -function toComparators (range, options) { - return new Range(range, options).set.map(function (comp) { - return comp.map(function (c) { - return c.value - }).join(' ').trim().split(' ') - }) -} + while (ch !== 0) { -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -function parseComparator (comp, options) { - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} + if (ch !== 0x2D/* - */) { + break; + } -function isX (id) { - return !id || id.toLowerCase() === 'x' || id === '*' -} + following = state.input.charCodeAt(state.position + 1); -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 -function replaceTildes (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceTilde(comp, options) - }).join(' ') -} + if (!is_WS_OR_EOL(following)) { + break; + } -function replaceTilde (comp, options) { - var r = options.loose ? re[TILDELOOSE] : re[TILDE] - return comp.replace(r, function (_, M, m, p, pr) { - debug('tilde', comp, _, M, m, p, pr) - var ret + detected = true; + state.position++; - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0 - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else if (pr) { - debug('replaceTilde pr', pr) - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } else { - // ~1.2.3 == >=1.2.3 <1.3.0 - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' + if (skipSeparationSpace(state, true, -1)) { + if (state.lineIndent <= nodeIndent) { + _result.push(null); + ch = state.input.charCodeAt(state.position); + continue; + } } - debug('tilde return', ret) - return ret - }) -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 -// ^1.2.3 --> >=1.2.3 <2.0.0 -// ^1.2.0 --> >=1.2.0 <2.0.0 -function replaceCarets (comp, options) { - return comp.trim().split(/\s+/).map(function (comp) { - return replaceCaret(comp, options) - }).join(' ') -} + _line = state.line; + composeNode(state, nodeIndent, CONTEXT_BLOCK_IN, false, true); + _result.push(state.result); + skipSeparationSpace(state, true, -1); -function replaceCaret (comp, options) { - debug('caret', comp, options) - var r = options.loose ? re[CARETLOOSE] : re[CARET] - return comp.replace(r, function (_, M, m, p, pr) { - debug('caret', comp, _, M, m, p, pr) - var ret + ch = state.input.charCodeAt(state.position); - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (isX(p)) { - if (M === '0') { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } else { - ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + '-' + pr + - ' <' + (+M + 1) + '.0.0' - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + m + '.' + (+p + 1) - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + M + '.' + (+m + 1) + '.0' - } - } else { - ret = '>=' + M + '.' + m + '.' + p + - ' <' + (+M + 1) + '.0.0' - } + if ((state.line === _line || state.lineIndent > nodeIndent) && (ch !== 0)) { + throwError(state, 'bad indentation of a sequence entry'); + } else if (state.lineIndent < nodeIndent) { + break; } + } - debug('caret return', ret) - return ret - }) + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'sequence'; + state.result = _result; + return true; + } + return false; } -function replaceXRanges (comp, options) { - debug('replaceXRanges', comp, options) - return comp.split(/\s+/).map(function (comp) { - return replaceXRange(comp, options) - }).join(' ') -} +function readBlockMapping(state, nodeIndent, flowIndent) { + var following, + allowCompact, + _line, + _pos, + _tag = state.tag, + _anchor = state.anchor, + _result = {}, + overridableKeys = {}, + keyTag = null, + keyNode = null, + valueNode = null, + atExplicitKey = false, + detected = false, + ch; -function replaceXRange (comp, options) { - comp = comp.trim() - var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] - return comp.replace(r, function (ret, gtlt, M, m, p, pr) { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - var xM = isX(M) - var xm = xM || isX(m) - var xp = xm || isX(p) - var anyX = xp + if (state.anchor !== null) { + state.anchorMap[state.anchor] = _result; + } - if (gtlt === '=' && anyX) { - gtlt = '' - } + ch = state.input.charCodeAt(state.position); - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 + while (ch !== 0) { + following = state.input.charCodeAt(state.position + 1); + _line = state.line; // Save the current line. + _pos = state.position; - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - // >1.2.3 => >= 1.2.4 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 + // + // Explicit notation case. There are two separate blocks: + // first for the key (denoted by "?") and second for the value (denoted by ":") + // + if ((ch === 0x3F/* ? */ || ch === 0x3A/* : */) && is_WS_OR_EOL(following)) { + + if (ch === 0x3F/* ? */) { + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; } + + detected = true; + atExplicitKey = true; + allowCompact = true; + + } else if (atExplicitKey) { + // i.e. 0x3A/* : */ === character after the explicit key. + atExplicitKey = false; + allowCompact = true; + + } else { + throwError(state, 'incomplete explicit mapping pair; a key node is missed; or followed by a non-tabulated empty line'); } - ret = gtlt + M + '.' + m + '.' + p - } else if (xm) { - ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' - } else if (xp) { - ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' - } + state.position += 1; + ch = following; - debug('xRange return', ret) + // + // Implicit notation case. Flow-style node as the key first, then ":", and the value. + // + } else if (composeNode(state, flowIndent, CONTEXT_FLOW_OUT, false, true)) { - return ret - }) -} + if (state.line === _line) { + ch = state.input.charCodeAt(state.position); -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -function replaceStars (comp, options) { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp.trim().replace(re[STAR], '') -} + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } -// This function is passed to string.replace(re[HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0 -function hyphenReplace ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr, tb) { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = '>=' + fM + '.0.0' - } else if (isX(fp)) { - from = '>=' + fM + '.' + fm + '.0' - } else { - from = '>=' + from - } + if (ch === 0x3A/* : */) { + ch = state.input.charCodeAt(++state.position); + + if (!is_WS_OR_EOL(ch)) { + throwError(state, 'a whitespace character is expected after the key-value separator within a block mapping'); + } - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = '<' + (+tM + 1) + '.0.0' - } else if (isX(tp)) { - to = '<' + tM + '.' + (+tm + 1) + '.0' - } else if (tpr) { - to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr - } else { - to = '<=' + to - } + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); + keyTag = keyNode = valueNode = null; + } - return (from + ' ' + to).trim() -} + detected = true; + atExplicitKey = false; + allowCompact = false; + keyTag = state.tag; + keyNode = state.result; -// if ANY of the sets match ALL of its comparators, then pass -Range.prototype.test = function (version) { - if (!version) { - return false - } + } else if (detected) { + throwError(state, 'can not read an implicit mapping pair; a colon is missed'); - if (typeof version === 'string') { - version = new SemVer(version, this.options) - } + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } - for (var i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false -} + } else if (detected) { + throwError(state, 'can not read a block mapping entry; a multiline key may not be an implicit key'); -function testSet (set, version, options) { - for (var i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false + } else { + state.tag = _tag; + state.anchor = _anchor; + return true; // Keep the result of `composeNode`. + } + + } else { + break; // Reading is done. Go to the epilogue. } - } - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === ANY) { - continue + // + // Common reading code for both explicit and implicit notations. + // + if (state.line === _line || state.lineIndent > nodeIndent) { + if (composeNode(state, nodeIndent, CONTEXT_BLOCK_OUT, true, allowCompact)) { + if (atExplicitKey) { + keyNode = state.result; + } else { + valueNode = state.result; + } } - if (set[i].semver.prerelease.length > 0) { - var allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } + if (!atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, valueNode, _line, _pos); + keyTag = keyNode = valueNode = null; } + + skipSeparationSpace(state, true, -1); + ch = state.input.charCodeAt(state.position); } - // Version has a -pre, but it's not one of the ones we like. - return false + if (state.lineIndent > nodeIndent && (ch !== 0)) { + throwError(state, 'bad indentation of a mapping entry'); + } else if (state.lineIndent < nodeIndent) { + break; + } } - return true -} + // + // Epilogue. + // -exports.satisfies = satisfies -function satisfies (version, range, options) { - try { - range = new Range(range, options) - } catch (er) { - return false + // Special case: last mapping's node contains only the key in explicit notation. + if (atExplicitKey) { + storeMappingPair(state, _result, overridableKeys, keyTag, keyNode, null); } - return range.test(version) -} -exports.maxSatisfying = maxSatisfying -function maxSatisfying (versions, range, options) { - var max = null - var maxSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null + // Expose the resulting mapping. + if (detected) { + state.tag = _tag; + state.anchor = _anchor; + state.kind = 'mapping'; + state.result = _result; } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max -} -exports.minSatisfying = minSatisfying -function minSatisfying (versions, range, options) { - var min = null - var minSV = null - try { - var rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach(function (v) { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) - } - } - }) - return min + return detected; } -exports.minVersion = minVersion -function minVersion (range, loose) { - range = new Range(range, loose) +function readTagProperty(state) { + var _position, + isVerbatim = false, + isNamed = false, + tagHandle, + tagName, + ch; - var minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } + ch = state.input.charCodeAt(state.position); - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver + if (ch !== 0x21/* ! */) return false; + + if (state.tag !== null) { + throwError(state, 'duplication of a tag property'); } - minver = null - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] + ch = state.input.charCodeAt(++state.position); - comparators.forEach(function (comparator) { - // Clone to avoid manipulating the comparator's semver object. - var compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!minver || gt(minver, compver)) { - minver = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error('Unexpected operation: ' + comparator.operator) - } - }) - } + if (ch === 0x3C/* < */) { + isVerbatim = true; + ch = state.input.charCodeAt(++state.position); - if (minver && range.test(minver)) { - return minver + } else if (ch === 0x21/* ! */) { + isNamed = true; + tagHandle = '!!'; + ch = state.input.charCodeAt(++state.position); + + } else { + tagHandle = '!'; } - return null -} + _position = state.position; -exports.validRange = validRange -function validRange (range, options) { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } -} + if (isVerbatim) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && ch !== 0x3E/* > */); -// Determine if version is less than all the versions possible in the range -exports.ltr = ltr -function ltr (version, range, options) { - return outside(version, range, '<', options) -} + if (state.position < state.length) { + tagName = state.input.slice(_position, state.position); + ch = state.input.charCodeAt(++state.position); + } else { + throwError(state, 'unexpected end of the stream within a verbatim tag'); + } + } else { + while (ch !== 0 && !is_WS_OR_EOL(ch)) { -// Determine if version is greater than all the versions possible in the range. -exports.gtr = gtr -function gtr (version, range, options) { - return outside(version, range, '>', options) -} + if (ch === 0x21/* ! */) { + if (!isNamed) { + tagHandle = state.input.slice(_position - 1, state.position + 1); -exports.outside = outside -function outside (version, range, hilo, options) { - version = new SemVer(version, options) - range = new Range(range, options) + if (!PATTERN_TAG_HANDLE.test(tagHandle)) { + throwError(state, 'named tag handle cannot contain such characters'); + } - var gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } + isNamed = true; + _position = state.position + 1; + } else { + throwError(state, 'tag suffix cannot contain exclamation marks'); + } + } - // If it satisifes the range it is not outside - if (satisfies(version, range, options)) { - return false + ch = state.input.charCodeAt(++state.position); + } + + tagName = state.input.slice(_position, state.position); + + if (PATTERN_FLOW_INDICATORS.test(tagName)) { + throwError(state, 'tag suffix cannot contain flow indicator characters'); + } } - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. + if (tagName && !PATTERN_TAG_URI.test(tagName)) { + throwError(state, 'tag name cannot contain such characters: ' + tagName); + } - for (var i = 0; i < range.set.length; ++i) { - var comparators = range.set[i] + if (isVerbatim) { + state.tag = tagName; - var high = null - var low = null + } else if (_hasOwnProperty.call(state.tagMap, tagHandle)) { + state.tag = state.tagMap[tagHandle] + tagName; - comparators.forEach(function (comparator) { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) + } else if (tagHandle === '!') { + state.tag = '!' + tagName; - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } + } else if (tagHandle === '!!') { + state.tag = 'tag:yaml.org,2002:' + tagName; - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } + } else { + throwError(state, 'undeclared tag handle "' + tagHandle + '"'); } - return true -} -exports.prerelease = prerelease -function prerelease (version, options) { - var parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null + return true; } -exports.intersects = intersects -function intersects (r1, r2, options) { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2) -} +function readAnchorProperty(state) { + var _position, + ch; -exports.coerce = coerce -function coerce (version) { - if (version instanceof SemVer) { - return version - } + ch = state.input.charCodeAt(state.position); - if (typeof version !== 'string') { - return null + if (ch !== 0x26/* & */) return false; + + if (state.anchor !== null) { + throwError(state, 'duplication of an anchor property'); } - var match = version.match(re[COERCE]) + ch = state.input.charCodeAt(++state.position); + _position = state.position; - if (match == null) { - return null + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); } - return parse(match[1] + - '.' + (match[2] || '0') + - '.' + (match[3] || '0')) + if (state.position === _position) { + throwError(state, 'name of an anchor node must contain at least one character'); + } + + state.anchor = state.input.slice(_position, state.position); + return true; } +function readAlias(state) { + var _position, alias, + ch; -/***/ }), + ch = state.input.charCodeAt(state.position); -/***/ 82022: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (ch !== 0x2A/* * */) return false; -var timespan = __nccwpck_require__(46098); -var PS_SUPPORTED = __nccwpck_require__(59085); -var jws = __nccwpck_require__(4636); -var includes = __nccwpck_require__(17931); -var isBoolean = __nccwpck_require__(16501); -var isInteger = __nccwpck_require__(21441); -var isNumber = __nccwpck_require__(40298); -var isPlainObject = __nccwpck_require__(25723); -var isString = __nccwpck_require__(25180); -var once = __nccwpck_require__(94499); + ch = state.input.charCodeAt(++state.position); + _position = state.position; -var SUPPORTED_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'none'] -if (PS_SUPPORTED) { - SUPPORTED_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); -} + while (ch !== 0 && !is_WS_OR_EOL(ch) && !is_FLOW_INDICATOR(ch)) { + ch = state.input.charCodeAt(++state.position); + } -var sign_options_schema = { - expiresIn: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"expiresIn" should be a number of seconds or string representing a timespan' }, - notBefore: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"notBefore" should be a number of seconds or string representing a timespan' }, - audience: { isValid: function(value) { return isString(value) || Array.isArray(value); }, message: '"audience" must be a string or array' }, - algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' }, - header: { isValid: isPlainObject, message: '"header" must be an object' }, - encoding: { isValid: isString, message: '"encoding" must be a string' }, - issuer: { isValid: isString, message: '"issuer" must be a string' }, - subject: { isValid: isString, message: '"subject" must be a string' }, - jwtid: { isValid: isString, message: '"jwtid" must be a string' }, - noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' }, - keyid: { isValid: isString, message: '"keyid" must be a string' }, - mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' } -}; + if (state.position === _position) { + throwError(state, 'name of an alias node must contain at least one character'); + } -var registered_claims_schema = { - iat: { isValid: isNumber, message: '"iat" should be a number of seconds' }, - exp: { isValid: isNumber, message: '"exp" should be a number of seconds' }, - nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' } -}; + alias = state.input.slice(_position, state.position); -function validate(schema, allowUnknown, object, parameterName) { - if (!isPlainObject(object)) { - throw new Error('Expected "' + parameterName + '" to be a plain object.'); + if (!_hasOwnProperty.call(state.anchorMap, alias)) { + throwError(state, 'unidentified alias "' + alias + '"'); } - Object.keys(object) - .forEach(function(key) { - var validator = schema[key]; - if (!validator) { - if (!allowUnknown) { - throw new Error('"' + key + '" is not allowed in "' + parameterName + '"'); - } - return; - } - if (!validator.isValid(object[key])) { - throw new Error(validator.message); - } - }); -} -function validateOptions(options) { - return validate(sign_options_schema, false, options, 'options'); + state.result = state.anchorMap[alias]; + skipSeparationSpace(state, true, -1); + return true; } -function validatePayload(payload) { - return validate(registered_claims_schema, true, payload, 'payload'); -} +function composeNode(state, parentIndent, nodeContext, allowToSeek, allowCompact) { + var allowBlockStyles, + allowBlockScalars, + allowBlockCollections, + indentStatus = 1, // 1: this>parent, 0: this=parent, -1: this parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } + } - var header = Object.assign({ - alg: options.algorithm || 'HS256', - typ: isObjectPayload ? 'JWT' : undefined, - kid: options.keyid - }, options.header); + if (indentStatus === 1) { + while (readTagProperty(state) || readAnchorProperty(state)) { + if (skipSeparationSpace(state, true, -1)) { + atNewLine = true; + allowBlockCollections = allowBlockStyles; - function failure(err) { - if (callback) { - return callback(err); + if (state.lineIndent > parentIndent) { + indentStatus = 1; + } else if (state.lineIndent === parentIndent) { + indentStatus = 0; + } else if (state.lineIndent < parentIndent) { + indentStatus = -1; + } + } else { + allowBlockCollections = false; + } } - throw err; } - if (!secretOrPrivateKey && options.algorithm !== 'none') { - return failure(new Error('secretOrPrivateKey must have a value')); + if (allowBlockCollections) { + allowBlockCollections = atNewLine || allowCompact; } - if (typeof payload === 'undefined') { - return failure(new Error('payload is required')); - } else if (isObjectPayload) { - try { - validatePayload(payload); - } - catch (error) { - return failure(error); - } - if (!options.mutatePayload) { - payload = Object.assign({},payload); + if (indentStatus === 1 || CONTEXT_BLOCK_OUT === nodeContext) { + if (CONTEXT_FLOW_IN === nodeContext || CONTEXT_FLOW_OUT === nodeContext) { + flowIndent = parentIndent; + } else { + flowIndent = parentIndent + 1; } - } else { - var invalid_options = options_for_objects.filter(function (opt) { - return typeof options[opt] !== 'undefined'; - }); - if (invalid_options.length > 0) { - return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload')); - } - } + blockIndent = state.position - state.lineStart; - if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') { - return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.')); - } + if (indentStatus === 1) { + if (allowBlockCollections && + (readBlockSequence(state, blockIndent) || + readBlockMapping(state, blockIndent, flowIndent)) || + readFlowCollection(state, flowIndent)) { + hasContent = true; + } else { + if ((allowBlockScalars && readBlockScalar(state, flowIndent)) || + readSingleQuotedScalar(state, flowIndent) || + readDoubleQuotedScalar(state, flowIndent)) { + hasContent = true; - if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') { - return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.')); - } + } else if (readAlias(state)) { + hasContent = true; - try { - validateOptions(options); - } - catch (error) { - return failure(error); - } + if (state.tag !== null || state.anchor !== null) { + throwError(state, 'alias node should not have any properties'); + } - var timestamp = payload.iat || Math.floor(Date.now() / 1000); + } else if (readPlainScalar(state, flowIndent, CONTEXT_FLOW_IN === nodeContext)) { + hasContent = true; - if (options.noTimestamp) { - delete payload.iat; - } else if (isObjectPayload) { - payload.iat = timestamp; - } + if (state.tag === null) { + state.tag = '?'; + } + } - if (typeof options.notBefore !== 'undefined') { - try { - payload.nbf = timespan(options.notBefore, timestamp); - } - catch (err) { - return failure(err); - } - if (typeof payload.nbf === 'undefined') { - return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else if (indentStatus === 0) { + // Special case: block sequences are allowed to have same indentation level as the parent. + // http://www.yaml.org/spec/1.2/spec.html#id2799784 + hasContent = allowBlockCollections && readBlockSequence(state, blockIndent); } } - if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') { - try { - payload.exp = timespan(options.expiresIn, timestamp); - } - catch (err) { - return failure(err); - } - if (typeof payload.exp === 'undefined') { - return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); - } - } + if (state.tag !== null && state.tag !== '!') { + if (state.tag === '?') { + // Implicit resolving is not allowed for non-scalar types, and '?' + // non-specific tag is only automatically assigned to plain scalars. + // + // We only need to check kind conformity in case user explicitly assigns '?' + // tag, for example like this: "! [0]" + // + if (state.result !== null && state.kind !== 'scalar') { + throwError(state, 'unacceptable node kind for ! tag; it should be "scalar", not "' + state.kind + '"'); + } - Object.keys(options_to_payload).forEach(function (key) { - var claim = options_to_payload[key]; - if (typeof options[key] !== 'undefined') { - if (typeof payload[claim] !== 'undefined') { - return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.')); + for (typeIndex = 0, typeQuantity = state.implicitTypes.length; typeIndex < typeQuantity; typeIndex += 1) { + type = state.implicitTypes[typeIndex]; + + if (type.resolve(state.result)) { // `state.result` updated in resolver if matched + state.result = type.construct(state.result); + state.tag = type.tag; + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + break; + } } - payload[claim] = options[key]; - } - }); + } else if (_hasOwnProperty.call(state.typeMap[state.kind || 'fallback'], state.tag)) { + type = state.typeMap[state.kind || 'fallback'][state.tag]; - var encoding = options.encoding || 'utf8'; + if (state.result !== null && type.kind !== state.kind) { + throwError(state, 'unacceptable node kind for !<' + state.tag + '> tag; it should be "' + type.kind + '", not "' + state.kind + '"'); + } - if (typeof callback === 'function') { - callback = callback && once(callback); + if (!type.resolve(state.result)) { // `state.result` updated in resolver if matched + throwError(state, 'cannot resolve a node with !<' + state.tag + '> explicit tag'); + } else { + state.result = type.construct(state.result); + if (state.anchor !== null) { + state.anchorMap[state.anchor] = state.result; + } + } + } else { + throwError(state, 'unknown tag !<' + state.tag + '>'); + } + } - jws.createSign({ - header: header, - privateKey: secretOrPrivateKey, - payload: payload, - encoding: encoding - }).once('error', callback) - .once('done', function (signature) { - callback(null, signature); - }); - } else { - return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding}); + if (state.listener !== null) { + state.listener('close', state); } -}; + return state.tag !== null || state.anchor !== null || hasContent; +} +function readDocument(state) { + var documentStart = state.position, + _position, + directiveName, + directiveArgs, + hasDirectives = false, + ch; -/***/ }), + state.version = null; + state.checkLineBreaks = state.legacy; + state.tagMap = {}; + state.anchorMap = {}; -/***/ 12327: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + while ((ch = state.input.charCodeAt(state.position)) !== 0) { + skipSeparationSpace(state, true, -1); -var JsonWebTokenError = __nccwpck_require__(405); -var NotBeforeError = __nccwpck_require__(4383); -var TokenExpiredError = __nccwpck_require__(46637); -var decode = __nccwpck_require__(53359); -var timespan = __nccwpck_require__(46098); -var PS_SUPPORTED = __nccwpck_require__(59085); -var jws = __nccwpck_require__(4636); + ch = state.input.charCodeAt(state.position); -var PUB_KEY_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512']; -var RSA_KEY_ALGS = ['RS256', 'RS384', 'RS512']; -var HS_ALGS = ['HS256', 'HS384', 'HS512']; + if (state.lineIndent > 0 || ch !== 0x25/* % */) { + break; + } -if (PS_SUPPORTED) { - PUB_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); - RSA_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); -} + hasDirectives = true; + ch = state.input.charCodeAt(++state.position); + _position = state.position; -module.exports = function (jwtString, secretOrPublicKey, options, callback) { - if ((typeof options === 'function') && !callback) { - callback = options; - options = {}; - } + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } - if (!options) { - options = {}; - } + directiveName = state.input.slice(_position, state.position); + directiveArgs = []; - //clone this object since we are going to mutate it. - options = Object.assign({}, options); + if (directiveName.length < 1) { + throwError(state, 'directive name must not be less than one character in length'); + } - var done; + while (ch !== 0) { + while (is_WHITE_SPACE(ch)) { + ch = state.input.charCodeAt(++state.position); + } - if (callback) { - done = callback; - } else { - done = function(err, data) { - if (err) throw err; - return data; - }; - } + if (ch === 0x23/* # */) { + do { ch = state.input.charCodeAt(++state.position); } + while (ch !== 0 && !is_EOL(ch)); + break; + } - if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') { - return done(new JsonWebTokenError('clockTimestamp must be a number')); - } + if (is_EOL(ch)) break; - if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) { - return done(new JsonWebTokenError('nonce must be a non-empty string')); - } + _position = state.position; - var clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000); + while (ch !== 0 && !is_WS_OR_EOL(ch)) { + ch = state.input.charCodeAt(++state.position); + } - if (!jwtString){ - return done(new JsonWebTokenError('jwt must be provided')); - } + directiveArgs.push(state.input.slice(_position, state.position)); + } - if (typeof jwtString !== 'string') { - return done(new JsonWebTokenError('jwt must be a string')); + if (ch !== 0) readLineBreak(state); + + if (_hasOwnProperty.call(directiveHandlers, directiveName)) { + directiveHandlers[directiveName](state, directiveName, directiveArgs); + } else { + throwWarning(state, 'unknown document directive "' + directiveName + '"'); + } } - var parts = jwtString.split('.'); + skipSeparationSpace(state, true, -1); - if (parts.length !== 3){ - return done(new JsonWebTokenError('jwt malformed')); + if (state.lineIndent === 0 && + state.input.charCodeAt(state.position) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 1) === 0x2D/* - */ && + state.input.charCodeAt(state.position + 2) === 0x2D/* - */) { + state.position += 3; + skipSeparationSpace(state, true, -1); + + } else if (hasDirectives) { + throwError(state, 'directives end mark is expected'); } - var decodedToken; + composeNode(state, state.lineIndent - 1, CONTEXT_BLOCK_OUT, false, true); + skipSeparationSpace(state, true, -1); - try { - decodedToken = decode(jwtString, { complete: true }); - } catch(err) { - return done(err); + if (state.checkLineBreaks && + PATTERN_NON_ASCII_LINE_BREAKS.test(state.input.slice(documentStart, state.position))) { + throwWarning(state, 'non-ASCII line breaks are interpreted as content'); } - if (!decodedToken) { - return done(new JsonWebTokenError('invalid token')); - } + state.documents.push(state.result); - var header = decodedToken.header; - var getSecret; + if (state.position === state.lineStart && testDocumentSeparator(state)) { - if(typeof secretOrPublicKey === 'function') { - if(!callback) { - return done(new JsonWebTokenError('verify must be called asynchronous if secret or public key is provided as a callback')); + if (state.input.charCodeAt(state.position) === 0x2E/* . */) { + state.position += 3; + skipSeparationSpace(state, true, -1); } - - getSecret = secretOrPublicKey; + return; } - else { - getSecret = function(header, secretCallback) { - return secretCallback(null, secretOrPublicKey); - }; + + if (state.position < (state.length - 1)) { + throwError(state, 'end of the stream or a document separator is expected'); + } else { + return; } +} - return getSecret(header, function(err, secretOrPublicKey) { - if(err) { - return done(new JsonWebTokenError('error in secret or public key callback: ' + err.message)); - } - var hasSignature = parts[2].trim() !== ''; +function loadDocuments(input, options) { + input = String(input); + options = options || {}; - if (!hasSignature && secretOrPublicKey){ - return done(new JsonWebTokenError('jwt signature is required')); - } + if (input.length !== 0) { - if (hasSignature && !secretOrPublicKey) { - return done(new JsonWebTokenError('secret or public key must be provided')); + // Add tailing `\n` if not exists + if (input.charCodeAt(input.length - 1) !== 0x0A/* LF */ && + input.charCodeAt(input.length - 1) !== 0x0D/* CR */) { + input += '\n'; } - if (!hasSignature && !options.algorithms) { - options.algorithms = ['none']; + // Strip BOM + if (input.charCodeAt(0) === 0xFEFF) { + input = input.slice(1); } + } - if (!options.algorithms) { - options.algorithms = ~secretOrPublicKey.toString().indexOf('BEGIN CERTIFICATE') || - ~secretOrPublicKey.toString().indexOf('BEGIN PUBLIC KEY') ? PUB_KEY_ALGS : - ~secretOrPublicKey.toString().indexOf('BEGIN RSA PUBLIC KEY') ? RSA_KEY_ALGS : HS_ALGS; + var state = new State(input, options); - } + var nullpos = input.indexOf('\0'); - if (!~options.algorithms.indexOf(decodedToken.header.alg)) { - return done(new JsonWebTokenError('invalid algorithm')); - } + if (nullpos !== -1) { + state.position = nullpos; + throwError(state, 'null byte is not allowed in input'); + } - var valid; + // Use 0 as string terminator. That significantly simplifies bounds check. + state.input += '\0'; - try { - valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey); - } catch (e) { - return done(e); - } + while (state.input.charCodeAt(state.position) === 0x20/* Space */) { + state.lineIndent += 1; + state.position += 1; + } - if (!valid) { - return done(new JsonWebTokenError('invalid signature')); - } + while (state.position < (state.length - 1)) { + readDocument(state); + } - var payload = decodedToken.payload; + return state.documents; +} - if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) { - if (typeof payload.nbf !== 'number') { - return done(new JsonWebTokenError('invalid nbf value')); - } - if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) { - return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000))); - } - } - if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) { - if (typeof payload.exp !== 'number') { - return done(new JsonWebTokenError('invalid exp value')); - } - if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) { - return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000))); - } - } +function loadAll(input, iterator, options) { + if (iterator !== null && typeof iterator === 'object' && typeof options === 'undefined') { + options = iterator; + iterator = null; + } - if (options.audience) { - var audiences = Array.isArray(options.audience) ? options.audience : [options.audience]; - var target = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; + var documents = loadDocuments(input, options); - var match = target.some(function (targetAudience) { - return audiences.some(function (audience) { - return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience; - }); - }); + if (typeof iterator !== 'function') { + return documents; + } - if (!match) { - return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or '))); - } - } + for (var index = 0, length = documents.length; index < length; index += 1) { + iterator(documents[index]); + } +} - if (options.issuer) { - var invalid_issuer = - (typeof options.issuer === 'string' && payload.iss !== options.issuer) || - (Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1); - if (invalid_issuer) { - return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer)); - } - } +function load(input, options) { + var documents = loadDocuments(input, options); - if (options.subject) { - if (payload.sub !== options.subject) { - return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject)); - } - } + if (documents.length === 0) { + /*eslint-disable no-undefined*/ + return undefined; + } else if (documents.length === 1) { + return documents[0]; + } + throw new YAMLException('expected a single document in the stream, but found more'); +} - if (options.jwtid) { - if (payload.jti !== options.jwtid) { - return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid)); - } - } - if (options.nonce) { - if (payload.nonce !== options.nonce) { - return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce)); - } - } +function safeLoadAll(input, iterator, options) { + if (typeof iterator === 'object' && iterator !== null && typeof options === 'undefined') { + options = iterator; + iterator = null; + } - if (options.maxAge) { - if (typeof payload.iat !== 'number') { - return done(new JsonWebTokenError('iat required when maxAge is specified')); - } + return loadAll(input, iterator, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} - var maxAgeTimestamp = timespan(options.maxAge, payload.iat); - if (typeof maxAgeTimestamp === 'undefined') { - return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); - } - if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) { - return done(new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000))); - } - } - if (options.complete === true) { - var signature = decodedToken.signature; +function safeLoad(input, options) { + return load(input, common.extend({ schema: DEFAULT_SAFE_SCHEMA }, options)); +} - return done(null, { - header: header, - payload: payload, - signature: signature - }); - } - return done(null, payload); - }); -}; +module.exports.loadAll = loadAll; +module.exports.load = load; +module.exports.safeLoadAll = safeLoadAll; +module.exports.safeLoad = safeLoad; /***/ }), -/***/ 96010: +/***/ 55426: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var bufferEqual = __nccwpck_require__(9239); -var Buffer = __nccwpck_require__(21867).Buffer; -var crypto = __nccwpck_require__(76417); -var formatEcdsa = __nccwpck_require__(11728); -var util = __nccwpck_require__(31669); +"use strict"; -var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' -var MSG_INVALID_SECRET = 'secret must be a string or buffer'; -var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; -var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; -var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; -if (supportsKeyObjects) { - MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; - MSG_INVALID_SECRET += 'or a KeyObject'; -} -function checkIsPublicKey(key) { - if (Buffer.isBuffer(key)) { - return; - } +var common = __nccwpck_require__(59136); - if (typeof key === 'string') { - return; - } - if (!supportsKeyObjects) { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } +function Mark(name, buffer, position, line, column) { + this.name = name; + this.buffer = buffer; + this.position = position; + this.line = line; + this.column = column; +} - if (typeof key !== 'object') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } - if (typeof key.type !== 'string') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } +Mark.prototype.getSnippet = function getSnippet(indent, maxLength) { + var head, start, tail, end, snippet; - if (typeof key.asymmetricKeyType !== 'string') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } + if (!this.buffer) return null; - if (typeof key.export !== 'function') { - throw typeError(MSG_INVALID_VERIFIER_KEY); - } -}; + indent = indent || 4; + maxLength = maxLength || 75; -function checkIsPrivateKey(key) { - if (Buffer.isBuffer(key)) { - return; - } + head = ''; + start = this.position; - if (typeof key === 'string') { - return; + while (start > 0 && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(start - 1)) === -1) { + start -= 1; + if (this.position - start > (maxLength / 2 - 1)) { + head = ' ... '; + start += 5; + break; + } } - if (typeof key === 'object') { - return; + tail = ''; + end = this.position; + + while (end < this.buffer.length && '\x00\r\n\x85\u2028\u2029'.indexOf(this.buffer.charAt(end)) === -1) { + end += 1; + if (end - this.position > (maxLength / 2 - 1)) { + tail = ' ... '; + end -= 5; + break; + } } - throw typeError(MSG_INVALID_SIGNER_KEY); + snippet = this.buffer.slice(start, end); + + return common.repeat(' ', indent) + head + snippet + tail + '\n' + + common.repeat(' ', indent + this.position - start + head.length) + '^'; }; -function checkIsSecretKey(key) { - if (Buffer.isBuffer(key)) { - return; - } - if (typeof key === 'string') { - return key; - } +Mark.prototype.toString = function toString(compact) { + var snippet, where = ''; - if (!supportsKeyObjects) { - throw typeError(MSG_INVALID_SECRET); + if (this.name) { + where += 'in "' + this.name + '" '; } - if (typeof key !== 'object') { - throw typeError(MSG_INVALID_SECRET); - } + where += 'at line ' + (this.line + 1) + ', column ' + (this.column + 1); - if (key.type !== 'secret') { - throw typeError(MSG_INVALID_SECRET); - } + if (!compact) { + snippet = this.getSnippet(); - if (typeof key.export !== 'function') { - throw typeError(MSG_INVALID_SECRET); + if (snippet) { + where += ':\n' + snippet; + } } -} -function fromBase64(base64) { - return base64 - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} + return where; +}; -function toBase64(base64url) { - base64url = base64url.toString(); - var padding = 4 - base64url.length % 4; - if (padding !== 4) { - for (var i = 0; i < padding; ++i) { - base64url += '='; - } - } +module.exports = Mark; - return base64url - .replace(/\-/g, '+') - .replace(/_/g, '/'); -} -function typeError(template) { - var args = [].slice.call(arguments, 1); - var errMsg = util.format.bind(util, template).apply(null, args); - return new TypeError(errMsg); -} +/***/ }), -function bufferOrString(obj) { - return Buffer.isBuffer(obj) || typeof obj === 'string'; -} +/***/ 66514: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -function normalizeInput(thing) { - if (!bufferOrString(thing)) - thing = JSON.stringify(thing); - return thing; -} +"use strict"; -function createHmacSigner(bits) { - return function sign(thing, secret) { - checkIsSecretKey(secret); - thing = normalizeInput(thing); - var hmac = crypto.createHmac('sha' + bits, secret); - var sig = (hmac.update(thing), hmac.digest('base64')) - return fromBase64(sig); - } -} -function createHmacVerifier(bits) { - return function verify(thing, signature, secret) { - var computedSig = createHmacSigner(bits)(thing, secret); - return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); - } -} +/*eslint-disable max-len*/ -function createKeySigner(bits) { - return function sign(thing, privateKey) { - checkIsPrivateKey(privateKey); - thing = normalizeInput(thing); - // Even though we are specifying "RSA" here, this works with ECDSA - // keys as well. - var signer = crypto.createSign('RSA-SHA' + bits); - var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); - return fromBase64(sig); - } -} +var common = __nccwpck_require__(59136); +var YAMLException = __nccwpck_require__(65199); +var Type = __nccwpck_require__(30967); -function createKeyVerifier(bits) { - return function verify(thing, signature, publicKey) { - checkIsPublicKey(publicKey); - thing = normalizeInput(thing); - signature = toBase64(signature); - var verifier = crypto.createVerify('RSA-SHA' + bits); - verifier.update(thing); - return verifier.verify(publicKey, signature, 'base64'); - } -} -function createPSSKeySigner(bits) { - return function sign(thing, privateKey) { - checkIsPrivateKey(privateKey); - thing = normalizeInput(thing); - var signer = crypto.createSign('RSA-SHA' + bits); - var sig = (signer.update(thing), signer.sign({ - key: privateKey, - padding: crypto.constants.RSA_PKCS1_PSS_PADDING, - saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST - }, 'base64')); - return fromBase64(sig); - } -} +function compileList(schema, name, result) { + var exclude = []; -function createPSSKeyVerifier(bits) { - return function verify(thing, signature, publicKey) { - checkIsPublicKey(publicKey); - thing = normalizeInput(thing); - signature = toBase64(signature); - var verifier = crypto.createVerify('RSA-SHA' + bits); - verifier.update(thing); - return verifier.verify({ - key: publicKey, - padding: crypto.constants.RSA_PKCS1_PSS_PADDING, - saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST - }, signature, 'base64'); - } -} + schema.include.forEach(function (includedSchema) { + result = compileList(includedSchema, name, result); + }); -function createECDSASigner(bits) { - var inner = createKeySigner(bits); - return function sign() { - var signature = inner.apply(null, arguments); - signature = formatEcdsa.derToJose(signature, 'ES' + bits); - return signature; - }; -} + schema[name].forEach(function (currentType) { + result.forEach(function (previousType, previousIndex) { + if (previousType.tag === currentType.tag && previousType.kind === currentType.kind) { + exclude.push(previousIndex); + } + }); -function createECDSAVerifer(bits) { - var inner = createKeyVerifier(bits); - return function verify(thing, signature, publicKey) { - signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); - var result = inner(thing, signature, publicKey); - return result; - }; -} + result.push(currentType); + }); -function createNoneSigner() { - return function sign() { - return ''; - } + return result.filter(function (type, index) { + return exclude.indexOf(index) === -1; + }); } -function createNoneVerifier() { - return function verify(thing, signature) { - return signature === ''; - } -} -module.exports = function jwa(algorithm) { - var signerFactories = { - hs: createHmacSigner, - rs: createKeySigner, - ps: createPSSKeySigner, - es: createECDSASigner, - none: createNoneSigner, - } - var verifierFactories = { - hs: createHmacVerifier, - rs: createKeyVerifier, - ps: createPSSKeyVerifier, - es: createECDSAVerifer, - none: createNoneVerifier, - } - var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/i); - if (!match) - throw typeError(MSG_INVALID_ALGORITHM, algorithm); - var algo = (match[1] || match[3]).toLowerCase(); - var bits = match[2]; +function compileMap(/* lists... */) { + var result = { + scalar: {}, + sequence: {}, + mapping: {}, + fallback: {} + }, index, length; - return { - sign: signerFactories[algo](bits), - verify: verifierFactories[algo](bits), + function collectType(type) { + result[type.kind][type.tag] = result['fallback'][type.tag] = type; } -}; + for (index = 0, length = arguments.length; index < length; index += 1) { + arguments[index].forEach(collectType); + } + return result; +} -/***/ }), -/***/ 4636: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { +function Schema(definition) { + this.include = definition.include || []; + this.implicit = definition.implicit || []; + this.explicit = definition.explicit || []; -/*global exports*/ -var SignStream = __nccwpck_require__(73334); -var VerifyStream = __nccwpck_require__(5522); + this.implicit.forEach(function (type) { + if (type.loadKind && type.loadKind !== 'scalar') { + throw new YAMLException('There is a non-scalar type in the implicit list of a schema. Implicit resolving of such types is not supported.'); + } + }); -var ALGORITHMS = [ - 'HS256', 'HS384', 'HS512', - 'RS256', 'RS384', 'RS512', - 'PS256', 'PS384', 'PS512', - 'ES256', 'ES384', 'ES512' -]; + this.compiledImplicit = compileList(this, 'implicit', []); + this.compiledExplicit = compileList(this, 'explicit', []); + this.compiledTypeMap = compileMap(this.compiledImplicit, this.compiledExplicit); +} -exports.ALGORITHMS = ALGORITHMS; -exports.sign = SignStream.sign; -exports.verify = VerifyStream.verify; -exports.decode = VerifyStream.decode; -exports.isValid = VerifyStream.isValid; -exports.createSign = function createSign(opts) { - return new SignStream(opts); -}; -exports.createVerify = function createVerify(opts) { - return new VerifyStream(opts); -}; +Schema.DEFAULT = null; -/***/ }), -/***/ 61868: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +Schema.create = function createSchema() { + var schemas, types; -/*global module, process*/ -var Buffer = __nccwpck_require__(21867).Buffer; -var Stream = __nccwpck_require__(92413); -var util = __nccwpck_require__(31669); + switch (arguments.length) { + case 1: + schemas = Schema.DEFAULT; + types = arguments[0]; + break; -function DataStream(data) { - this.buffer = null; - this.writable = true; - this.readable = true; + case 2: + schemas = arguments[0]; + types = arguments[1]; + break; - // No input - if (!data) { - this.buffer = Buffer.alloc(0); - return this; + default: + throw new YAMLException('Wrong number of arguments for Schema.create function'); } - // Stream - if (typeof data.pipe === 'function') { - this.buffer = Buffer.alloc(0); - data.pipe(this); - return this; - } + schemas = common.toArray(schemas); + types = common.toArray(types); - // Buffer or String - // or Object (assumedly a passworded key) - if (data.length || typeof data === 'object') { - this.buffer = data; - this.writable = false; - process.nextTick(function () { - this.emit('end', data); - this.readable = false; - this.emit('close'); - }.bind(this)); - return this; + if (!schemas.every(function (schema) { return schema instanceof Schema; })) { + throw new YAMLException('Specified list of super schemas (or a single Schema object) contains a non-Schema object.'); } - throw new TypeError('Unexpected data type ('+ typeof data + ')'); -} -util.inherits(DataStream, Stream); + if (!types.every(function (type) { return type instanceof Type; })) { + throw new YAMLException('Specified list of YAML types (or a single Type object) contains a non-Type object.'); + } -DataStream.prototype.write = function write(data) { - this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); - this.emit('data', data); + return new Schema({ + include: schemas, + explicit: types + }); }; -DataStream.prototype.end = function end(data) { - if (data) - this.write(data); - this.emit('end', data); - this.emit('close'); - this.writable = false; - this.readable = false; -}; -module.exports = DataStream; +module.exports = Schema; /***/ }), -/***/ 73334: +/***/ 92183: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/*global module*/ -var Buffer = __nccwpck_require__(21867).Buffer; -var DataStream = __nccwpck_require__(61868); -var jwa = __nccwpck_require__(96010); -var Stream = __nccwpck_require__(92413); -var toString = __nccwpck_require__(65292); -var util = __nccwpck_require__(31669); +"use strict"; +// Standard YAML's Core schema. +// http://www.yaml.org/spec/1.2/spec.html#id2804923 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, Core schema has no distinctions from JSON schema is JS-YAML. -function base64url(string, encoding) { - return Buffer - .from(string, encoding) - .toString('base64') - .replace(/=/g, '') - .replace(/\+/g, '-') - .replace(/\//g, '_'); -} -function jwsSecuredInput(header, payload, encoding) { - encoding = encoding || 'utf8'; - var encodedHeader = base64url(toString(header), 'binary'); - var encodedPayload = base64url(toString(payload), encoding); - return util.format('%s.%s', encodedHeader, encodedPayload); -} -function jwsSign(opts) { - var header = opts.header; - var payload = opts.payload; - var secretOrKey = opts.secret || opts.privateKey; - var encoding = opts.encoding; - var algo = jwa(header.alg); - var securedInput = jwsSecuredInput(header, payload, encoding); - var signature = algo.sign(securedInput, secretOrKey); - return util.format('%s.%s', securedInput, signature); -} -function SignStream(opts) { - var secret = opts.secret||opts.privateKey||opts.key; - var secretStream = new DataStream(secret); - this.readable = true; - this.header = opts.header; - this.encoding = opts.encoding; - this.secret = this.privateKey = this.key = secretStream; - this.payload = new DataStream(opts.payload); - this.secret.once('close', function () { - if (!this.payload.writable && this.readable) - this.sign(); - }.bind(this)); - this.payload.once('close', function () { - if (!this.secret.writable && this.readable) - this.sign(); - }.bind(this)); -} -util.inherits(SignStream, Stream); +var Schema = __nccwpck_require__(66514); -SignStream.prototype.sign = function sign() { - try { - var signature = jwsSign({ - header: this.header, - payload: this.payload.buffer, - secret: this.secret.buffer, - encoding: this.encoding - }); - this.emit('done', signature); - this.emit('data', signature); - this.emit('end'); - this.readable = false; - return signature; - } catch (e) { - this.readable = false; - this.emit('error', e); - this.emit('close'); - } -}; -SignStream.sign = jwsSign; +module.exports = new Schema({ + include: [ + __nccwpck_require__(1571) + ] +}); + + +/***/ }), + +/***/ 56874: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; +// JS-YAML's default schema for `load` function. +// It is not described in the YAML specification. +// +// This schema is based on JS-YAML's default safe schema and includes +// JavaScript-specific types: !!js/undefined, !!js/regexp and !!js/function. +// +// Also this schema is used as default base schema at `Schema.create` function. + -module.exports = SignStream; -/***/ }), -/***/ 65292: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { +var Schema = __nccwpck_require__(66514); -/*global module*/ -var Buffer = __nccwpck_require__(64293).Buffer; -module.exports = function toString(obj) { - if (typeof obj === 'string') - return obj; - if (typeof obj === 'number' || Buffer.isBuffer(obj)) - return obj.toString(); - return JSON.stringify(obj); -}; +module.exports = Schema.DEFAULT = new Schema({ + include: [ + __nccwpck_require__(48949) + ], + explicit: [ + __nccwpck_require__(25914), + __nccwpck_require__(69242), + __nccwpck_require__(27278) + ] +}); /***/ }), -/***/ 5522: +/***/ 48949: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/*global module*/ -var Buffer = __nccwpck_require__(21867).Buffer; -var DataStream = __nccwpck_require__(61868); -var jwa = __nccwpck_require__(96010); -var Stream = __nccwpck_require__(92413); -var toString = __nccwpck_require__(65292); -var util = __nccwpck_require__(31669); -var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; +"use strict"; +// JS-YAML's default schema for `safeLoad` function. +// It is not described in the YAML specification. +// +// This schema is based on standard YAML's Core schema and includes most of +// extra types described at YAML tag repository. (http://yaml.org/type/) -function isObject(thing) { - return Object.prototype.toString.call(thing) === '[object Object]'; -} -function safeJsonParse(thing) { - if (isObject(thing)) - return thing; - try { return JSON.parse(thing); } - catch (e) { return undefined; } -} -function headerFromJWS(jwsSig) { - var encodedHeader = jwsSig.split('.', 1)[0]; - return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); -} -function securedInputFromJWS(jwsSig) { - return jwsSig.split('.', 2).join('.'); -} -function signatureFromJWS(jwsSig) { - return jwsSig.split('.')[2]; -} +var Schema = __nccwpck_require__(66514); -function payloadFromJWS(jwsSig, encoding) { - encoding = encoding || 'utf8'; - var payload = jwsSig.split('.')[1]; - return Buffer.from(payload, 'base64').toString(encoding); -} -function isValidJws(string) { - return JWS_REGEX.test(string) && !!headerFromJWS(string); -} +module.exports = new Schema({ + include: [ + __nccwpck_require__(92183) + ], + implicit: [ + __nccwpck_require__(83714), + __nccwpck_require__(81393) + ], + explicit: [ + __nccwpck_require__(32551), + __nccwpck_require__(96668), + __nccwpck_require__(76039), + __nccwpck_require__(69237) + ] +}); -function jwsVerify(jwsSig, algorithm, secretOrKey) { - if (!algorithm) { - var err = new Error("Missing algorithm parameter for jws.verify"); - err.code = "MISSING_ALGORITHM"; - throw err; - } - jwsSig = toString(jwsSig); - var signature = signatureFromJWS(jwsSig); - var securedInput = securedInputFromJWS(jwsSig); - var algo = jwa(algorithm); - return algo.verify(securedInput, signature, secretOrKey); -} -function jwsDecode(jwsSig, opts) { - opts = opts || {}; - jwsSig = toString(jwsSig); +/***/ }), - if (!isValidJws(jwsSig)) - return null; +/***/ 66037: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - var header = headerFromJWS(jwsSig); +"use strict"; +// Standard YAML's Failsafe schema. +// http://www.yaml.org/spec/1.2/spec.html#id2802346 - if (!header) - return null; - var payload = payloadFromJWS(jwsSig); - if (header.typ === 'JWT' || opts.json) - payload = JSON.parse(payload, opts.encoding); - return { - header: header, - payload: payload, - signature: signatureFromJWS(jwsSig) - }; -} -function VerifyStream(opts) { - opts = opts || {}; - var secretOrKey = opts.secret||opts.publicKey||opts.key; - var secretStream = new DataStream(secretOrKey); - this.readable = true; - this.algorithm = opts.algorithm; - this.encoding = opts.encoding; - this.secret = this.publicKey = this.key = secretStream; - this.signature = new DataStream(opts.signature); - this.secret.once('close', function () { - if (!this.signature.writable && this.readable) - this.verify(); - }.bind(this)); - this.signature.once('close', function () { - if (!this.secret.writable && this.readable) - this.verify(); - }.bind(this)); -} -util.inherits(VerifyStream, Stream); -VerifyStream.prototype.verify = function verify() { - try { - var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); - var obj = jwsDecode(this.signature.buffer, this.encoding); - this.emit('done', valid, obj); - this.emit('data', valid); - this.emit('end'); - this.readable = false; - return valid; - } catch (e) { - this.readable = false; - this.emit('error', e); - this.emit('close'); - } -}; +var Schema = __nccwpck_require__(66514); -VerifyStream.decode = jwsDecode; -VerifyStream.isValid = isValidJws; -VerifyStream.verify = jwsVerify; -module.exports = VerifyStream; +module.exports = new Schema({ + explicit: [ + __nccwpck_require__(93955), + __nccwpck_require__(5490), + __nccwpck_require__(31173) + ] +}); /***/ }), -/***/ 75978: +/***/ 1571: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; +// Standard YAML's JSON schema. +// http://www.yaml.org/spec/1.2/spec.html#id2803231 +// +// NOTE: JS-YAML does not support schema-specific tag resolution restrictions. +// So, this schema is not such strict as defined in the YAML specification. +// It allows numbers in binary notaion, use `Null` and `NULL` as `null`, etc. -const path = __nccwpck_require__(85622); -const fs = __nccwpck_require__(18962); -const stripBom = __nccwpck_require__(88551); -const parseJson = __nccwpck_require__(81680); -const pify = __nccwpck_require__(64810); -const parse = (data, filePath, options = {}) => { - data = stripBom(data); - if (typeof options.beforeParse === 'function') { - data = options.beforeParse(data); - } - return parseJson(data, options.reviver, path.relative(process.cwd(), filePath)); -}; -const loadJsonFile = (filePath, options) => pify(fs.readFile)(filePath, 'utf8').then(data => parse(data, filePath, options)); +var Schema = __nccwpck_require__(66514); -module.exports = loadJsonFile; -module.exports.default = loadJsonFile; -module.exports.sync = (filePath, options) => parse(fs.readFileSync(filePath, 'utf8'), filePath, options); + +module.exports = new Schema({ + include: [ + __nccwpck_require__(66037) + ], + implicit: [ + __nccwpck_require__(22671), + __nccwpck_require__(94675), + __nccwpck_require__(89963), + __nccwpck_require__(15564) + ] +}); /***/ }), -/***/ 70760: -/***/ ((module) => { +/***/ 30967: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -module.exports = clone +var YAMLException = __nccwpck_require__(65199); -function clone (obj) { - if (obj === null || typeof obj !== 'object') - return obj +var TYPE_CONSTRUCTOR_OPTIONS = [ + 'kind', + 'resolve', + 'construct', + 'instanceOf', + 'predicate', + 'represent', + 'defaultStyle', + 'styleAliases' +]; - if (obj instanceof Object) - var copy = { __proto__: obj.__proto__ } - else - var copy = Object.create(null) +var YAML_NODE_KINDS = [ + 'scalar', + 'sequence', + 'mapping' +]; - Object.getOwnPropertyNames(obj).forEach(function (key) { - Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) - }) +function compileStyleAliases(map) { + var result = {}; - return copy + if (map !== null) { + Object.keys(map).forEach(function (style) { + map[style].forEach(function (alias) { + result[String(alias)] = style; + }); + }); + } + + return result; +} + +function Type(tag, options) { + options = options || {}; + + Object.keys(options).forEach(function (name) { + if (TYPE_CONSTRUCTOR_OPTIONS.indexOf(name) === -1) { + throw new YAMLException('Unknown option "' + name + '" is met in definition of "' + tag + '" YAML type.'); + } + }); + + // TODO: Add tag format check. + this.tag = tag; + this.kind = options['kind'] || null; + this.resolve = options['resolve'] || function () { return true; }; + this.construct = options['construct'] || function (data) { return data; }; + this.instanceOf = options['instanceOf'] || null; + this.predicate = options['predicate'] || null; + this.represent = options['represent'] || null; + this.defaultStyle = options['defaultStyle'] || null; + this.styleAliases = compileStyleAliases(options['styleAliases'] || null); + + if (YAML_NODE_KINDS.indexOf(this.kind) === -1) { + throw new YAMLException('Unknown kind "' + this.kind + '" is specified for "' + tag + '" YAML type.'); + } } +module.exports = Type; + /***/ }), -/***/ 18962: +/***/ 32551: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var fs = __nccwpck_require__(35747) -var polyfills = __nccwpck_require__(11566) -var legacy = __nccwpck_require__(21357) -var clone = __nccwpck_require__(70760) +"use strict"; -var queue = [] -var util = __nccwpck_require__(31669) +/*eslint-disable no-bitwise*/ -function noop () {} +var NodeBuffer; -var debug = noop -if (util.debuglog) - debug = util.debuglog('gfs4') -else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) - debug = function() { - var m = util.format.apply(util, arguments) - m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') - console.error(m) - } +try { + // A trick for browserified version, to not include `Buffer` shim + var _require = require; + NodeBuffer = _require('buffer').Buffer; +} catch (__) {} -if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { - process.on('exit', function() { - debug(queue) - __nccwpck_require__(42357).equal(queue.length, 0) - }) -} +var Type = __nccwpck_require__(30967); -module.exports = patch(clone(fs)) -if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { - module.exports = patch(fs) - fs.__patched = true; -} -// Always patch fs.close/closeSync, because we want to -// retry() whenever a close happens *anywhere* in the program. -// This is essential when multiple graceful-fs instances are -// in play at the same time. -module.exports.close = (function (fs$close) { return function (fd, cb) { - return fs$close.call(fs, fd, function (err) { - if (!err) - retry() +// [ 64, 65, 66 ] -> [ padding, CR, LF ] +var BASE64_MAP = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r'; - if (typeof cb === 'function') - cb.apply(this, arguments) - }) -}})(fs.close) -module.exports.closeSync = (function (fs$closeSync) { return function (fd) { - // Note that graceful-fs also retries when fs.closeSync() fails. - // Looks like a bug to me, although it's probably a harmless one. - var rval = fs$closeSync.apply(fs, arguments) - retry() - return rval -}})(fs.closeSync) +function resolveYamlBinary(data) { + if (data === null) return false; + + var code, idx, bitlen = 0, max = data.length, map = BASE64_MAP; + + // Convert one by one. + for (idx = 0; idx < max; idx++) { + code = map.indexOf(data.charAt(idx)); + + // Skip CR/LF + if (code > 64) continue; -// Only patch fs once, otherwise we'll run into a memory leak if -// graceful-fs is loaded multiple times, such as in test environments that -// reset the loaded modules between tests. -// We look for the string `graceful-fs` from the comment above. This -// way we are not adding any extra properties and it will detect if older -// versions of graceful-fs are installed. -if (!/\bgraceful-fs\b/.test(fs.closeSync.toString())) { - fs.closeSync = module.exports.closeSync; - fs.close = module.exports.close; + // Fail on illegal characters + if (code < 0) return false; + + bitlen += 6; + } + + // If there are any bits left, source was corrupted + return (bitlen % 8) === 0; } -function patch (fs) { - // Everything that references the open() function needs to be in here - polyfills(fs) - fs.gracefulify = patch - fs.FileReadStream = ReadStream; // Legacy name. - fs.FileWriteStream = WriteStream; // Legacy name. - fs.createReadStream = createReadStream - fs.createWriteStream = createWriteStream - var fs$readFile = fs.readFile - fs.readFile = readFile - function readFile (path, options, cb) { - if (typeof options === 'function') - cb = options, options = null +function constructYamlBinary(data) { + var idx, tailbits, + input = data.replace(/[\r\n=]/g, ''), // remove CR/LF & padding to simplify scan + max = input.length, + map = BASE64_MAP, + bits = 0, + result = []; - return go$readFile(path, options, cb) + // Collect by 6*4 bits (3 bytes) - function go$readFile (path, options, cb) { - return fs$readFile(path, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readFile, [path, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) + for (idx = 0; idx < max; idx++) { + if ((idx % 4 === 0) && idx) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); } + + bits = (bits << 6) | map.indexOf(input.charAt(idx)); } - var fs$writeFile = fs.writeFile - fs.writeFile = writeFile - function writeFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + // Dump tail - return go$writeFile(path, data, options, cb) + tailbits = (max % 4) * 6; - function go$writeFile (path, data, options, cb) { - return fs$writeFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$writeFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) - } + if (tailbits === 0) { + result.push((bits >> 16) & 0xFF); + result.push((bits >> 8) & 0xFF); + result.push(bits & 0xFF); + } else if (tailbits === 18) { + result.push((bits >> 10) & 0xFF); + result.push((bits >> 2) & 0xFF); + } else if (tailbits === 12) { + result.push((bits >> 4) & 0xFF); } - var fs$appendFile = fs.appendFile - if (fs$appendFile) - fs.appendFile = appendFile - function appendFile (path, data, options, cb) { - if (typeof options === 'function') - cb = options, options = null + // Wrap into Buffer for NodeJS and leave Array for browser + if (NodeBuffer) { + // Support node 6.+ Buffer API when available + return NodeBuffer.from ? NodeBuffer.from(result) : new NodeBuffer(result); + } - return go$appendFile(path, data, options, cb) + return result; +} - function go$appendFile (path, data, options, cb) { - return fs$appendFile(path, data, options, function (err) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$appendFile, [path, data, options, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) +function representYamlBinary(object /*, style*/) { + var result = '', bits = 0, idx, tail, + max = object.length, + map = BASE64_MAP; + + // Convert every three bytes to 4 ASCII characters. + + for (idx = 0; idx < max; idx++) { + if ((idx % 3 === 0) && idx) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; } + + bits = (bits << 8) + object[idx]; } - var fs$readdir = fs.readdir - fs.readdir = readdir - function readdir (path, options, cb) { - var args = [path] - if (typeof options !== 'function') { - args.push(options) - } else { - cb = options - } - args.push(go$readdir$cb) + // Dump tail + + tail = max % 3; + + if (tail === 0) { + result += map[(bits >> 18) & 0x3F]; + result += map[(bits >> 12) & 0x3F]; + result += map[(bits >> 6) & 0x3F]; + result += map[bits & 0x3F]; + } else if (tail === 2) { + result += map[(bits >> 10) & 0x3F]; + result += map[(bits >> 4) & 0x3F]; + result += map[(bits << 2) & 0x3F]; + result += map[64]; + } else if (tail === 1) { + result += map[(bits >> 2) & 0x3F]; + result += map[(bits << 4) & 0x3F]; + result += map[64]; + result += map[64]; + } + + return result; +} + +function isBinary(object) { + return NodeBuffer && NodeBuffer.isBuffer(object); +} + +module.exports = new Type('tag:yaml.org,2002:binary', { + kind: 'scalar', + resolve: resolveYamlBinary, + construct: constructYamlBinary, + predicate: isBinary, + represent: representYamlBinary +}); + + +/***/ }), + +/***/ 94675: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Type = __nccwpck_require__(30967); + +function resolveYamlBoolean(data) { + if (data === null) return false; + + var max = data.length; + + return (max === 4 && (data === 'true' || data === 'True' || data === 'TRUE')) || + (max === 5 && (data === 'false' || data === 'False' || data === 'FALSE')); +} + +function constructYamlBoolean(data) { + return data === 'true' || + data === 'True' || + data === 'TRUE'; +} + +function isBoolean(object) { + return Object.prototype.toString.call(object) === '[object Boolean]'; +} + +module.exports = new Type('tag:yaml.org,2002:bool', { + kind: 'scalar', + resolve: resolveYamlBoolean, + construct: constructYamlBoolean, + predicate: isBoolean, + represent: { + lowercase: function (object) { return object ? 'true' : 'false'; }, + uppercase: function (object) { return object ? 'TRUE' : 'FALSE'; }, + camelcase: function (object) { return object ? 'True' : 'False'; } + }, + defaultStyle: 'lowercase' +}); + + +/***/ }), + +/***/ 15564: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - return go$readdir(args) +"use strict"; - function go$readdir$cb (err, files) { - if (files && files.sort) - files.sort() - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$readdir, [args]]) +var common = __nccwpck_require__(59136); +var Type = __nccwpck_require__(30967); - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - } - } +var YAML_FLOAT_PATTERN = new RegExp( + // 2.5e4, 2.5 and integers + '^(?:[-+]?(?:0|[1-9][0-9_]*)(?:\\.[0-9_]*)?(?:[eE][-+]?[0-9]+)?' + + // .2e4, .2 + // special case, seems not from spec + '|\\.[0-9_]+(?:[eE][-+]?[0-9]+)?' + + // 20:59 + '|[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*' + + // .inf + '|[-+]?\\.(?:inf|Inf|INF)' + + // .nan + '|\\.(?:nan|NaN|NAN))$'); - function go$readdir (args) { - return fs$readdir.apply(fs, args) - } +function resolveYamlFloat(data) { + if (data === null) return false; - if (process.version.substr(0, 4) === 'v0.8') { - var legStreams = legacy(fs) - ReadStream = legStreams.ReadStream - WriteStream = legStreams.WriteStream + if (!YAML_FLOAT_PATTERN.test(data) || + // Quick hack to not allow integers end with `_` + // Probably should update regexp & check speed + data[data.length - 1] === '_') { + return false; } - var fs$ReadStream = fs.ReadStream - if (fs$ReadStream) { - ReadStream.prototype = Object.create(fs$ReadStream.prototype) - ReadStream.prototype.open = ReadStream$open - } + return true; +} - var fs$WriteStream = fs.WriteStream - if (fs$WriteStream) { - WriteStream.prototype = Object.create(fs$WriteStream.prototype) - WriteStream.prototype.open = WriteStream$open - } +function constructYamlFloat(data) { + var value, sign, base, digits; - fs.ReadStream = ReadStream - fs.WriteStream = WriteStream + value = data.replace(/_/g, '').toLowerCase(); + sign = value[0] === '-' ? -1 : 1; + digits = []; - function ReadStream (path, options) { - if (this instanceof ReadStream) - return fs$ReadStream.apply(this, arguments), this - else - return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + if ('+-'.indexOf(value[0]) >= 0) { + value = value.slice(1); } - function ReadStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - if (that.autoClose) - that.destroy() + if (value === '.inf') { + return (sign === 1) ? Number.POSITIVE_INFINITY : Number.NEGATIVE_INFINITY; - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - that.read() - } - }) - } + } else if (value === '.nan') { + return NaN; - function WriteStream (path, options) { - if (this instanceof WriteStream) - return fs$WriteStream.apply(this, arguments), this - else - return WriteStream.apply(Object.create(WriteStream.prototype), arguments) - } + } else if (value.indexOf(':') >= 0) { + value.split(':').forEach(function (v) { + digits.unshift(parseFloat(v, 10)); + }); - function WriteStream$open () { - var that = this - open(that.path, that.flags, that.mode, function (err, fd) { - if (err) { - that.destroy() - that.emit('error', err) - } else { - that.fd = fd - that.emit('open', fd) - } - }) - } + value = 0.0; + base = 1; - function createReadStream (path, options) { - return new ReadStream(path, options) - } + digits.forEach(function (d) { + value += d * base; + base *= 60; + }); + + return sign * value; - function createWriteStream (path, options) { - return new WriteStream(path, options) } + return sign * parseFloat(value, 10); +} - var fs$open = fs.open - fs.open = open - function open (path, flags, mode, cb) { - if (typeof mode === 'function') - cb = mode, mode = null - return go$open(path, flags, mode, cb) +var SCIENTIFIC_WITHOUT_DOT = /^[-+]?[0-9]+e/; - function go$open (path, flags, mode, cb) { - return fs$open(path, flags, mode, function (err, fd) { - if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) - enqueue([go$open, [path, flags, mode, cb]]) - else { - if (typeof cb === 'function') - cb.apply(this, arguments) - retry() - } - }) +function representYamlFloat(object, style) { + var res; + + if (isNaN(object)) { + switch (style) { + case 'lowercase': return '.nan'; + case 'uppercase': return '.NAN'; + case 'camelcase': return '.NaN'; + } + } else if (Number.POSITIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '.inf'; + case 'uppercase': return '.INF'; + case 'camelcase': return '.Inf'; + } + } else if (Number.NEGATIVE_INFINITY === object) { + switch (style) { + case 'lowercase': return '-.inf'; + case 'uppercase': return '-.INF'; + case 'camelcase': return '-.Inf'; } + } else if (common.isNegativeZero(object)) { + return '-0.0'; } - return fs -} + res = object.toString(10); -function enqueue (elem) { - debug('ENQUEUE', elem[0].name, elem[1]) - queue.push(elem) + // JS stringifier can build scientific format without dots: 5e-100, + // while YAML requres dot: 5.e-100. Fix it with simple hack + + return SCIENTIFIC_WITHOUT_DOT.test(res) ? res.replace('e', '.e') : res; } -function retry () { - var elem = queue.shift() - if (elem) { - debug('RETRY', elem[0].name, elem[1]) - elem[0].apply(null, elem[1]) - } +function isFloat(object) { + return (Object.prototype.toString.call(object) === '[object Number]') && + (object % 1 !== 0 || common.isNegativeZero(object)); } +module.exports = new Type('tag:yaml.org,2002:float', { + kind: 'scalar', + resolve: resolveYamlFloat, + construct: constructYamlFloat, + predicate: isFloat, + represent: representYamlFloat, + defaultStyle: 'lowercase' +}); + /***/ }), -/***/ 21357: +/***/ 89963: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -var Stream = __nccwpck_require__(92413).Stream +"use strict"; -module.exports = legacy -function legacy (fs) { - return { - ReadStream: ReadStream, - WriteStream: WriteStream - } +var common = __nccwpck_require__(59136); +var Type = __nccwpck_require__(30967); - function ReadStream (path, options) { - if (!(this instanceof ReadStream)) return new ReadStream(path, options); +function isHexCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)) || + ((0x41/* A */ <= c) && (c <= 0x46/* F */)) || + ((0x61/* a */ <= c) && (c <= 0x66/* f */)); +} - Stream.call(this); +function isOctCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x37/* 7 */)); +} - var self = this; +function isDecCode(c) { + return ((0x30/* 0 */ <= c) && (c <= 0x39/* 9 */)); +} - this.path = path; - this.fd = null; - this.readable = true; - this.paused = false; +function resolveYamlInteger(data) { + if (data === null) return false; - this.flags = 'r'; - this.mode = 438; /*=0666*/ - this.bufferSize = 64 * 1024; + var max = data.length, + index = 0, + hasDigits = false, + ch; - options = options || {}; + if (!max) return false; - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } + ch = data[index]; - if (this.encoding) this.setEncoding(this.encoding); + // sign + if (ch === '-' || ch === '+') { + ch = data[++index]; + } - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.end === undefined) { - this.end = Infinity; - } else if ('number' !== typeof this.end) { - throw TypeError('end must be a Number'); - } + if (ch === '0') { + // 0 + if (index + 1 === max) return true; + ch = data[++index]; - if (this.start > this.end) { - throw new Error('start must be <= end'); - } + // base 2, base 8, base 16 - this.pos = this.start; - } + if (ch === 'b') { + // base 2 + index++; - if (this.fd !== null) { - process.nextTick(function() { - self._read(); - }); - return; + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch !== '0' && ch !== '1') return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; } - fs.open(this.path, this.flags, this.mode, function (err, fd) { - if (err) { - self.emit('error', err); - self.readable = false; - return; + + if (ch === 'x') { + // base 16 + index++; + + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isHexCode(data.charCodeAt(index))) return false; + hasDigits = true; } + return hasDigits && ch !== '_'; + } - self.fd = fd; - self.emit('open', fd); - self._read(); - }) + // base 8 + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (!isOctCode(data.charCodeAt(index))) return false; + hasDigits = true; + } + return hasDigits && ch !== '_'; } - function WriteStream (path, options) { - if (!(this instanceof WriteStream)) return new WriteStream(path, options); + // base 10 (except 0) or base 60 - Stream.call(this); + // value should not start with `_`; + if (ch === '_') return false; - this.path = path; - this.fd = null; - this.writable = true; + for (; index < max; index++) { + ch = data[index]; + if (ch === '_') continue; + if (ch === ':') break; + if (!isDecCode(data.charCodeAt(index))) { + return false; + } + hasDigits = true; + } - this.flags = 'w'; - this.encoding = 'binary'; - this.mode = 438; /*=0666*/ - this.bytesWritten = 0; + // Should have digits and should not end with `_` + if (!hasDigits || ch === '_') return false; - options = options || {}; + // if !base60 - done; + if (ch !== ':') return true; - // Mixin options into this - var keys = Object.keys(options); - for (var index = 0, length = keys.length; index < length; index++) { - var key = keys[index]; - this[key] = options[key]; - } + // base60 almost not used, no needs to optimize + return /^(:[0-5]?[0-9])+$/.test(data.slice(index)); +} - if (this.start !== undefined) { - if ('number' !== typeof this.start) { - throw TypeError('start must be a Number'); - } - if (this.start < 0) { - throw new Error('start must be >= zero'); - } +function constructYamlInteger(data) { + var value = data, sign = 1, ch, base, digits = []; - this.pos = this.start; - } + if (value.indexOf('_') !== -1) { + value = value.replace(/_/g, ''); + } - this.busy = false; - this._queue = []; + ch = value[0]; - if (this.fd === null) { - this._open = fs.open; - this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); - this.flush(); - } + if (ch === '-' || ch === '+') { + if (ch === '-') sign = -1; + value = value.slice(1); + ch = value[0]; } -} + if (value === '0') return 0; -/***/ }), + if (ch === '0') { + if (value[1] === 'b') return sign * parseInt(value.slice(2), 2); + if (value[1] === 'x') return sign * parseInt(value, 16); + return sign * parseInt(value, 8); + } -/***/ 11566: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + if (value.indexOf(':') !== -1) { + value.split(':').forEach(function (v) { + digits.unshift(parseInt(v, 10)); + }); -var constants = __nccwpck_require__(27619) + value = 0; + base = 1; -var origCwd = process.cwd -var cwd = null + digits.forEach(function (d) { + value += (d * base); + base *= 60; + }); -var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform + return sign * value; -process.cwd = function() { - if (!cwd) - cwd = origCwd.call(process) - return cwd -} -try { - process.cwd() -} catch (er) {} + } -var chdir = process.chdir -process.chdir = function(d) { - cwd = null - chdir.call(process, d) + return sign * parseInt(value, 10); } -module.exports = patch - -function patch (fs) { - // (re-)implement some things that are known busted or missing. - - // lchmod, broken prior to 0.6.2 - // back-port the fix here. - if (constants.hasOwnProperty('O_SYMLINK') && - process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { - patchLchmod(fs) - } +function isInteger(object) { + return (Object.prototype.toString.call(object)) === '[object Number]' && + (object % 1 === 0 && !common.isNegativeZero(object)); +} - // lutimes implementation, or no-op - if (!fs.lutimes) { - patchLutimes(fs) +module.exports = new Type('tag:yaml.org,2002:int', { + kind: 'scalar', + resolve: resolveYamlInteger, + construct: constructYamlInteger, + predicate: isInteger, + represent: { + binary: function (obj) { return obj >= 0 ? '0b' + obj.toString(2) : '-0b' + obj.toString(2).slice(1); }, + octal: function (obj) { return obj >= 0 ? '0' + obj.toString(8) : '-0' + obj.toString(8).slice(1); }, + decimal: function (obj) { return obj.toString(10); }, + /* eslint-disable max-len */ + hexadecimal: function (obj) { return obj >= 0 ? '0x' + obj.toString(16).toUpperCase() : '-0x' + obj.toString(16).toUpperCase().slice(1); } + }, + defaultStyle: 'decimal', + styleAliases: { + binary: [ 2, 'bin' ], + octal: [ 8, 'oct' ], + decimal: [ 10, 'dec' ], + hexadecimal: [ 16, 'hex' ] } +}); - // https://github.com/isaacs/node-graceful-fs/issues/4 - // Chown should not fail on einval or eperm if non-root. - // It should not fail on enosys ever, as this just indicates - // that a fs doesn't support the intended operation. - fs.chown = chownFix(fs.chown) - fs.fchown = chownFix(fs.fchown) - fs.lchown = chownFix(fs.lchown) +/***/ }), - fs.chmod = chmodFix(fs.chmod) - fs.fchmod = chmodFix(fs.fchmod) - fs.lchmod = chmodFix(fs.lchmod) +/***/ 27278: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - fs.chownSync = chownFixSync(fs.chownSync) - fs.fchownSync = chownFixSync(fs.fchownSync) - fs.lchownSync = chownFixSync(fs.lchownSync) +"use strict"; - fs.chmodSync = chmodFixSync(fs.chmodSync) - fs.fchmodSync = chmodFixSync(fs.fchmodSync) - fs.lchmodSync = chmodFixSync(fs.lchmodSync) - fs.stat = statFix(fs.stat) - fs.fstat = statFix(fs.fstat) - fs.lstat = statFix(fs.lstat) +var esprima; - fs.statSync = statFixSync(fs.statSync) - fs.fstatSync = statFixSync(fs.fstatSync) - fs.lstatSync = statFixSync(fs.lstatSync) +// Browserified version does not have esprima +// +// 1. For node.js just require module as deps +// 2. For browser try to require mudule via external AMD system. +// If not found - try to fallback to window.esprima. If not +// found too - then fail to parse. +// +try { + // workaround to exclude package from browserify list. + var _require = require; + esprima = _require('esprima'); +} catch (_) { + /* eslint-disable no-redeclare */ + /* global window */ + if (typeof window !== 'undefined') esprima = window.esprima; +} - // if lchmod/lchown do not exist, then make them no-ops - if (!fs.lchmod) { - fs.lchmod = function (path, mode, cb) { - if (cb) process.nextTick(cb) - } - fs.lchmodSync = function () {} - } - if (!fs.lchown) { - fs.lchown = function (path, uid, gid, cb) { - if (cb) process.nextTick(cb) - } - fs.lchownSync = function () {} - } +var Type = __nccwpck_require__(30967); - // on Windows, A/V software can lock the directory, causing this - // to fail with an EACCES or EPERM if the directory contains newly - // created files. Try again on failure, for up to 60 seconds. +function resolveJavascriptFunction(data) { + if (data === null) return false; - // Set the timeout this long because some Windows Anti-Virus, such as Parity - // bit9, may lock files for up to a minute, causing npm package install - // failures. Also, take care to yield the scheduler. Windows scheduling gives - // CPU to a busy looping process, which can cause the program causing the lock - // contention to be starved of CPU by node, so the contention doesn't resolve. - if (platform === "win32") { - fs.rename = (function (fs$rename) { return function (from, to, cb) { - var start = Date.now() - var backoff = 0; - fs$rename(from, to, function CB (er) { - if (er - && (er.code === "EACCES" || er.code === "EPERM") - && Date.now() - start < 60000) { - setTimeout(function() { - fs.stat(to, function (stater, st) { - if (stater && stater.code === "ENOENT") - fs$rename(from, to, CB); - else - cb(er) - }) - }, backoff) - if (backoff < 100) - backoff += 10; - return; - } - if (cb) cb(er) - }) - }})(fs.rename) - } + try { + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }); - // if read() returns EAGAIN, then just try it again. - fs.read = (function (fs$read) { return function (fd, buffer, offset, length, position, callback_) { - var callback - if (callback_ && typeof callback_ === 'function') { - var eagCounter = 0 - callback = function (er, _, __) { - if (er && er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - } - callback_.apply(this, arguments) - } + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + return false; } - return fs$read.call(fs, fd, buffer, offset, length, position, callback) - }})(fs.read) - fs.readSync = (function (fs$readSync) { return function (fd, buffer, offset, length, position) { - var eagCounter = 0 - while (true) { - try { - return fs$readSync.call(fs, fd, buffer, offset, length, position) - } catch (er) { - if (er.code === 'EAGAIN' && eagCounter < 10) { - eagCounter ++ - continue - } - throw er - } - } - }})(fs.readSync) + return true; + } catch (err) { + return false; + } +} - function patchLchmod (fs) { - fs.lchmod = function (path, mode, callback) { - fs.open( path - , constants.O_WRONLY | constants.O_SYMLINK - , mode - , function (err, fd) { - if (err) { - if (callback) callback(err) - return - } - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - fs.fchmod(fd, mode, function (err) { - fs.close(fd, function(err2) { - if (callback) callback(err || err2) - }) - }) - }) - } +function constructJavascriptFunction(data) { + /*jslint evil:true*/ - fs.lchmodSync = function (path, mode) { - var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + var source = '(' + data + ')', + ast = esprima.parse(source, { range: true }), + params = [], + body; - // prefer to return the chmod error, if one occurs, - // but still try to close, and report closing errors if they occur. - var threw = true - var ret - try { - ret = fs.fchmodSync(fd, mode) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } + if (ast.type !== 'Program' || + ast.body.length !== 1 || + ast.body[0].type !== 'ExpressionStatement' || + (ast.body[0].expression.type !== 'ArrowFunctionExpression' && + ast.body[0].expression.type !== 'FunctionExpression')) { + throw new Error('Failed to resolve function'); } - function patchLutimes (fs) { - if (constants.hasOwnProperty("O_SYMLINK")) { - fs.lutimes = function (path, at, mt, cb) { - fs.open(path, constants.O_SYMLINK, function (er, fd) { - if (er) { - if (cb) cb(er) - return - } - fs.futimes(fd, at, mt, function (er) { - fs.close(fd, function (er2) { - if (cb) cb(er || er2) - }) - }) - }) - } + ast.body[0].expression.params.forEach(function (param) { + params.push(param.name); + }); - fs.lutimesSync = function (path, at, mt) { - var fd = fs.openSync(path, constants.O_SYMLINK) - var ret - var threw = true - try { - ret = fs.futimesSync(fd, at, mt) - threw = false - } finally { - if (threw) { - try { - fs.closeSync(fd) - } catch (er) {} - } else { - fs.closeSync(fd) - } - } - return ret - } + body = ast.body[0].expression.body.range; - } else { - fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } - fs.lutimesSync = function () {} - } + // Esprima's ranges include the first '{' and the last '}' characters on + // function expressions. So cut them out. + if (ast.body[0].expression.body.type === 'BlockStatement') { + /*eslint-disable no-new-func*/ + return new Function(params, source.slice(body[0] + 1, body[1] - 1)); } + // ES6 arrow functions can omit the BlockStatement. In that case, just return + // the body. + /*eslint-disable no-new-func*/ + return new Function(params, 'return ' + source.slice(body[0], body[1])); +} - function chmodFix (orig) { - if (!orig) return orig - return function (target, mode, cb) { - return orig.call(fs, target, mode, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } +function representJavascriptFunction(object /*, style*/) { + return object.toString(); +} - function chmodFixSync (orig) { - if (!orig) return orig - return function (target, mode) { - try { - return orig.call(fs, target, mode) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } +function isFunction(object) { + return Object.prototype.toString.call(object) === '[object Function]'; +} +module.exports = new Type('tag:yaml.org,2002:js/function', { + kind: 'scalar', + resolve: resolveJavascriptFunction, + construct: constructJavascriptFunction, + predicate: isFunction, + represent: representJavascriptFunction +}); - function chownFix (orig) { - if (!orig) return orig - return function (target, uid, gid, cb) { - return orig.call(fs, target, uid, gid, function (er) { - if (chownErOk(er)) er = null - if (cb) cb.apply(this, arguments) - }) - } - } - function chownFixSync (orig) { - if (!orig) return orig - return function (target, uid, gid) { - try { - return orig.call(fs, target, uid, gid) - } catch (er) { - if (!chownErOk(er)) throw er - } - } - } +/***/ }), +/***/ 69242: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - function statFix (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target, cb) { - return orig.call(fs, target, function (er, stats) { - if (!stats) return cb.apply(this, arguments) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - if (cb) cb.apply(this, arguments) - }) - } +"use strict"; + + +var Type = __nccwpck_require__(30967); + +function resolveJavascriptRegExp(data) { + if (data === null) return false; + if (data.length === 0) return false; + + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // if regexp starts with '/' it can have modifiers and must be properly closed + // `/foo/gim` - modifiers tail can be maximum 3 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + + if (modifiers.length > 3) return false; + // if expression starts with /, is should be properly terminated + if (regexp[regexp.length - modifiers.length - 1] !== '/') return false; } - function statFixSync (orig) { - if (!orig) return orig - // Older versions of Node erroneously returned signed integers for - // uid + gid. - return function (target) { - var stats = orig.call(fs, target) - if (stats.uid < 0) stats.uid += 0x100000000 - if (stats.gid < 0) stats.gid += 0x100000000 - return stats; - } + return true; +} + +function constructJavascriptRegExp(data) { + var regexp = data, + tail = /\/([gim]*)$/.exec(data), + modifiers = ''; + + // `/foo/gim` - tail can be maximum 4 chars + if (regexp[0] === '/') { + if (tail) modifiers = tail[1]; + regexp = regexp.slice(1, regexp.length - modifiers.length - 1); } - // ENOSYS means that the fs doesn't support the op. Just ignore - // that, because it doesn't matter. - // - // if there's no getuid, or if getuid() is something other - // than 0, and the error is EINVAL or EPERM, then just ignore - // it. - // - // This specific case is a silent failure in cp, install, tar, - // and most other unix tools that manage permissions. - // - // When running as root, or if other types of errors are - // encountered, then it's strict. - function chownErOk (er) { - if (!er) - return true + return new RegExp(regexp, modifiers); +} - if (er.code === "ENOSYS") - return true +function representJavascriptRegExp(object /*, style*/) { + var result = '/' + object.source + '/'; - var nonroot = !process.getuid || process.getuid() !== 0 - if (nonroot) { - if (er.code === "EINVAL" || er.code === "EPERM") - return true - } + if (object.global) result += 'g'; + if (object.multiline) result += 'm'; + if (object.ignoreCase) result += 'i'; - return false - } + return result; +} + +function isRegExp(object) { + return Object.prototype.toString.call(object) === '[object RegExp]'; } +module.exports = new Type('tag:yaml.org,2002:js/regexp', { + kind: 'scalar', + resolve: resolveJavascriptRegExp, + construct: constructJavascriptRegExp, + predicate: isRegExp, + represent: representJavascriptRegExp +}); + /***/ }), -/***/ 81680: +/***/ 25914: /***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { "use strict"; -const errorEx = __nccwpck_require__(23505); -const fallback = __nccwpck_require__(55586); -const JSONError = errorEx('JSONError', { - fileName: errorEx.append('in %s') -}); +var Type = __nccwpck_require__(30967); -module.exports = (input, reviver, filename) => { - if (typeof reviver === 'string') { - filename = reviver; - reviver = null; - } +function resolveJavascriptUndefined() { + return true; +} - try { - try { - return JSON.parse(input, reviver); - } catch (err) { - fallback(input, reviver); +function constructJavascriptUndefined() { + /*eslint-disable no-undefined*/ + return undefined; +} - throw err; - } - } catch (err) { - err.message = err.message.replace(/\n/g, ''); +function representJavascriptUndefined() { + return ''; +} - const jsonErr = new JSONError(err); - if (filename) { - jsonErr.fileName = filename; - } +function isUndefined(object) { + return typeof object === 'undefined'; +} - throw jsonErr; - } -}; +module.exports = new Type('tag:yaml.org,2002:js/undefined', { + kind: 'scalar', + resolve: resolveJavascriptUndefined, + construct: constructJavascriptUndefined, + predicate: isUndefined, + represent: representJavascriptUndefined +}); /***/ }), -/***/ 11289: -/***/ ((module) => { +/***/ 31173: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ +"use strict"; -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; +var Type = __nccwpck_require__(30967); -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; +module.exports = new Type('tag:yaml.org,2002:map', { + kind: 'mapping', + construct: function (data) { return data !== null ? data : {}; } +}); -/** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ -function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); - } - return func.apply(thisArg, args); -} -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); +/***/ }), - while (++index < n) { - result[index] = iteratee(index); - } - return result; +/***/ 81393: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Type = __nccwpck_require__(30967); + +function resolveYamlMerge(data) { + return data === '<<' || data === null; } -/** Used for built-in method references. */ -var objectProto = Object.prototype; +module.exports = new Type('tag:yaml.org,2002:merge', { + kind: 'scalar', + resolve: resolveYamlMerge +}); -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +/***/ }), -/** Built-in value references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable; +/***/ 22671: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeMax = Math.max; +"use strict"; -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; - var length = result.length, - skipIndexes = !!length; +var Type = __nccwpck_require__(30967); - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } - } - return result; +function resolveYamlNull(data) { + if (data === null) return true; + + var max = data.length; + + return (max === 1 && data === '~') || + (max === 4 && (data === 'null' || data === 'Null' || data === 'NULL')); } -/** - * Used by `_.defaults` to customize its `_.assignIn` use. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. - */ -function assignInDefaults(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; - } - return objValue; +function constructYamlNull() { + return null; } -/** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ -function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - object[key] = value; - } +function isNull(object) { + return object === null; } -/** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; +module.exports = new Type('tag:yaml.org,2002:null', { + kind: 'scalar', + resolve: resolveYamlNull, + construct: constructYamlNull, + predicate: isNull, + represent: { + canonical: function () { return '~'; }, + lowercase: function () { return 'null'; }, + uppercase: function () { return 'NULL'; }, + camelcase: function () { return 'Null'; } + }, + defaultStyle: 'lowercase' +}); - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; -} -/** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ -function baseRest(func, start) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); +/***/ }), - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = array; - return apply(func, this, otherArgs); - }; -} +/***/ 96668: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ -function copyObject(source, props, object, customizer) { - object || (object = {}); +"use strict"; - var index = -1, - length = props.length; - while (++index < length) { - var key = props[index]; +var Type = __nccwpck_require__(30967); - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; +var _hasOwnProperty = Object.prototype.hasOwnProperty; +var _toString = Object.prototype.toString; - assignValue(object, key, newValue === undefined ? source[key] : newValue); - } - return object; -} +function resolveYamlOmap(data) { + if (data === null) return true; -/** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ -function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; + var objectKeys = [], index, length, pair, pairKey, pairHasKey, + object = data; - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + pairHasKey = false; - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); + if (_toString.call(pair) !== '[object Object]') return false; + + for (pairKey in pair) { + if (_hasOwnProperty.call(pair, pairKey)) { + if (!pairHasKey) pairHasKey = true; + else return false; } } - return object; - }); -} -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); -} + if (!pairHasKey) return false; -/** - * Checks if the given arguments are from an iteratee call. - * - * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. - */ -function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); + if (objectKeys.indexOf(pairKey) === -1) objectKeys.push(pairKey); + else return false; } - return false; -} -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; + return true; } -/** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; +function constructYamlOmap(data) { + return data !== null ? data : []; } -/** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false - * - * _.eq(NaN, NaN); - * // => true - */ -function eq(value, other) { - return value === other || (value !== value && other !== other); -} +module.exports = new Type('tag:yaml.org,2002:omap', { + kind: 'sequence', + resolve: resolveYamlOmap, + construct: constructYamlOmap +}); -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; +/***/ }), -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} +/***/ 76039: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); -} +"use strict"; -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} +var Type = __nccwpck_require__(30967); -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); +var _toString = Object.prototype.toString; + +function resolveYamlPairs(data) { + if (data === null) return true; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + if (_toString.call(pair) !== '[object Object]') return false; + + keys = Object.keys(pair); + + if (keys.length !== 1) return false; + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return true; } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +function constructYamlPairs(data) { + if (data === null) return []; + + var index, length, pair, keys, result, + object = data; + + result = new Array(object.length); + + for (index = 0, length = object.length; index < length; index += 1) { + pair = object[index]; + + keys = Object.keys(pair); + + result[index] = [ keys[0], pair[keys[0]] ]; + } + + return result; } -/** - * This method is like `_.assignIn` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @alias extendWith - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignWith - * @example - * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); - * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ -var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); +module.exports = new Type('tag:yaml.org,2002:pairs', { + kind: 'sequence', + resolve: resolveYamlPairs, + construct: constructYamlPairs }); -/** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep - * @example - * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ -var defaults = baseRest(function(args) { - args.push(undefined, assignInDefaults); - return apply(assignInWith, undefined, args); + +/***/ }), + +/***/ 5490: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Type = __nccwpck_require__(30967); + +module.exports = new Type('tag:yaml.org,2002:seq', { + kind: 'sequence', + construct: function (data) { return data !== null ? data : []; } }); -/** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) - */ -function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + +/***/ }), + +/***/ 69237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +"use strict"; + + +var Type = __nccwpck_require__(30967); + +var _hasOwnProperty = Object.prototype.hasOwnProperty; + +function resolveYamlSet(data) { + if (data === null) return true; + + var key, object = data; + + for (key in object) { + if (_hasOwnProperty.call(object, key)) { + if (object[key] !== null) return false; + } + } + + return true; } -module.exports = defaults; +function constructYamlSet(data) { + return data !== null ? data : {}; +} + +module.exports = new Type('tag:yaml.org,2002:set', { + kind: 'mapping', + resolve: resolveYamlSet, + construct: constructYamlSet +}); /***/ }), -/***/ 48919: -/***/ ((module) => { +/***/ 93955: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ +"use strict"; -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]'; +var Type = __nccwpck_require__(30967); -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; +module.exports = new Type('tag:yaml.org,2002:str', { + kind: 'scalar', + construct: function (data) { return data !== null ? data : ''; } +}); -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); +/***/ }), -/** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ -function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; +/***/ 83714: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - while (++index < length) { - array[offset + index] = values[index]; - } - return array; +"use strict"; + + +var Type = __nccwpck_require__(30967); + +var YAML_DATE_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9])' + // [2] month + '-([0-9][0-9])$'); // [3] day + +var YAML_TIMESTAMP_REGEXP = new RegExp( + '^([0-9][0-9][0-9][0-9])' + // [1] year + '-([0-9][0-9]?)' + // [2] month + '-([0-9][0-9]?)' + // [3] day + '(?:[Tt]|[ \\t]+)' + // ... + '([0-9][0-9]?)' + // [4] hour + ':([0-9][0-9])' + // [5] minute + ':([0-9][0-9])' + // [6] second + '(?:\\.([0-9]*))?' + // [7] fraction + '(?:[ \\t]*(Z|([-+])([0-9][0-9]?)' + // [8] tz [9] tz_sign [10] tz_hour + '(?::([0-9][0-9]))?))?$'); // [11] tz_minute + +function resolveYamlTimestamp(data) { + if (data === null) return false; + if (YAML_DATE_REGEXP.exec(data) !== null) return true; + if (YAML_TIMESTAMP_REGEXP.exec(data) !== null) return true; + return false; } -/** Used for built-in method references. */ -var objectProto = Object.prototype; +function constructYamlTimestamp(data) { + var match, year, month, day, hour, minute, second, fraction = 0, + delta = null, tz_hour, tz_minute, date; -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; + match = YAML_DATE_REGEXP.exec(data); + if (match === null) match = YAML_TIMESTAMP_REGEXP.exec(data); -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + if (match === null) throw new Error('Date resolve error'); -/** Built-in value references. */ -var Symbol = root.Symbol, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; + // match: [1] year [2] month [3] day -/** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ -function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; + year = +(match[1]); + month = +(match[2]) - 1; // JS month starts with 0 + day = +(match[3]); - predicate || (predicate = isFlattenable); - result || (result = []); + if (!match[4]) { // no hour + return new Date(Date.UTC(year, month, day)); + } - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; + // match: [4] hour [5] minute [6] second [7] fraction + + hour = +(match[4]); + minute = +(match[5]); + second = +(match[6]); + + if (match[7]) { + fraction = match[7].slice(0, 3); + while (fraction.length < 3) { // milli-seconds + fraction += '0'; } + fraction = +fraction; } - return result; -} -/** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ -function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); -} + // match: [8] tz [9] tz_sign [10] tz_hour [11] tz_minute -/** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example - * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] - */ -function flatten(array) { - var length = array ? array.length : 0; - return length ? baseFlatten(array, 1) : []; -} + if (match[9]) { + tz_hour = +(match[10]); + tz_minute = +(match[11] || 0); + delta = (tz_hour * 60 + tz_minute) * 60000; // delta in mili-seconds + if (match[9] === '-') delta = -delta; + } -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); -} + date = new Date(Date.UTC(year, month, day, hour, minute, second, fraction)); -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; + if (delta) date.setTime(date.getTime() - delta); -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); + return date; } -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); +function representYamlTimestamp(object /*, style*/) { + return object.toISOString(); } -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} +module.exports = new Type('tag:yaml.org,2002:timestamp', { + kind: 'scalar', + resolve: resolveYamlTimestamp, + construct: constructYamlTimestamp, + instanceOf: Date, + represent: representYamlTimestamp +}); -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + +/***/ }), + +/***/ 55586: +/***/ ((module) => { + +"use strict"; + + +module.exports = parseJson +function parseJson (txt, reviver, context) { + context = context || 20 + try { + return JSON.parse(txt, reviver) + } catch (e) { + if (typeof txt !== 'string') { + const isEmptyArray = Array.isArray(txt) && txt.length === 0 + const errorMessage = 'Cannot parse ' + + (isEmptyArray ? 'an empty array' : String(txt)) + throw new TypeError(errorMessage) + } + const syntaxErr = e.message.match(/^Unexpected token.*position\s+(\d+)/i) + const errIdx = syntaxErr + ? +syntaxErr[1] + : e.message.match(/^Unexpected end of JSON.*/i) + ? txt.length - 1 + : null + if (errIdx != null) { + const start = errIdx <= context + ? 0 + : errIdx - context + const end = errIdx + context >= txt.length + ? txt.length + : errIdx + context + e.message += ` while parsing near '${ + start === 0 ? '' : '...' + }${txt.slice(start, end)}${ + end === txt.length ? '' : '...' + }'` + } else { + e.message += ` while parsing '${txt.slice(0, context * 2)}'` + } + throw e + } } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} +/***/ }), + +/***/ 53359: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var jws = __nccwpck_require__(4636); + +module.exports = function (jwt, options) { + options = options || {}; + var decoded = jws.decode(jwt, options); + if (!decoded) { return null; } + var payload = decoded.payload; + + //try parse the payload + if(typeof payload === 'string') { + try { + var obj = JSON.parse(payload); + if(obj !== null && typeof obj === 'object') { + payload = obj; + } + } catch (e) { } + } + + //return header if `complete` option is enabled. header includes claims + //such as `kid` and `alg` used to select the key within a JWKS needed to + //verify the signature + if (options.complete === true) { + return { + header: decoded.header, + payload: payload, + signature: decoded.signature + }; + } + return payload; +}; + + +/***/ }), -module.exports = flatten; +/***/ 77486: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = { + decode: __nccwpck_require__(53359), + verify: __nccwpck_require__(12327), + sign: __nccwpck_require__(82022), + JsonWebTokenError: __nccwpck_require__(405), + NotBeforeError: __nccwpck_require__(4383), + TokenExpiredError: __nccwpck_require__(46637), +}; /***/ }), -/***/ 17931: +/***/ 405: /***/ ((module) => { -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ +var JsonWebTokenError = function (message, error) { + Error.call(this, message); + if(Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = 'JsonWebTokenError'; + this.message = message; + if (error) this.inner = error; +}; -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; +JsonWebTokenError.prototype = Object.create(Error.prototype); +JsonWebTokenError.prototype.constructor = JsonWebTokenError; -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - stringTag = '[object String]', - symbolTag = '[object Symbol]'; +module.exports = JsonWebTokenError; -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; +/***/ }), -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; +/***/ 4383: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; +var JsonWebTokenError = __nccwpck_require__(405); -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; +var NotBeforeError = function (message, date) { + JsonWebTokenError.call(this, message); + this.name = 'NotBeforeError'; + this.date = date; +}; -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; +NotBeforeError.prototype = Object.create(JsonWebTokenError.prototype); -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array ? array.length : 0, - result = Array(length); +NotBeforeError.prototype.constructor = NotBeforeError; - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} +module.exports = NotBeforeError; -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); +/***/ }), - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; -} +/***/ 46637: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - if (value !== value) { - return baseFindIndex(array, baseIsNaN, fromIndex); - } - var index = fromIndex - 1, - length = array.length; +var JsonWebTokenError = __nccwpck_require__(405); - while (++index < length) { - if (array[index] === value) { - return index; +var TokenExpiredError = function (message, expiredAt) { + JsonWebTokenError.call(this, message); + this.name = 'TokenExpiredError'; + this.expiredAt = expiredAt; +}; + +TokenExpiredError.prototype = Object.create(JsonWebTokenError.prototype); + +TokenExpiredError.prototype.constructor = TokenExpiredError; + +module.exports = TokenExpiredError; + +/***/ }), + +/***/ 59085: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var semver = __nccwpck_require__(27174); + +module.exports = semver.satisfies(process.version, '^6.12.0 || >=8.0.0'); + + +/***/ }), + +/***/ 46098: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var ms = __nccwpck_require__(80900); + +module.exports = function (time, iat) { + var timestamp = iat || Math.floor(Date.now() / 1000); + + if (typeof time === 'string') { + var milliseconds = ms(time); + if (typeof milliseconds === 'undefined') { + return; } + return Math.floor(timestamp + milliseconds / 1000); + } else if (typeof time === 'number') { + return timestamp + time; + } else { + return; } - return -1; -} -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; -} +}; -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); +/***/ }), - while (++index < n) { - result[index] = iteratee(index); +/***/ 27174: +/***/ ((module, exports) => { + +exports = module.exports = SemVer + +var debug +/* istanbul ignore next */ +if (typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG)) { + debug = function () { + var args = Array.prototype.slice.call(arguments, 0) + args.unshift('SEMVER') + console.log.apply(console, args) } - return result; +} else { + debug = function () {} } -/** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ -function baseValues(object, props) { - return arrayMap(props, function(key) { - return object[key]; - }); -} +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +exports.SEMVER_SPEC_VERSION = '2.0.0' -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; -} +var MAX_LENGTH = 256 +var MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || + /* istanbul ignore next */ 9007199254740991 -/** Used for built-in method references. */ -var objectProto = Object.prototype; +// Max safe segment length for coercion. +var MAX_SAFE_COMPONENT_LENGTH = 16 -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; +// The actual regexps go on exports.re +var re = exports.re = [] +var src = exports.src = [] +var R = 0 -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. -/** Built-in value references. */ -var propertyIsEnumerable = objectProto.propertyIsEnumerable; +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys = overArg(Object.keys, Object), - nativeMax = Math.max; +var NUMERICIDENTIFIER = R++ +src[NUMERICIDENTIFIER] = '0|[1-9]\\d*' +var NUMERICIDENTIFIERLOOSE = R++ +src[NUMERICIDENTIFIERLOOSE] = '[0-9]+' + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +var NONNUMERICIDENTIFIER = R++ +src[NONNUMERICIDENTIFIER] = '\\d*[a-zA-Z-][a-zA-Z0-9-]*' + +// ## Main Version +// Three dot-separated numeric identifiers. + +var MAINVERSION = R++ +src[MAINVERSION] = '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')\\.' + + '(' + src[NUMERICIDENTIFIER] + ')' + +var MAINVERSIONLOOSE = R++ +src[MAINVERSIONLOOSE] = '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')\\.' + + '(' + src[NUMERICIDENTIFIERLOOSE] + ')' + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. + +var PRERELEASEIDENTIFIER = R++ +src[PRERELEASEIDENTIFIER] = '(?:' + src[NUMERICIDENTIFIER] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +var PRERELEASEIDENTIFIERLOOSE = R++ +src[PRERELEASEIDENTIFIERLOOSE] = '(?:' + src[NUMERICIDENTIFIERLOOSE] + + '|' + src[NONNUMERICIDENTIFIER] + ')' + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +var PRERELEASE = R++ +src[PRERELEASE] = '(?:-(' + src[PRERELEASEIDENTIFIER] + + '(?:\\.' + src[PRERELEASEIDENTIFIER] + ')*))' + +var PRERELEASELOOSE = R++ +src[PRERELEASELOOSE] = '(?:-?(' + src[PRERELEASEIDENTIFIERLOOSE] + + '(?:\\.' + src[PRERELEASEIDENTIFIERLOOSE] + ')*))' + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +var BUILDIDENTIFIER = R++ +src[BUILDIDENTIFIER] = '[0-9A-Za-z-]+' + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +var BUILD = R++ +src[BUILD] = '(?:\\+(' + src[BUILDIDENTIFIER] + + '(?:\\.' + src[BUILDIDENTIFIER] + ')*))' + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +var FULL = R++ +var FULLPLAIN = 'v?' + src[MAINVERSION] + + src[PRERELEASE] + '?' + + src[BUILD] + '?' + +src[FULL] = '^' + FULLPLAIN + '$' + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +var LOOSEPLAIN = '[v=\\s]*' + src[MAINVERSIONLOOSE] + + src[PRERELEASELOOSE] + '?' + + src[BUILD] + '?' + +var LOOSE = R++ +src[LOOSE] = '^' + LOOSEPLAIN + '$' + +var GTLT = R++ +src[GTLT] = '((?:<|>)?=?)' + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +var XRANGEIDENTIFIERLOOSE = R++ +src[XRANGEIDENTIFIERLOOSE] = src[NUMERICIDENTIFIERLOOSE] + '|x|X|\\*' +var XRANGEIDENTIFIER = R++ +src[XRANGEIDENTIFIER] = src[NUMERICIDENTIFIER] + '|x|X|\\*' + +var XRANGEPLAIN = R++ +src[XRANGEPLAIN] = '[v=\\s]*(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIER] + ')' + + '(?:' + src[PRERELEASE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGEPLAINLOOSE = R++ +src[XRANGEPLAINLOOSE] = '[v=\\s]*(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:\\.(' + src[XRANGEIDENTIFIERLOOSE] + ')' + + '(?:' + src[PRERELEASELOOSE] + ')?' + + src[BUILD] + '?' + + ')?)?' + +var XRANGE = R++ +src[XRANGE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAIN] + '$' +var XRANGELOOSE = R++ +src[XRANGELOOSE] = '^' + src[GTLT] + '\\s*' + src[XRANGEPLAINLOOSE] + '$' + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +var COERCE = R++ +src[COERCE] = '(?:^|[^\\d])' + + '(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '})' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:\\.(\\d{1,' + MAX_SAFE_COMPONENT_LENGTH + '}))?' + + '(?:$|[^\\d])' + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +var LONETILDE = R++ +src[LONETILDE] = '(?:~>?)' + +var TILDETRIM = R++ +src[TILDETRIM] = '(\\s*)' + src[LONETILDE] + '\\s+' +re[TILDETRIM] = new RegExp(src[TILDETRIM], 'g') +var tildeTrimReplace = '$1~' + +var TILDE = R++ +src[TILDE] = '^' + src[LONETILDE] + src[XRANGEPLAIN] + '$' +var TILDELOOSE = R++ +src[TILDELOOSE] = '^' + src[LONETILDE] + src[XRANGEPLAINLOOSE] + '$' + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +var LONECARET = R++ +src[LONECARET] = '(?:\\^)' + +var CARETTRIM = R++ +src[CARETTRIM] = '(\\s*)' + src[LONECARET] + '\\s+' +re[CARETTRIM] = new RegExp(src[CARETTRIM], 'g') +var caretTrimReplace = '$1^' + +var CARET = R++ +src[CARET] = '^' + src[LONECARET] + src[XRANGEPLAIN] + '$' +var CARETLOOSE = R++ +src[CARETLOOSE] = '^' + src[LONECARET] + src[XRANGEPLAINLOOSE] + '$' + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +var COMPARATORLOOSE = R++ +src[COMPARATORLOOSE] = '^' + src[GTLT] + '\\s*(' + LOOSEPLAIN + ')$|^$' +var COMPARATOR = R++ +src[COMPARATOR] = '^' + src[GTLT] + '\\s*(' + FULLPLAIN + ')$|^$' + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +var COMPARATORTRIM = R++ +src[COMPARATORTRIM] = '(\\s*)' + src[GTLT] + + '\\s*(' + LOOSEPLAIN + '|' + src[XRANGEPLAIN] + ')' + +// this one has to use the /g flag +re[COMPARATORTRIM] = new RegExp(src[COMPARATORTRIM], 'g') +var comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +var HYPHENRANGE = R++ +src[HYPHENRANGE] = '^\\s*(' + src[XRANGEPLAIN] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAIN] + ')' + + '\\s*$' -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - // Safari 9 makes `arguments.length` enumerable in strict mode. - var result = (isArray(value) || isArguments(value)) - ? baseTimes(value.length, String) - : []; +var HYPHENRANGELOOSE = R++ +src[HYPHENRANGELOOSE] = '^\\s*(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s+-\\s+' + + '(' + src[XRANGEPLAINLOOSE] + ')' + + '\\s*$' - var length = result.length, - skipIndexes = !!length; +// Star ranges basically just allow anything at all. +var STAR = R++ +src[STAR] = '(<|>)?=?\\s*\\*' - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && (key == 'length' || isIndex(key, length)))) { - result.push(key); - } +// Compile to actual regexp objects. +// All are flag-free, unless they were created above with a flag. +for (var i = 0; i < R; i++) { + debug(i, src[i]) + if (!re[i]) { + re[i] = new RegExp(src[i]) } - return result; } -/** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); +exports.parse = parse +function parse (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false } } - return result; -} - -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); -} -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + if (version instanceof SemVer) { + return version + } - return value === proto; -} + if (typeof version !== 'string') { + return null + } -/** - * Checks if `value` is in `collection`. If `collection` is a string, it's - * checked for a substring of `value`, otherwise - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * is used for equality comparisons. If `fromIndex` is negative, it's used as - * the offset from the end of `collection`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {boolean} Returns `true` if `value` is found, else `false`. - * @example - * - * _.includes([1, 2, 3], 1); - * // => true - * - * _.includes([1, 2, 3], 1, 2); - * // => false - * - * _.includes({ 'a': 1, 'b': 2 }, 1); - * // => true - * - * _.includes('abcd', 'bc'); - * // => true - */ -function includes(collection, value, fromIndex, guard) { - collection = isArrayLike(collection) ? collection : values(collection); - fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + if (version.length > MAX_LENGTH) { + return null + } - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); + var r = options.loose ? re[LOOSE] : re[FULL] + if (!r.test(version)) { + return null } - return isString(collection) - ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) - : (!!length && baseIndexOf(collection, value, fromIndex) > -1); -} -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -function isArguments(value) { - // Safari 8.1 makes `arguments.callee` enumerable in strict mode. - return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && - (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); + try { + return new SemVer(version, options) + } catch (er) { + return null + } } -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; - -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); +exports.valid = valid +function valid (version, options) { + var v = parse(version, options) + return v ? v.version : null } -/** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false - * - * _.isArrayLikeObject(_.noop); - * // => false - */ -function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); +exports.clean = clean +function clean (version, options) { + var s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null } -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 8-9 which returns 'object' for typed array and other constructors. - var tag = isObject(value) ? objectToString.call(value) : ''; - return tag == funcTag || tag == genTag; -} +exports.SemVer = SemVer -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} +function SemVer (version, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (version instanceof SemVer) { + if (version.loose === options.loose) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError('Invalid Version: ' + version) + } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); -} + if (version.length > MAX_LENGTH) { + throw new TypeError('version is longer than ' + MAX_LENGTH + ' characters') + } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} + if (!(this instanceof SemVer)) { + return new SemVer(version, options) + } -/** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ -function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); -} + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); -} + var m = version.trim().match(options.loose ? re[LOOSE] : re[FULL]) -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ -function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; + if (!m) { + throw new TypeError('Invalid Version: ' + version) } - return value === value ? value : 0; -} -/** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ -function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; + this.raw = version - return result === result ? (remainder ? result - remainder : result) : 0; -} + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ -function toNumber(value) { - if (typeof value == 'number') { - return value; + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') } - if (isSymbol(value)) { - return NAN; + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map(function (id) { + if (/^[0-9]+$/.test(id)) { + var num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) } - if (typeof value != 'string') { - return value === 0 ? value : +value; + + this.build = m[5] ? m[5].split('.') : [] + this.format() +} + +SemVer.prototype.format = function () { + this.version = this.major + '.' + this.minor + '.' + this.patch + if (this.prerelease.length) { + this.version += '-' + this.prerelease.join('.') } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); + return this.version } -/** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ -function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +SemVer.prototype.toString = function () { + return this.version } -/** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) - * - * _.values('hi'); - * // => ['h', 'i'] - */ -function values(object) { - return object ? baseValues(object, keys(object)) : []; +SemVer.prototype.compare = function (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + return this.compareMain(other) || this.comparePre(other) } -module.exports = includes; +SemVer.prototype.compareMain = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + return compareIdentifiers(this.major, other.major) || + compareIdentifiers(this.minor, other.minor) || + compareIdentifiers(this.patch, other.patch) +} -/***/ }), +SemVer.prototype.comparePre = function (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } -/***/ 16501: -/***/ ((module) => { + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } -/** - * lodash 3.0.3 (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright 2012-2016 The Dojo Foundation - * Based on Underscore.js 1.8.3 - * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ + var i = 0 + do { + var a = this.prerelease[i] + var b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) +} -/** `Object#toString` result references. */ -var boolTag = '[object Boolean]'; +// preminor will bump the version up to the next minor release, and immediately +// down to pre-release. premajor and prepatch work the same way. +SemVer.prototype.inc = function (release, identifier) { + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier) + this.inc('pre', identifier) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier) + } + this.inc('pre', identifier) + break -/** Used for built-in method references. */ -var objectProto = Object.prototype; + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if (this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 "pre" would become 1.0.0-0 which is the wrong direction. + case 'pre': + if (this.prerelease.length === 0) { + this.prerelease = [0] + } else { + var i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + this.prerelease.push(0) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + if (this.prerelease[0] === identifier) { + if (isNaN(this.prerelease[1])) { + this.prerelease = [identifier, 0] + } + } else { + this.prerelease = [identifier, 0] + } + } + break -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + default: + throw new Error('invalid increment argument: ' + release) + } + this.format() + this.raw = this.version + return this +} -/** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isBoolean(false); - * // => true - * - * _.isBoolean(null); - * // => false - */ -function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && objectToString.call(value) == boolTag); +exports.inc = inc +function inc (version, release, loose, identifier) { + if (typeof (loose) === 'string') { + identifier = loose + loose = undefined + } + + try { + return new SemVer(version, loose).inc(release, identifier).version + } catch (er) { + return null + } } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +exports.diff = diff +function diff (version1, version2) { + if (eq(version1, version2)) { + return null + } else { + var v1 = parse(version1) + var v2 = parse(version2) + var prefix = '' + if (v1.prerelease.length || v2.prerelease.length) { + prefix = 'pre' + var defaultResult = 'prerelease' + } + for (var key in v1) { + if (key === 'major' || key === 'minor' || key === 'patch') { + if (v1[key] !== v2[key]) { + return prefix + key + } + } + } + return defaultResult // may be undefined + } } -module.exports = isBoolean; +exports.compareIdentifiers = compareIdentifiers +var numeric = /^[0-9]+$/ +function compareIdentifiers (a, b) { + var anum = numeric.test(a) + var bnum = numeric.test(b) -/***/ }), + if (anum && bnum) { + a = +a + b = +b + } -/***/ 21441: -/***/ ((module) => { + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ +exports.rcompareIdentifiers = rcompareIdentifiers +function rcompareIdentifiers (a, b) { + return compareIdentifiers(b, a) +} -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; +exports.major = major +function major (a, loose) { + return new SemVer(a, loose).major +} -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; +exports.minor = minor +function minor (a, loose) { + return new SemVer(a, loose).minor +} -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; +exports.patch = patch +function patch (a, loose) { + return new SemVer(a, loose).patch +} -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; +exports.compare = compare +function compare (a, b, loose) { + return new SemVer(a, loose).compare(new SemVer(b, loose)) +} -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; +exports.compareLoose = compareLoose +function compareLoose (a, b) { + return compare(a, b, true) +} -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; +exports.rcompare = rcompare +function rcompare (a, b, loose) { + return compare(b, a, loose) +} -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; +exports.sort = sort +function sort (list, loose) { + return list.sort(function (a, b) { + return exports.compare(a, b, loose) + }) +} -/** Used for built-in method references. */ -var objectProto = Object.prototype; +exports.rsort = rsort +function rsort (list, loose) { + return list.sort(function (a, b) { + return exports.rcompare(a, b, loose) + }) +} -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +exports.gt = gt +function gt (a, b, loose) { + return compare(a, b, loose) > 0 +} -/** - * Checks if `value` is an integer. - * - * **Note:** This method is based on - * [`Number.isInteger`](https://mdn.io/Number/isInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an integer, else `false`. - * @example - * - * _.isInteger(3); - * // => true - * - * _.isInteger(Number.MIN_VALUE); - * // => false - * - * _.isInteger(Infinity); - * // => false - * - * _.isInteger('3'); - * // => false - */ -function isInteger(value) { - return typeof value == 'number' && value == toInteger(value); +exports.lt = lt +function lt (a, b, loose) { + return compare(a, b, loose) < 0 +} + +exports.eq = eq +function eq (a, b, loose) { + return compare(a, b, loose) === 0 +} + +exports.neq = neq +function neq (a, b, loose) { + return compare(a, b, loose) !== 0 } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); +exports.gte = gte +function gte (a, b, loose) { + return compare(a, b, loose) >= 0 } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +exports.lte = lte +function lte (a, b, loose) { + return compare(a, b, loose) <= 0 } -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); +exports.cmp = cmp +function cmp (a, op, b, loose) { + switch (op) { + case '===': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a === b + + case '!==': + if (typeof a === 'object') + a = a.version + if (typeof b === 'object') + b = b.version + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError('Invalid operator: ' + op) + } } -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ -function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; +exports.Comparator = Comparator +function Comparator (comp, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } } - return value === value ? value : 0; -} -/** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ -function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; + if (!(this instanceof Comparator)) { + return new Comparator(comp, options) + } - return result === result ? (remainder ? result - remainder : result) : 0; -} + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ -function toNumber(value) { - if (typeof value == 'number') { - return value; + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version } - if (isSymbol(value)) { - return NAN; + + debug('comp', this) +} + +var ANY = {} +Comparator.prototype.parse = function (comp) { + var r = this.options.loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var m = comp.match(r) + + if (!m) { + throw new TypeError('Invalid comparator: ' + comp) } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; + + this.operator = m[1] + if (this.operator === '=') { + this.operator = '' } - if (typeof value != 'string') { - return value === 0 ? value : +value; + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); } -module.exports = isInteger; +Comparator.prototype.toString = function () { + return this.value +} +Comparator.prototype.test = function (version) { + debug('Comparator.test', version, this.options.loose) -/***/ }), + if (this.semver === ANY) { + return true + } -/***/ 40298: -/***/ ((module) => { + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } -/** - * lodash 3.0.3 (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright 2012-2016 The Dojo Foundation - * Based on Underscore.js 1.8.3 - * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ + return cmp(version, this.operator, this.semver, this.options) +} -/** `Object#toString` result references. */ -var numberTag = '[object Number]'; +Comparator.prototype.intersects = function (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } -/** Used for built-in method references. */ -var objectProto = Object.prototype; + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + var rangeTmp -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} + if (this.operator === '') { + rangeTmp = new Range(comp.value, options) + return satisfies(this.value, rangeTmp, options) + } else if (comp.operator === '') { + rangeTmp = new Range(this.value, options) + return satisfies(comp.semver, rangeTmp, options) + } -/** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified - * as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true - * - * _.isNumber('3'); - * // => false - */ -function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && objectToString.call(value) == numberTag); + var sameDirectionIncreasing = + (this.operator === '>=' || this.operator === '>') && + (comp.operator === '>=' || comp.operator === '>') + var sameDirectionDecreasing = + (this.operator === '<=' || this.operator === '<') && + (comp.operator === '<=' || comp.operator === '<') + var sameSemVer = this.semver.version === comp.semver.version + var differentDirectionsInclusive = + (this.operator === '>=' || this.operator === '<=') && + (comp.operator === '>=' || comp.operator === '<=') + var oppositeDirectionsLessThan = + cmp(this.semver, '<', comp.semver, options) && + ((this.operator === '>=' || this.operator === '>') && + (comp.operator === '<=' || comp.operator === '<')) + var oppositeDirectionsGreaterThan = + cmp(this.semver, '>', comp.semver, options) && + ((this.operator === '<=' || this.operator === '<') && + (comp.operator === '>=' || comp.operator === '>')) + + return sameDirectionIncreasing || sameDirectionDecreasing || + (sameSemVer && differentDirectionsInclusive) || + oppositeDirectionsLessThan || oppositeDirectionsGreaterThan } -module.exports = isNumber; +exports.Range = Range +function Range (range, options) { + if (!options || typeof options !== 'object') { + options = { + loose: !!options, + includePrerelease: false + } + } + if (range instanceof Range) { + if (range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease) { + return range + } else { + return new Range(range.raw, options) + } + } -/***/ }), + if (range instanceof Comparator) { + return new Range(range.value, options) + } -/***/ 25723: -/***/ ((module) => { + if (!(this instanceof Range)) { + return new Range(range, options) + } -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease -/** `Object#toString` result references. */ -var objectTag = '[object Object]'; + // First, split based on boolean or || + this.raw = range + this.set = range.split(/\s*\|\|\s*/).map(function (range) { + return this.parseRange(range.trim()) + }, this).filter(function (c) { + // throw out any that are not relevant for whatever reason + return c.length + }) -/** - * Checks if `value` is a host object in IE < 9. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a host object, else `false`. - */ -function isHostObject(value) { - // Many host objects are `Object` objects that can coerce to strings - // despite having improperly defined `toString` methods. - var result = false; - if (value != null && typeof value.toString != 'function') { - try { - result = !!(value + ''); - } catch (e) {} + if (!this.set.length) { + throw new TypeError('Invalid SemVer Range: ' + range) } - return result; -} -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; + this.format() } -/** Used for built-in method references. */ -var funcProto = Function.prototype, - objectProto = Object.prototype; +Range.prototype.format = function () { + this.range = this.set.map(function (comps) { + return comps.join(' ').trim() + }).join('||').trim() + return this.range +} -/** Used to resolve the decompiled source of functions. */ -var funcToString = funcProto.toString; +Range.prototype.toString = function () { + return this.range +} -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; +Range.prototype.parseRange = function (range) { + var loose = this.options.loose + range = range.trim() + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + var hr = loose ? re[HYPHENRANGELOOSE] : re[HYPHENRANGE] + range = range.replace(hr, hyphenReplace) + debug('hyphen replace', range) + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range, re[COMPARATORTRIM]) -/** Used to infer the `Object` constructor. */ -var objectCtorString = funcToString.call(Object); + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[TILDETRIM], tildeTrimReplace) -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[CARETTRIM], caretTrimReplace) -/** Built-in value references. */ -var getPrototype = overArg(Object.getPrototypeOf, Object); + // normalize spaces + range = range.split(/\s+/).join(' ') -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; -} + // At this point, the range is completely trimmed and + // ready to be split into comparators. -/** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - * - * _.isPlainObject(Object.create(null)); - * // => true - */ -function isPlainObject(value) { - if (!isObjectLike(value) || - objectToString.call(value) != objectTag || isHostObject(value)) { - return false; - } - var proto = getPrototype(value); - if (proto === null) { - return true; + var compRe = loose ? re[COMPARATORLOOSE] : re[COMPARATOR] + var set = range.split(' ').map(function (comp) { + return parseComparator(comp, this.options) + }, this).join(' ').split(/\s+/) + if (this.options.loose) { + // in loose mode, throw out any that are not valid comparators + set = set.filter(function (comp) { + return !!comp.match(compRe) + }) } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return (typeof Ctor == 'function' && - Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); -} + set = set.map(function (comp) { + return new Comparator(comp, this.options) + }, this) -module.exports = isPlainObject; + return set +} +Range.prototype.intersects = function (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } -/***/ }), + return this.set.some(function (thisComparators) { + return thisComparators.every(function (thisComparator) { + return range.set.some(function (rangeComparators) { + return rangeComparators.every(function (rangeComparator) { + return thisComparator.intersects(rangeComparator, options) + }) + }) + }) + }) +} -/***/ 25180: -/***/ ((module) => { +// Mostly just for testing and legacy API reasons +exports.toComparators = toComparators +function toComparators (range, options) { + return new Range(range, options).set.map(function (comp) { + return comp.map(function (c) { + return c.value + }).join(' ').trim().split(' ') + }) +} -/** - * lodash 4.0.1 (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright 2012-2016 The Dojo Foundation - * Based on Underscore.js 1.8.3 - * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +function parseComparator (comp, options) { + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} -/** `Object#toString` result references. */ -var stringTag = '[object String]'; +function isX (id) { + return !id || id.toLowerCase() === 'x' || id === '*' +} -/** Used for built-in method references. */ -var objectProto = Object.prototype; +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0 +function replaceTildes (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceTilde(comp, options) + }).join(' ') +} -/** - * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; +function replaceTilde (comp, options) { + var r = options.loose ? re[TILDELOOSE] : re[TILDE] + return comp.replace(r, function (_, M, m, p, pr) { + debug('tilde', comp, _, M, m, p, pr) + var ret -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @type Function - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0 + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else if (pr) { + debug('replaceTilde pr', pr) + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } else { + // ~1.2.3 == >=1.2.3 <1.3.0 + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; + debug('tilde return', ret) + return ret + }) } -/** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ -function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0 +// ^1.2.3 --> >=1.2.3 <2.0.0 +// ^1.2.0 --> >=1.2.0 <2.0.0 +function replaceCarets (comp, options) { + return comp.trim().split(/\s+/).map(function (comp) { + return replaceCaret(comp, options) + }).join(' ') } -module.exports = isString; +function replaceCaret (comp, options) { + debug('caret', comp, options) + var r = options.loose ? re[CARETLOOSE] : re[CARET] + return comp.replace(r, function (_, M, m, p, pr) { + debug('caret', comp, _, M, m, p, pr) + var ret + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (isX(p)) { + if (M === '0') { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } else { + ret = '>=' + M + '.' + m + '.0 <' + (+M + 1) + '.0.0' + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + '-' + pr + + ' <' + (+M + 1) + '.0.0' + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + m + '.' + (+p + 1) + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + M + '.' + (+m + 1) + '.0' + } + } else { + ret = '>=' + M + '.' + m + '.' + p + + ' <' + (+M + 1) + '.0.0' + } + } -/***/ }), + debug('caret return', ret) + return ret + }) +} -/***/ 94499: -/***/ ((module) => { +function replaceXRanges (comp, options) { + debug('replaceXRanges', comp, options) + return comp.split(/\s+/).map(function (comp) { + return replaceXRange(comp, options) + }).join(' ') +} -/** - * lodash (Custom Build) - * Build: `lodash modularize exports="npm" -o ./` - * Copyright jQuery Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ +function replaceXRange (comp, options) { + comp = comp.trim() + var r = options.loose ? re[XRANGELOOSE] : re[XRANGE] + return comp.replace(r, function (ret, gtlt, M, m, p, pr) { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + var xM = isX(M) + var xm = xM || isX(m) + var xp = xm || isX(p) + var anyX = xp -/** Used as the `TypeError` message for "Functions" methods. */ -var FUNC_ERROR_TEXT = 'Expected a function'; + if (gtlt === '=' && anyX) { + gtlt = '' + } -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + // >1.2.3 => >= 1.2.4 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; + ret = gtlt + M + '.' + m + '.' + p + } else if (xm) { + ret = '>=' + M + '.0.0 <' + (+M + 1) + '.0.0' + } else if (xp) { + ret = '>=' + M + '.' + m + '.0 <' + M + '.' + (+m + 1) + '.0' + } -/** Used to detect bad signed hexadecimal string values. */ -var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + debug('xRange return', ret) -/** Used to detect binary string values. */ -var reIsBinary = /^0b[01]+$/i; + return ret + }) +} -/** Used to detect octal string values. */ -var reIsOctal = /^0o[0-7]+$/i; +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +function replaceStars (comp, options) { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp.trim().replace(re[STAR], '') +} -/** Built-in method references without a dependency on `root`. */ -var freeParseInt = parseInt; +// This function is passed to string.replace(re[HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0 +function hyphenReplace ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr, tb) { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = '>=' + fM + '.0.0' + } else if (isX(fp)) { + from = '>=' + fM + '.' + fm + '.0' + } else { + from = '>=' + from + } -/** Used for built-in method references. */ -var objectProto = Object.prototype; + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = '<' + (+tM + 1) + '.0.0' + } else if (isX(tp)) { + to = '<' + tM + '.' + (+tm + 1) + '.0' + } else if (tpr) { + to = '<=' + tM + '.' + tm + '.' + tp + '-' + tpr + } else { + to = '<=' + to + } -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var objectToString = objectProto.toString; + return (from + ' ' + to).trim() +} -/** - * Creates a function that invokes `func`, with the `this` binding and arguments - * of the created function, while it's called less than `n` times. Subsequent - * calls to the created function return the result of the last `func` invocation. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {number} n The number of calls at which `func` is no longer invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * jQuery(element).on('click', _.before(5, addContactToList)); - * // => Allows adding up to 4 contacts to the list. - */ -function before(n, func) { - var result; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); +// if ANY of the sets match ALL of its comparators, then pass +Range.prototype.test = function (version) { + if (!version) { + return false } - n = toInteger(n); - return function() { - if (--n > 0) { - result = func.apply(this, arguments); + + if (typeof version === 'string') { + version = new SemVer(version, this.options) + } + + for (var i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true } - if (n <= 1) { - func = undefined; + } + return false +} + +function testSet (set, version, options) { + for (var i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + var allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } } - return result; - }; -} -/** - * Creates a function that is restricted to invoking `func` once. Repeat calls - * to the function return the value of the first invocation. The `func` is - * invoked with the `this` binding and arguments of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once - */ -function once(func) { - return before(2, func); -} + // Version has a -pre, but it's not one of the ones we like. + return false + } -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return !!value && (type == 'object' || type == 'function'); + return true } -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return !!value && typeof value == 'object'; +exports.satisfies = satisfies +function satisfies (version, range, options) { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) } -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && objectToString.call(value) == symbolTag); +exports.maxSatisfying = maxSatisfying +function maxSatisfying (versions, range, options) { + var max = null + var maxSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max } -/** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toFinite('3.2'); - * // => 3.2 - */ -function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; +exports.minSatisfying = minSatisfying +function minSatisfying (versions, range, options) { + var min = null + var minSV = null + try { + var rangeObj = new Range(range, options) + } catch (er) { + return null } - return value === value ? value : 0; + versions.forEach(function (v) { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min } -/** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 - * - * _.toInteger('3.2'); - * // => 3 - */ -function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; +exports.minVersion = minVersion +function minVersion (range, loose) { + range = new Range(range, loose) - return result === result ? (remainder ? result - remainder : result) : 0; -} + var minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } -/** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toNumber(Infinity); - * // => Infinity - * - * _.toNumber('3.2'); - * // => 3.2 - */ -function toNumber(value) { - if (typeof value == 'number') { - return value; + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver } - if (isSymbol(value)) { - return NAN; + + minver = null + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] + + comparators.forEach(function (comparator) { + // Clone to avoid manipulating the comparator's semver object. + var compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!minver || gt(minver, compver)) { + minver = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error('Unexpected operation: ' + comparator.operator) + } + }) } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; + + if (minver && range.test(minver)) { + return minver } - if (typeof value != 'string') { - return value === 0 ? value : +value; + + return null +} + +exports.validRange = validRange +function validRange (range, options) { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null } - value = value.replace(reTrim, ''); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); } -module.exports = once; +// Determine if version is less than all the versions possible in the range +exports.ltr = ltr +function ltr (version, range, options) { + return outside(version, range, '<', options) +} +// Determine if version is greater than all the versions possible in the range. +exports.gtr = gtr +function gtr (version, range, options) { + return outside(version, range, '>', options) +} -/***/ }), +exports.outside = outside +function outside (version, range, hilo, options) { + version = new SemVer(version, options) + range = new Range(range, options) -/***/ 90250: -/***/ (function(module, exports, __nccwpck_require__) { + var gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } -/* module decorator */ module = __nccwpck_require__.nmd(module); -/** - * @license - * Lodash - * Copyright OpenJS Foundation and other contributors - * Released under MIT license - * Based on Underscore.js 1.8.3 - * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - */ -;(function() { + // If it satisifes the range it is not outside + if (satisfies(version, range, options)) { + return false + } - /** Used as a safe reference for `undefined` in pre-ES5 environments. */ - var undefined; + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. - /** Used as the semantic version number. */ - var VERSION = '4.17.21'; + for (var i = 0; i < range.set.length; ++i) { + var comparators = range.set[i] - /** Used as the size to enable large array optimizations. */ - var LARGE_ARRAY_SIZE = 200; + var high = null + var low = null - /** Error message constants. */ - var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', - FUNC_ERROR_TEXT = 'Expected a function', - INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; + comparators.forEach(function (comparator) { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) - /** Used to stand-in for `undefined` hash values. */ - var HASH_UNDEFINED = '__lodash_hash_undefined__'; + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } - /** Used as the maximum memoize cache size. */ - var MAX_MEMOIZE_SIZE = 500; + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} - /** Used as the internal argument placeholder. */ - var PLACEHOLDER = '__lodash_placeholder__'; +exports.prerelease = prerelease +function prerelease (version, options) { + var parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} - /** Used to compose bitmasks for cloning. */ - var CLONE_DEEP_FLAG = 1, - CLONE_FLAT_FLAG = 2, - CLONE_SYMBOLS_FLAG = 4; +exports.intersects = intersects +function intersects (r1, r2, options) { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2) +} - /** Used to compose bitmasks for value comparisons. */ - var COMPARE_PARTIAL_FLAG = 1, - COMPARE_UNORDERED_FLAG = 2; +exports.coerce = coerce +function coerce (version) { + if (version instanceof SemVer) { + return version + } - /** Used to compose bitmasks for function metadata. */ - var WRAP_BIND_FLAG = 1, - WRAP_BIND_KEY_FLAG = 2, - WRAP_CURRY_BOUND_FLAG = 4, - WRAP_CURRY_FLAG = 8, - WRAP_CURRY_RIGHT_FLAG = 16, - WRAP_PARTIAL_FLAG = 32, - WRAP_PARTIAL_RIGHT_FLAG = 64, - WRAP_ARY_FLAG = 128, - WRAP_REARG_FLAG = 256, - WRAP_FLIP_FLAG = 512; + if (typeof version !== 'string') { + return null + } - /** Used as default options for `_.truncate`. */ - var DEFAULT_TRUNC_LENGTH = 30, - DEFAULT_TRUNC_OMISSION = '...'; + var match = version.match(re[COERCE]) - /** Used to detect hot functions by number of calls within a span of milliseconds. */ - var HOT_COUNT = 800, - HOT_SPAN = 16; + if (match == null) { + return null + } - /** Used to indicate the type of lazy iteratees. */ - var LAZY_FILTER_FLAG = 1, - LAZY_MAP_FLAG = 2, - LAZY_WHILE_FLAG = 3; + return parse(match[1] + + '.' + (match[2] || '0') + + '.' + (match[3] || '0')) +} - /** Used as references for various `Number` constants. */ - var INFINITY = 1 / 0, - MAX_SAFE_INTEGER = 9007199254740991, - MAX_INTEGER = 1.7976931348623157e+308, - NAN = 0 / 0; - /** Used as references for the maximum length and index of an array. */ - var MAX_ARRAY_LENGTH = 4294967295, - MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, - HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; +/***/ }), + +/***/ 82022: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var timespan = __nccwpck_require__(46098); +var PS_SUPPORTED = __nccwpck_require__(59085); +var jws = __nccwpck_require__(4636); +var includes = __nccwpck_require__(17931); +var isBoolean = __nccwpck_require__(16501); +var isInteger = __nccwpck_require__(21441); +var isNumber = __nccwpck_require__(40298); +var isPlainObject = __nccwpck_require__(25723); +var isString = __nccwpck_require__(25180); +var once = __nccwpck_require__(94499); + +var SUPPORTED_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'none'] +if (PS_SUPPORTED) { + SUPPORTED_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); +} + +var sign_options_schema = { + expiresIn: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"expiresIn" should be a number of seconds or string representing a timespan' }, + notBefore: { isValid: function(value) { return isInteger(value) || (isString(value) && value); }, message: '"notBefore" should be a number of seconds or string representing a timespan' }, + audience: { isValid: function(value) { return isString(value) || Array.isArray(value); }, message: '"audience" must be a string or array' }, + algorithm: { isValid: includes.bind(null, SUPPORTED_ALGS), message: '"algorithm" must be a valid string enum value' }, + header: { isValid: isPlainObject, message: '"header" must be an object' }, + encoding: { isValid: isString, message: '"encoding" must be a string' }, + issuer: { isValid: isString, message: '"issuer" must be a string' }, + subject: { isValid: isString, message: '"subject" must be a string' }, + jwtid: { isValid: isString, message: '"jwtid" must be a string' }, + noTimestamp: { isValid: isBoolean, message: '"noTimestamp" must be a boolean' }, + keyid: { isValid: isString, message: '"keyid" must be a string' }, + mutatePayload: { isValid: isBoolean, message: '"mutatePayload" must be a boolean' } +}; - /** Used to associate wrap methods with their bit flags. */ - var wrapFlags = [ - ['ary', WRAP_ARY_FLAG], - ['bind', WRAP_BIND_FLAG], - ['bindKey', WRAP_BIND_KEY_FLAG], - ['curry', WRAP_CURRY_FLAG], - ['curryRight', WRAP_CURRY_RIGHT_FLAG], - ['flip', WRAP_FLIP_FLAG], - ['partial', WRAP_PARTIAL_FLAG], - ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], - ['rearg', WRAP_REARG_FLAG] - ]; +var registered_claims_schema = { + iat: { isValid: isNumber, message: '"iat" should be a number of seconds' }, + exp: { isValid: isNumber, message: '"exp" should be a number of seconds' }, + nbf: { isValid: isNumber, message: '"nbf" should be a number of seconds' } +}; - /** `Object#toString` result references. */ - var argsTag = '[object Arguments]', - arrayTag = '[object Array]', - asyncTag = '[object AsyncFunction]', - boolTag = '[object Boolean]', - dateTag = '[object Date]', - domExcTag = '[object DOMException]', - errorTag = '[object Error]', - funcTag = '[object Function]', - genTag = '[object GeneratorFunction]', - mapTag = '[object Map]', - numberTag = '[object Number]', - nullTag = '[object Null]', - objectTag = '[object Object]', - promiseTag = '[object Promise]', - proxyTag = '[object Proxy]', - regexpTag = '[object RegExp]', - setTag = '[object Set]', - stringTag = '[object String]', - symbolTag = '[object Symbol]', - undefinedTag = '[object Undefined]', - weakMapTag = '[object WeakMap]', - weakSetTag = '[object WeakSet]'; +function validate(schema, allowUnknown, object, parameterName) { + if (!isPlainObject(object)) { + throw new Error('Expected "' + parameterName + '" to be a plain object.'); + } + Object.keys(object) + .forEach(function(key) { + var validator = schema[key]; + if (!validator) { + if (!allowUnknown) { + throw new Error('"' + key + '" is not allowed in "' + parameterName + '"'); + } + return; + } + if (!validator.isValid(object[key])) { + throw new Error(validator.message); + } + }); +} - var arrayBufferTag = '[object ArrayBuffer]', - dataViewTag = '[object DataView]', - float32Tag = '[object Float32Array]', - float64Tag = '[object Float64Array]', - int8Tag = '[object Int8Array]', - int16Tag = '[object Int16Array]', - int32Tag = '[object Int32Array]', - uint8Tag = '[object Uint8Array]', - uint8ClampedTag = '[object Uint8ClampedArray]', - uint16Tag = '[object Uint16Array]', - uint32Tag = '[object Uint32Array]'; +function validateOptions(options) { + return validate(sign_options_schema, false, options, 'options'); +} - /** Used to match empty string literals in compiled template source. */ - var reEmptyStringLeading = /\b__p \+= '';/g, - reEmptyStringMiddle = /\b(__p \+=) '' \+/g, - reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; +function validatePayload(payload) { + return validate(registered_claims_schema, true, payload, 'payload'); +} - /** Used to match HTML entities and HTML characters. */ - var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, - reUnescapedHtml = /[&<>"']/g, - reHasEscapedHtml = RegExp(reEscapedHtml.source), - reHasUnescapedHtml = RegExp(reUnescapedHtml.source); +var options_to_payload = { + 'audience': 'aud', + 'issuer': 'iss', + 'subject': 'sub', + 'jwtid': 'jti' +}; - /** Used to match template delimiters. */ - var reEscape = /<%-([\s\S]+?)%>/g, - reEvaluate = /<%([\s\S]+?)%>/g, - reInterpolate = /<%=([\s\S]+?)%>/g; +var options_for_objects = [ + 'expiresIn', + 'notBefore', + 'noTimestamp', + 'audience', + 'issuer', + 'subject', + 'jwtid', +]; - /** Used to match property names within property paths. */ - var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, - reIsPlainProp = /^\w*$/, - rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; +module.exports = function (payload, secretOrPrivateKey, options, callback) { + if (typeof options === 'function') { + callback = options; + options = {}; + } else { + options = options || {}; + } - /** - * Used to match `RegExp` - * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). - */ - var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, - reHasRegExpChar = RegExp(reRegExpChar.source); + var isObjectPayload = typeof payload === 'object' && + !Buffer.isBuffer(payload); - /** Used to match leading whitespace. */ - var reTrimStart = /^\s+/; + var header = Object.assign({ + alg: options.algorithm || 'HS256', + typ: isObjectPayload ? 'JWT' : undefined, + kid: options.keyid + }, options.header); - /** Used to match a single whitespace character. */ - var reWhitespace = /\s/; + function failure(err) { + if (callback) { + return callback(err); + } + throw err; + } - /** Used to match wrap detail comments. */ - var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, - reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, - reSplitDetails = /,? & /; + if (!secretOrPrivateKey && options.algorithm !== 'none') { + return failure(new Error('secretOrPrivateKey must have a value')); + } - /** Used to match words composed of alphanumeric characters. */ - var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + if (typeof payload === 'undefined') { + return failure(new Error('payload is required')); + } else if (isObjectPayload) { + try { + validatePayload(payload); + } + catch (error) { + return failure(error); + } + if (!options.mutatePayload) { + payload = Object.assign({},payload); + } + } else { + var invalid_options = options_for_objects.filter(function (opt) { + return typeof options[opt] !== 'undefined'; + }); - /** - * Used to validate the `validate` option in `_.template` variable. - * - * Forbids characters which could potentially change the meaning of the function argument definition: - * - "()," (modification of function parameters) - * - "=" (default value) - * - "[]{}" (destructuring of function parameters) - * - "/" (beginning of a comment) - * - whitespace - */ - var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; + if (invalid_options.length > 0) { + return failure(new Error('invalid ' + invalid_options.join(',') + ' option for ' + (typeof payload ) + ' payload')); + } + } - /** Used to match backslashes in property paths. */ - var reEscapeChar = /\\(\\)?/g; + if (typeof payload.exp !== 'undefined' && typeof options.expiresIn !== 'undefined') { + return failure(new Error('Bad "options.expiresIn" option the payload already has an "exp" property.')); + } - /** - * Used to match - * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). - */ - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + if (typeof payload.nbf !== 'undefined' && typeof options.notBefore !== 'undefined') { + return failure(new Error('Bad "options.notBefore" option the payload already has an "nbf" property.')); + } - /** Used to match `RegExp` flags from their coerced string values. */ - var reFlags = /\w*$/; + try { + validateOptions(options); + } + catch (error) { + return failure(error); + } - /** Used to detect bad signed hexadecimal string values. */ - var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + var timestamp = payload.iat || Math.floor(Date.now() / 1000); - /** Used to detect binary string values. */ - var reIsBinary = /^0b[01]+$/i; + if (options.noTimestamp) { + delete payload.iat; + } else if (isObjectPayload) { + payload.iat = timestamp; + } - /** Used to detect host constructors (Safari). */ - var reIsHostCtor = /^\[object .+?Constructor\]$/; + if (typeof options.notBefore !== 'undefined') { + try { + payload.nbf = timespan(options.notBefore, timestamp); + } + catch (err) { + return failure(err); + } + if (typeof payload.nbf === 'undefined') { + return failure(new Error('"notBefore" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + } - /** Used to detect octal string values. */ - var reIsOctal = /^0o[0-7]+$/i; + if (typeof options.expiresIn !== 'undefined' && typeof payload === 'object') { + try { + payload.exp = timespan(options.expiresIn, timestamp); + } + catch (err) { + return failure(err); + } + if (typeof payload.exp === 'undefined') { + return failure(new Error('"expiresIn" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + } - /** Used to detect unsigned integer values. */ - var reIsUint = /^(?:0|[1-9]\d*)$/; + Object.keys(options_to_payload).forEach(function (key) { + var claim = options_to_payload[key]; + if (typeof options[key] !== 'undefined') { + if (typeof payload[claim] !== 'undefined') { + return failure(new Error('Bad "options.' + key + '" option. The payload already has an "' + claim + '" property.')); + } + payload[claim] = options[key]; + } + }); - /** Used to match Latin Unicode letters (excluding mathematical operators). */ - var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + var encoding = options.encoding || 'utf8'; - /** Used to ensure capturing order of template delimiters. */ - var reNoMatch = /($^)/; + if (typeof callback === 'function') { + callback = callback && once(callback); - /** Used to match unescaped characters in compiled string literals. */ - var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + jws.createSign({ + header: header, + privateKey: secretOrPrivateKey, + payload: payload, + encoding: encoding + }).once('error', callback) + .once('done', function (signature) { + callback(null, signature); + }); + } else { + return jws.sign({header: header, payload: payload, secret: secretOrPrivateKey, encoding: encoding}); + } +}; - /** Used to compose unicode character classes. */ - var rsAstralRange = '\\ud800-\\udfff', - rsComboMarksRange = '\\u0300-\\u036f', - reComboHalfMarksRange = '\\ufe20-\\ufe2f', - rsComboSymbolsRange = '\\u20d0-\\u20ff', - rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, - rsDingbatRange = '\\u2700-\\u27bf', - rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', - rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', - rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', - rsPunctuationRange = '\\u2000-\\u206f', - rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', - rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', - rsVarRange = '\\ufe0e\\ufe0f', - rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - /** Used to compose unicode capture groups. */ - var rsApos = "['\u2019]", - rsAstral = '[' + rsAstralRange + ']', - rsBreak = '[' + rsBreakRange + ']', - rsCombo = '[' + rsComboRange + ']', - rsDigits = '\\d+', - rsDingbat = '[' + rsDingbatRange + ']', - rsLower = '[' + rsLowerRange + ']', - rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', - rsFitz = '\\ud83c[\\udffb-\\udfff]', - rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', - rsNonAstral = '[^' + rsAstralRange + ']', - rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', - rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', - rsUpper = '[' + rsUpperRange + ']', - rsZWJ = '\\u200d'; +/***/ }), - /** Used to compose unicode regexes. */ - var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', - rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', - rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', - rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', - reOptMod = rsModifier + '?', - rsOptVar = '[' + rsVarRange + ']?', - rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', - rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', - rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', - rsSeq = rsOptVar + reOptMod + rsOptJoin, - rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, - rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; +/***/ 12327: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** Used to match apostrophes. */ - var reApos = RegExp(rsApos, 'g'); +var JsonWebTokenError = __nccwpck_require__(405); +var NotBeforeError = __nccwpck_require__(4383); +var TokenExpiredError = __nccwpck_require__(46637); +var decode = __nccwpck_require__(53359); +var timespan = __nccwpck_require__(46098); +var PS_SUPPORTED = __nccwpck_require__(59085); +var jws = __nccwpck_require__(4636); - /** - * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and - * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). - */ - var reComboMark = RegExp(rsCombo, 'g'); +var PUB_KEY_ALGS = ['RS256', 'RS384', 'RS512', 'ES256', 'ES384', 'ES512']; +var RSA_KEY_ALGS = ['RS256', 'RS384', 'RS512']; +var HS_ALGS = ['HS256', 'HS384', 'HS512']; - /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ - var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); +if (PS_SUPPORTED) { + PUB_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); + RSA_KEY_ALGS.splice(3, 0, 'PS256', 'PS384', 'PS512'); +} - /** Used to match complex or compound words. */ - var reUnicodeWord = RegExp([ - rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', - rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', - rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, - rsUpper + '+' + rsOptContrUpper, - rsOrdUpper, - rsOrdLower, - rsDigits, - rsEmoji - ].join('|'), 'g'); +module.exports = function (jwtString, secretOrPublicKey, options, callback) { + if ((typeof options === 'function') && !callback) { + callback = options; + options = {}; + } - /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ - var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); + if (!options) { + options = {}; + } - /** Used to detect strings that need a more robust regexp to match words. */ - var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + //clone this object since we are going to mutate it. + options = Object.assign({}, options); - /** Used to assign default `context` object properties. */ - var contextProps = [ - 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', - 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', - 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', - 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', - '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' - ]; + var done; - /** Used to make template sourceURLs easier to identify. */ - var templateCounter = -1; + if (callback) { + done = callback; + } else { + done = function(err, data) { + if (err) throw err; + return data; + }; + } - /** Used to identify `toStringTag` values of typed arrays. */ - var typedArrayTags = {}; - typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = - typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = - typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = - typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = - typedArrayTags[uint32Tag] = true; - typedArrayTags[argsTag] = typedArrayTags[arrayTag] = - typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = - typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = - typedArrayTags[errorTag] = typedArrayTags[funcTag] = - typedArrayTags[mapTag] = typedArrayTags[numberTag] = - typedArrayTags[objectTag] = typedArrayTags[regexpTag] = - typedArrayTags[setTag] = typedArrayTags[stringTag] = - typedArrayTags[weakMapTag] = false; + if (options.clockTimestamp && typeof options.clockTimestamp !== 'number') { + return done(new JsonWebTokenError('clockTimestamp must be a number')); + } - /** Used to identify `toStringTag` values supported by `_.clone`. */ - var cloneableTags = {}; - cloneableTags[argsTag] = cloneableTags[arrayTag] = - cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = - cloneableTags[boolTag] = cloneableTags[dateTag] = - cloneableTags[float32Tag] = cloneableTags[float64Tag] = - cloneableTags[int8Tag] = cloneableTags[int16Tag] = - cloneableTags[int32Tag] = cloneableTags[mapTag] = - cloneableTags[numberTag] = cloneableTags[objectTag] = - cloneableTags[regexpTag] = cloneableTags[setTag] = - cloneableTags[stringTag] = cloneableTags[symbolTag] = - cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = - cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; - cloneableTags[errorTag] = cloneableTags[funcTag] = - cloneableTags[weakMapTag] = false; + if (options.nonce !== undefined && (typeof options.nonce !== 'string' || options.nonce.trim() === '')) { + return done(new JsonWebTokenError('nonce must be a non-empty string')); + } - /** Used to map Latin Unicode letters to basic Latin letters. */ - var deburredLetters = { - // Latin-1 Supplement block. - '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', - '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', - '\xc7': 'C', '\xe7': 'c', - '\xd0': 'D', '\xf0': 'd', - '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', - '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', - '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', - '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', - '\xd1': 'N', '\xf1': 'n', - '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', - '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', - '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', - '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', - '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', - '\xc6': 'Ae', '\xe6': 'ae', - '\xde': 'Th', '\xfe': 'th', - '\xdf': 'ss', - // Latin Extended-A block. - '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', - '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', - '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', - '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', - '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', - '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', - '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', - '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', - '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', - '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', - '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', - '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', - '\u0134': 'J', '\u0135': 'j', - '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', - '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', - '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', - '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', - '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', - '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', - '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', - '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', - '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', - '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', - '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', - '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', - '\u0163': 't', '\u0165': 't', '\u0167': 't', - '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', - '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', - '\u0174': 'W', '\u0175': 'w', - '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', - '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', - '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', - '\u0132': 'IJ', '\u0133': 'ij', - '\u0152': 'Oe', '\u0153': 'oe', - '\u0149': "'n", '\u017f': 's' - }; + var clockTimestamp = options.clockTimestamp || Math.floor(Date.now() / 1000); - /** Used to map characters to HTML entities. */ - var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; + if (!jwtString){ + return done(new JsonWebTokenError('jwt must be provided')); + } - /** Used to map HTML entities to characters. */ - var htmlUnescapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - ''': "'" - }; + if (typeof jwtString !== 'string') { + return done(new JsonWebTokenError('jwt must be a string')); + } - /** Used to escape characters for inclusion in compiled string literals. */ - var stringEscapes = { - '\\': '\\', - "'": "'", - '\n': 'n', - '\r': 'r', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; + var parts = jwtString.split('.'); - /** Built-in method references without a dependency on `root`. */ - var freeParseFloat = parseFloat, - freeParseInt = parseInt; + if (parts.length !== 3){ + return done(new JsonWebTokenError('jwt malformed')); + } - /** Detect free variable `global` from Node.js. */ - var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; + var decodedToken; - /** Detect free variable `self`. */ - var freeSelf = typeof self == 'object' && self && self.Object === Object && self; + try { + decodedToken = decode(jwtString, { complete: true }); + } catch(err) { + return done(err); + } - /** Used as a reference to the global object. */ - var root = freeGlobal || freeSelf || Function('return this')(); + if (!decodedToken) { + return done(new JsonWebTokenError('invalid token')); + } - /** Detect free variable `exports`. */ - var freeExports = true && exports && !exports.nodeType && exports; + var header = decodedToken.header; + var getSecret; - /** Detect free variable `module`. */ - var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; + if(typeof secretOrPublicKey === 'function') { + if(!callback) { + return done(new JsonWebTokenError('verify must be called asynchronous if secret or public key is provided as a callback')); + } - /** Detect the popular CommonJS extension `module.exports`. */ - var moduleExports = freeModule && freeModule.exports === freeExports; + getSecret = secretOrPublicKey; + } + else { + getSecret = function(header, secretCallback) { + return secretCallback(null, secretOrPublicKey); + }; + } - /** Detect free variable `process` from Node.js. */ - var freeProcess = moduleExports && freeGlobal.process; + return getSecret(header, function(err, secretOrPublicKey) { + if(err) { + return done(new JsonWebTokenError('error in secret or public key callback: ' + err.message)); + } - /** Used to access faster Node.js helpers. */ - var nodeUtil = (function() { - try { - // Use `util.types` for Node.js 10+. - var types = freeModule && freeModule.require && freeModule.require('util').types; + var hasSignature = parts[2].trim() !== ''; - if (types) { - return types; - } + if (!hasSignature && secretOrPublicKey){ + return done(new JsonWebTokenError('jwt signature is required')); + } - // Legacy `process.binding('util')` for Node.js < 10. - return freeProcess && freeProcess.binding && freeProcess.binding('util'); - } catch (e) {} - }()); + if (hasSignature && !secretOrPublicKey) { + return done(new JsonWebTokenError('secret or public key must be provided')); + } - /* Node.js helper references. */ - var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, - nodeIsDate = nodeUtil && nodeUtil.isDate, - nodeIsMap = nodeUtil && nodeUtil.isMap, - nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, - nodeIsSet = nodeUtil && nodeUtil.isSet, - nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + if (!hasSignature && !options.algorithms) { + options.algorithms = ['none']; + } - /*--------------------------------------------------------------------------*/ + if (!options.algorithms) { + options.algorithms = ~secretOrPublicKey.toString().indexOf('BEGIN CERTIFICATE') || + ~secretOrPublicKey.toString().indexOf('BEGIN PUBLIC KEY') ? PUB_KEY_ALGS : + ~secretOrPublicKey.toString().indexOf('BEGIN RSA PUBLIC KEY') ? RSA_KEY_ALGS : HS_ALGS; - /** - * A faster alternative to `Function#apply`, this function invokes `func` - * with the `this` binding of `thisArg` and the arguments of `args`. - * - * @private - * @param {Function} func The function to invoke. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} args The arguments to invoke `func` with. - * @returns {*} Returns the result of `func`. - */ - function apply(func, thisArg, args) { - switch (args.length) { - case 0: return func.call(thisArg); - case 1: return func.call(thisArg, args[0]); - case 2: return func.call(thisArg, args[0], args[1]); - case 3: return func.call(thisArg, args[0], args[1], args[2]); } - return func.apply(thisArg, args); - } - /** - * A specialized version of `baseAggregator` for arrays. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ - function arrayAggregator(array, setter, iteratee, accumulator) { - var index = -1, - length = array == null ? 0 : array.length; + if (!~options.algorithms.indexOf(decodedToken.header.alg)) { + return done(new JsonWebTokenError('invalid algorithm')); + } - while (++index < length) { - var value = array[index]; - setter(accumulator, value, iteratee(value), array); + var valid; + + try { + valid = jws.verify(jwtString, decodedToken.header.alg, secretOrPublicKey); + } catch (e) { + return done(e); } - return accumulator; - } - /** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEach(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length; + if (!valid) { + return done(new JsonWebTokenError('invalid signature')); + } - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; + var payload = decodedToken.payload; + + if (typeof payload.nbf !== 'undefined' && !options.ignoreNotBefore) { + if (typeof payload.nbf !== 'number') { + return done(new JsonWebTokenError('invalid nbf value')); + } + if (payload.nbf > clockTimestamp + (options.clockTolerance || 0)) { + return done(new NotBeforeError('jwt not active', new Date(payload.nbf * 1000))); } } - return array; - } - - /** - * A specialized version of `_.forEachRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ - function arrayEachRight(array, iteratee) { - var length = array == null ? 0 : array.length; - while (length--) { - if (iteratee(array[length], length, array) === false) { - break; + if (typeof payload.exp !== 'undefined' && !options.ignoreExpiration) { + if (typeof payload.exp !== 'number') { + return done(new JsonWebTokenError('invalid exp value')); + } + if (clockTimestamp >= payload.exp + (options.clockTolerance || 0)) { + return done(new TokenExpiredError('jwt expired', new Date(payload.exp * 1000))); } } - return array; - } - /** - * A specialized version of `_.every` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false`. - */ - function arrayEvery(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; + if (options.audience) { + var audiences = Array.isArray(options.audience) ? options.audience : [options.audience]; + var target = Array.isArray(payload.aud) ? payload.aud : [payload.aud]; - while (++index < length) { - if (!predicate(array[index], index, array)) { - return false; + var match = target.some(function (targetAudience) { + return audiences.some(function (audience) { + return audience instanceof RegExp ? audience.test(targetAudience) : audience === targetAudience; + }); + }); + + if (!match) { + return done(new JsonWebTokenError('jwt audience invalid. expected: ' + audiences.join(' or '))); } } - return true; - } - /** - * A specialized version of `_.filter` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function arrayFilter(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; + if (options.issuer) { + var invalid_issuer = + (typeof options.issuer === 'string' && payload.iss !== options.issuer) || + (Array.isArray(options.issuer) && options.issuer.indexOf(payload.iss) === -1); - while (++index < length) { - var value = array[index]; - if (predicate(value, index, array)) { - result[resIndex++] = value; + if (invalid_issuer) { + return done(new JsonWebTokenError('jwt issuer invalid. expected: ' + options.issuer)); } } - return result; - } - /** - * A specialized version of `_.includes` for arrays without support for - * specifying an index to search from. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludes(array, value) { - var length = array == null ? 0 : array.length; - return !!length && baseIndexOf(array, value, 0) > -1; - } + if (options.subject) { + if (payload.sub !== options.subject) { + return done(new JsonWebTokenError('jwt subject invalid. expected: ' + options.subject)); + } + } - /** - * This function is like `arrayIncludes` except that it accepts a comparator. - * - * @private - * @param {Array} [array] The array to inspect. - * @param {*} target The value to search for. - * @param {Function} comparator The comparator invoked per element. - * @returns {boolean} Returns `true` if `target` is found, else `false`. - */ - function arrayIncludesWith(array, value, comparator) { - var index = -1, - length = array == null ? 0 : array.length; + if (options.jwtid) { + if (payload.jti !== options.jwtid) { + return done(new JsonWebTokenError('jwt jwtid invalid. expected: ' + options.jwtid)); + } + } - while (++index < length) { - if (comparator(value, array[index])) { - return true; + if (options.nonce) { + if (payload.nonce !== options.nonce) { + return done(new JsonWebTokenError('jwt nonce invalid. expected: ' + options.nonce)); } } - return false; - } - /** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); + if (options.maxAge) { + if (typeof payload.iat !== 'number') { + return done(new JsonWebTokenError('iat required when maxAge is specified')); + } - while (++index < length) { - result[index] = iteratee(array[index], index, array); + var maxAgeTimestamp = timespan(options.maxAge, payload.iat); + if (typeof maxAgeTimestamp === 'undefined') { + return done(new JsonWebTokenError('"maxAge" should be a number of seconds or string representing a timespan eg: "1d", "20h", 60')); + } + if (clockTimestamp >= maxAgeTimestamp + (options.clockTolerance || 0)) { + return done(new TokenExpiredError('maxAge exceeded', new Date(maxAgeTimestamp * 1000))); + } } - return result; - } - /** - * Appends the elements of `values` to `array`. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to append. - * @returns {Array} Returns `array`. - */ - function arrayPush(array, values) { - var index = -1, - length = values.length, - offset = array.length; + if (options.complete === true) { + var signature = decodedToken.signature; - while (++index < length) { - array[offset + index] = values[index]; + return done(null, { + header: header, + payload: payload, + signature: signature + }); } - return array; + + return done(null, payload); + }); +}; + + +/***/ }), + +/***/ 96010: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var bufferEqual = __nccwpck_require__(9239); +var Buffer = __nccwpck_require__(21867).Buffer; +var crypto = __nccwpck_require__(76417); +var formatEcdsa = __nccwpck_require__(11728); +var util = __nccwpck_require__(31669); + +var MSG_INVALID_ALGORITHM = '"%s" is not a valid algorithm.\n Supported algorithms are:\n "HS256", "HS384", "HS512", "RS256", "RS384", "RS512", "PS256", "PS384", "PS512", "ES256", "ES384", "ES512" and "none".' +var MSG_INVALID_SECRET = 'secret must be a string or buffer'; +var MSG_INVALID_VERIFIER_KEY = 'key must be a string or a buffer'; +var MSG_INVALID_SIGNER_KEY = 'key must be a string, a buffer or an object'; + +var supportsKeyObjects = typeof crypto.createPublicKey === 'function'; +if (supportsKeyObjects) { + MSG_INVALID_VERIFIER_KEY += ' or a KeyObject'; + MSG_INVALID_SECRET += 'or a KeyObject'; +} + +function checkIsPublicKey(key) { + if (Buffer.isBuffer(key)) { + return; } - /** - * A specialized version of `_.reduce` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the first element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduce(array, iteratee, accumulator, initAccum) { - var index = -1, - length = array == null ? 0 : array.length; + if (typeof key === 'string') { + return; + } - if (initAccum && length) { - accumulator = array[++index]; - } - while (++index < length) { - accumulator = iteratee(accumulator, array[index], index, array); - } - return accumulator; + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_VERIFIER_KEY); } - /** - * A specialized version of `_.reduceRight` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @param {boolean} [initAccum] Specify using the last element of `array` as - * the initial value. - * @returns {*} Returns the accumulated value. - */ - function arrayReduceRight(array, iteratee, accumulator, initAccum) { - var length = array == null ? 0 : array.length; - if (initAccum && length) { - accumulator = array[--length]; - } - while (length--) { - accumulator = iteratee(accumulator, array[length], length, array); - } - return accumulator; + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_VERIFIER_KEY); } - /** - * A specialized version of `_.some` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function arraySome(array, predicate) { - var index = -1, - length = array == null ? 0 : array.length; + if (typeof key.type !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } - while (++index < length) { - if (predicate(array[index], index, array)) { - return true; - } - } - return false; + if (typeof key.asymmetricKeyType !== 'string') { + throw typeError(MSG_INVALID_VERIFIER_KEY); } - /** - * Gets the size of an ASCII `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - var asciiSize = baseProperty('length'); + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_VERIFIER_KEY); + } +}; - /** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function asciiToArray(string) { - return string.split(''); +function checkIsPrivateKey(key) { + if (Buffer.isBuffer(key)) { + return; } - /** - * Splits an ASCII `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function asciiWords(string) { - return string.match(reAsciiWord) || []; + if (typeof key === 'string') { + return; } - /** - * The base implementation of methods like `_.findKey` and `_.findLastKey`, - * without support for iteratee shorthands, which iterates over `collection` - * using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the found element or its key, else `undefined`. - */ - function baseFindKey(collection, predicate, eachFunc) { - var result; - eachFunc(collection, function(value, key, collection) { - if (predicate(value, key, collection)) { - result = key; - return false; - } - }); - return result; + if (typeof key === 'object') { + return; } - /** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); + throw typeError(MSG_INVALID_SIGNER_KEY); +}; - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; +function checkIsSecretKey(key) { + if (Buffer.isBuffer(key)) { + return; } - /** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); + if (typeof key === 'string') { + return key; } - /** - * This function is like `baseIndexOf` except that it accepts a comparator. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @param {Function} comparator The comparator invoked per element. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function baseIndexOfWith(array, value, fromIndex, comparator) { - var index = fromIndex - 1, - length = array.length; + if (!supportsKeyObjects) { + throw typeError(MSG_INVALID_SECRET); + } - while (++index < length) { - if (comparator(array[index], value)) { - return index; - } - } - return -1; + if (typeof key !== 'object') { + throw typeError(MSG_INVALID_SECRET); } - /** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ - function baseIsNaN(value) { - return value !== value; + if (key.type !== 'secret') { + throw typeError(MSG_INVALID_SECRET); } - /** - * The base implementation of `_.mean` and `_.meanBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the mean. - */ - function baseMean(array, iteratee) { - var length = array == null ? 0 : array.length; - return length ? (baseSum(array, iteratee) / length) : NAN; + if (typeof key.export !== 'function') { + throw typeError(MSG_INVALID_SECRET); } +} - /** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; +function fromBase64(base64) { + return base64 + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function toBase64(base64url) { + base64url = base64url.toString(); + + var padding = 4 - base64url.length % 4; + if (padding !== 4) { + for (var i = 0; i < padding; ++i) { + base64url += '='; + } } - /** - * The base implementation of `_.propertyOf` without support for deep paths. - * - * @private - * @param {Object} object The object to query. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyOf(object) { - return function(key) { - return object == null ? undefined : object[key]; - }; + return base64url + .replace(/\-/g, '+') + .replace(/_/g, '/'); +} + +function typeError(template) { + var args = [].slice.call(arguments, 1); + var errMsg = util.format.bind(util, template).apply(null, args); + return new TypeError(errMsg); +} + +function bufferOrString(obj) { + return Buffer.isBuffer(obj) || typeof obj === 'string'; +} + +function normalizeInput(thing) { + if (!bufferOrString(thing)) + thing = JSON.stringify(thing); + return thing; +} + +function createHmacSigner(bits) { + return function sign(thing, secret) { + checkIsSecretKey(secret); + thing = normalizeInput(thing); + var hmac = crypto.createHmac('sha' + bits, secret); + var sig = (hmac.update(thing), hmac.digest('base64')) + return fromBase64(sig); } +} - /** - * The base implementation of `_.reduce` and `_.reduceRight`, without support - * for iteratee shorthands, which iterates over `collection` using `eachFunc`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {*} accumulator The initial value. - * @param {boolean} initAccum Specify using the first or last element of - * `collection` as the initial value. - * @param {Function} eachFunc The function to iterate over `collection`. - * @returns {*} Returns the accumulated value. - */ - function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { - eachFunc(collection, function(value, index, collection) { - accumulator = initAccum - ? (initAccum = false, value) - : iteratee(accumulator, value, index, collection); - }); - return accumulator; +function createHmacVerifier(bits) { + return function verify(thing, signature, secret) { + var computedSig = createHmacSigner(bits)(thing, secret); + return bufferEqual(Buffer.from(signature), Buffer.from(computedSig)); } +} - /** - * The base implementation of `_.sortBy` which uses `comparer` to define the - * sort order of `array` and replaces criteria objects with their corresponding - * values. - * - * @private - * @param {Array} array The array to sort. - * @param {Function} comparer The function to define sort order. - * @returns {Array} Returns `array`. - */ - function baseSortBy(array, comparer) { - var length = array.length; +function createKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + // Even though we are specifying "RSA" here, this works with ECDSA + // keys as well. + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign(privateKey, 'base64')); + return fromBase64(sig); + } +} - array.sort(comparer); - while (length--) { - array[length] = array[length].value; - } - return array; +function createKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify(publicKey, signature, 'base64'); } +} - /** - * The base implementation of `_.sum` and `_.sumBy` without support for - * iteratee shorthands. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {number} Returns the sum. - */ - function baseSum(array, iteratee) { - var result, - index = -1, - length = array.length; +function createPSSKeySigner(bits) { + return function sign(thing, privateKey) { + checkIsPrivateKey(privateKey); + thing = normalizeInput(thing); + var signer = crypto.createSign('RSA-SHA' + bits); + var sig = (signer.update(thing), signer.sign({ + key: privateKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, 'base64')); + return fromBase64(sig); + } +} - while (++index < length) { - var current = iteratee(array[index]); - if (current !== undefined) { - result = result === undefined ? current : (result + current); - } - } - return result; +function createPSSKeyVerifier(bits) { + return function verify(thing, signature, publicKey) { + checkIsPublicKey(publicKey); + thing = normalizeInput(thing); + signature = toBase64(signature); + var verifier = crypto.createVerify('RSA-SHA' + bits); + verifier.update(thing); + return verifier.verify({ + key: publicKey, + padding: crypto.constants.RSA_PKCS1_PSS_PADDING, + saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST + }, signature, 'base64'); } +} - /** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ - function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); +function createECDSASigner(bits) { + var inner = createKeySigner(bits); + return function sign() { + var signature = inner.apply(null, arguments); + signature = formatEcdsa.derToJose(signature, 'ES' + bits); + return signature; + }; +} - while (++index < n) { - result[index] = iteratee(index); - } +function createECDSAVerifer(bits) { + var inner = createKeyVerifier(bits); + return function verify(thing, signature, publicKey) { + signature = formatEcdsa.joseToDer(signature, 'ES' + bits).toString('base64'); + var result = inner(thing, signature, publicKey); return result; - } + }; +} - /** - * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array - * of key-value pairs for `object` corresponding to the property names of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the key-value pairs. - */ - function baseToPairs(object, props) { - return arrayMap(props, function(key) { - return [key, object[key]]; - }); +function createNoneSigner() { + return function sign() { + return ''; } +} - /** - * The base implementation of `_.trim`. - * - * @private - * @param {string} string The string to trim. - * @returns {string} Returns the trimmed string. - */ - function baseTrim(string) { - return string - ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') - : string; +function createNoneVerifier() { + return function verify(thing, signature) { + return signature === ''; } +} - /** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ - function baseUnary(func) { - return function(value) { - return func(value); - }; +module.exports = function jwa(algorithm) { + var signerFactories = { + hs: createHmacSigner, + rs: createKeySigner, + ps: createPSSKeySigner, + es: createECDSASigner, + none: createNoneSigner, } + var verifierFactories = { + hs: createHmacVerifier, + rs: createKeyVerifier, + ps: createPSSKeyVerifier, + es: createECDSAVerifer, + none: createNoneVerifier, + } + var match = algorithm.match(/^(RS|PS|ES|HS)(256|384|512)$|^(none)$/i); + if (!match) + throw typeError(MSG_INVALID_ALGORITHM, algorithm); + var algo = (match[1] || match[3]).toLowerCase(); + var bits = match[2]; - /** - * The base implementation of `_.values` and `_.valuesIn` which creates an - * array of `object` property values corresponding to the property names - * of `props`. - * - * @private - * @param {Object} object The object to query. - * @param {Array} props The property names to get values for. - * @returns {Object} Returns the array of property values. - */ - function baseValues(object, props) { - return arrayMap(props, function(key) { - return object[key]; - }); + return { + sign: signerFactories[algo](bits), + verify: verifierFactories[algo](bits), } +}; - /** - * Checks if a `cache` value for `key` exists. - * - * @private - * @param {Object} cache The cache to query. - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function cacheHas(cache, key) { - return cache.has(key); + +/***/ }), + +/***/ 4636: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +/*global exports*/ +var SignStream = __nccwpck_require__(73334); +var VerifyStream = __nccwpck_require__(5522); + +var ALGORITHMS = [ + 'HS256', 'HS384', 'HS512', + 'RS256', 'RS384', 'RS512', + 'PS256', 'PS384', 'PS512', + 'ES256', 'ES384', 'ES512' +]; + +exports.ALGORITHMS = ALGORITHMS; +exports.sign = SignStream.sign; +exports.verify = VerifyStream.verify; +exports.decode = VerifyStream.decode; +exports.isValid = VerifyStream.isValid; +exports.createSign = function createSign(opts) { + return new SignStream(opts); +}; +exports.createVerify = function createVerify(opts) { + return new VerifyStream(opts); +}; + + +/***/ }), + +/***/ 61868: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/*global module, process*/ +var Buffer = __nccwpck_require__(21867).Buffer; +var Stream = __nccwpck_require__(92413); +var util = __nccwpck_require__(31669); + +function DataStream(data) { + this.buffer = null; + this.writable = true; + this.readable = true; + + // No input + if (!data) { + this.buffer = Buffer.alloc(0); + return this; } - /** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ - function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; + // Stream + if (typeof data.pipe === 'function') { + this.buffer = Buffer.alloc(0); + data.pipe(this); + return this; + } - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; + // Buffer or String + // or Object (assumedly a passworded key) + if (data.length || typeof data === 'object') { + this.buffer = data; + this.writable = false; + process.nextTick(function () { + this.emit('end', data); + this.readable = false; + this.emit('close'); + }.bind(this)); + return this; } - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ - function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; + throw new TypeError('Unexpected data type ('+ typeof data + ')'); +} +util.inherits(DataStream, Stream); + +DataStream.prototype.write = function write(data) { + this.buffer = Buffer.concat([this.buffer, Buffer.from(data)]); + this.emit('data', data); +}; + +DataStream.prototype.end = function end(data) { + if (data) + this.write(data); + this.emit('end', data); + this.emit('close'); + this.writable = false; + this.readable = false; +}; + +module.exports = DataStream; + + +/***/ }), + +/***/ 73334: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/*global module*/ +var Buffer = __nccwpck_require__(21867).Buffer; +var DataStream = __nccwpck_require__(61868); +var jwa = __nccwpck_require__(96010); +var Stream = __nccwpck_require__(92413); +var toString = __nccwpck_require__(65292); +var util = __nccwpck_require__(31669); + +function base64url(string, encoding) { + return Buffer + .from(string, encoding) + .toString('base64') + .replace(/=/g, '') + .replace(/\+/g, '-') + .replace(/\//g, '_'); +} + +function jwsSecuredInput(header, payload, encoding) { + encoding = encoding || 'utf8'; + var encodedHeader = base64url(toString(header), 'binary'); + var encodedPayload = base64url(toString(payload), encoding); + return util.format('%s.%s', encodedHeader, encodedPayload); +} + +function jwsSign(opts) { + var header = opts.header; + var payload = opts.payload; + var secretOrKey = opts.secret || opts.privateKey; + var encoding = opts.encoding; + var algo = jwa(header.alg); + var securedInput = jwsSecuredInput(header, payload, encoding); + var signature = algo.sign(securedInput, secretOrKey); + return util.format('%s.%s', securedInput, signature); +} + +function SignStream(opts) { + var secret = opts.secret||opts.privateKey||opts.key; + var secretStream = new DataStream(secret); + this.readable = true; + this.header = opts.header; + this.encoding = opts.encoding; + this.secret = this.privateKey = this.key = secretStream; + this.payload = new DataStream(opts.payload); + this.secret.once('close', function () { + if (!this.payload.writable && this.readable) + this.sign(); + }.bind(this)); + + this.payload.once('close', function () { + if (!this.secret.writable && this.readable) + this.sign(); + }.bind(this)); +} +util.inherits(SignStream, Stream); - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; +SignStream.prototype.sign = function sign() { + try { + var signature = jwsSign({ + header: this.header, + payload: this.payload.buffer, + secret: this.secret.buffer, + encoding: this.encoding + }); + this.emit('done', signature); + this.emit('data', signature); + this.emit('end'); + this.readable = false; + return signature; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); } +}; - /** - * Gets the number of `placeholder` occurrences in `array`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} placeholder The placeholder to search for. - * @returns {number} Returns the placeholder count. - */ - function countHolders(array, placeholder) { - var length = array.length, - result = 0; +SignStream.sign = jwsSign; - while (length--) { - if (array[length] === placeholder) { - ++result; - } - } - return result; - } +module.exports = SignStream; - /** - * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A - * letters to basic Latin letters. - * - * @private - * @param {string} letter The matched letter to deburr. - * @returns {string} Returns the deburred letter. - */ - var deburrLetter = basePropertyOf(deburredLetters); - /** - * Used by `_.escape` to convert characters to HTML entities. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - var escapeHtmlChar = basePropertyOf(htmlEscapes); +/***/ }), - /** - * Used by `_.template` to escape characters for inclusion in compiled string literals. - * - * @private - * @param {string} chr The matched character to escape. - * @returns {string} Returns the escaped character. - */ - function escapeStringChar(chr) { - return '\\' + stringEscapes[chr]; - } +/***/ 65292: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Gets the value at `key` of `object`. - * - * @private - * @param {Object} [object] The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. - */ - function getValue(object, key) { - return object == null ? undefined : object[key]; - } +/*global module*/ +var Buffer = __nccwpck_require__(64293).Buffer; - /** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ - function hasUnicode(string) { - return reHasUnicode.test(string); - } +module.exports = function toString(obj) { + if (typeof obj === 'string') + return obj; + if (typeof obj === 'number' || Buffer.isBuffer(obj)) + return obj.toString(); + return JSON.stringify(obj); +}; - /** - * Checks if `string` contains a word composed of Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a word is found, else `false`. - */ - function hasUnicodeWord(string) { - return reHasUnicodeWord.test(string); - } - /** - * Converts `iterator` to an array. - * - * @private - * @param {Object} iterator The iterator to convert. - * @returns {Array} Returns the converted array. - */ - function iteratorToArray(iterator) { - var data, - result = []; +/***/ }), - while (!(data = iterator.next()).done) { - result.push(data.value); - } - return result; - } +/***/ 5522: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Converts `map` to its key-value pairs. - * - * @private - * @param {Object} map The map to convert. - * @returns {Array} Returns the key-value pairs. - */ - function mapToArray(map) { - var index = -1, - result = Array(map.size); +/*global module*/ +var Buffer = __nccwpck_require__(21867).Buffer; +var DataStream = __nccwpck_require__(61868); +var jwa = __nccwpck_require__(96010); +var Stream = __nccwpck_require__(92413); +var toString = __nccwpck_require__(65292); +var util = __nccwpck_require__(31669); +var JWS_REGEX = /^[a-zA-Z0-9\-_]+?\.[a-zA-Z0-9\-_]+?\.([a-zA-Z0-9\-_]+)?$/; - map.forEach(function(value, key) { - result[++index] = [key, value]; - }); - return result; - } +function isObject(thing) { + return Object.prototype.toString.call(thing) === '[object Object]'; +} - /** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ - function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; - } +function safeJsonParse(thing) { + if (isObject(thing)) + return thing; + try { return JSON.parse(thing); } + catch (e) { return undefined; } +} - /** - * Replaces all `placeholder` elements in `array` with an internal placeholder - * and returns an array of their indexes. - * - * @private - * @param {Array} array The array to modify. - * @param {*} placeholder The placeholder to replace. - * @returns {Array} Returns the new array of placeholder indexes. - */ - function replaceHolders(array, placeholder) { - var index = -1, - length = array.length, - resIndex = 0, - result = []; +function headerFromJWS(jwsSig) { + var encodedHeader = jwsSig.split('.', 1)[0]; + return safeJsonParse(Buffer.from(encodedHeader, 'base64').toString('binary')); +} - while (++index < length) { - var value = array[index]; - if (value === placeholder || value === PLACEHOLDER) { - array[index] = PLACEHOLDER; - result[resIndex++] = index; - } - } - return result; - } +function securedInputFromJWS(jwsSig) { + return jwsSig.split('.', 2).join('.'); +} - /** - * Converts `set` to an array of its values. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the values. - */ - function setToArray(set) { - var index = -1, - result = Array(set.size); +function signatureFromJWS(jwsSig) { + return jwsSig.split('.')[2]; +} - set.forEach(function(value) { - result[++index] = value; - }); - return result; - } +function payloadFromJWS(jwsSig, encoding) { + encoding = encoding || 'utf8'; + var payload = jwsSig.split('.')[1]; + return Buffer.from(payload, 'base64').toString(encoding); +} - /** - * Converts `set` to its value-value pairs. - * - * @private - * @param {Object} set The set to convert. - * @returns {Array} Returns the value-value pairs. - */ - function setToPairs(set) { - var index = -1, - result = Array(set.size); +function isValidJws(string) { + return JWS_REGEX.test(string) && !!headerFromJWS(string); +} - set.forEach(function(value) { - result[++index] = [value, value]; - }); - return result; +function jwsVerify(jwsSig, algorithm, secretOrKey) { + if (!algorithm) { + var err = new Error("Missing algorithm parameter for jws.verify"); + err.code = "MISSING_ALGORITHM"; + throw err; } + jwsSig = toString(jwsSig); + var signature = signatureFromJWS(jwsSig); + var securedInput = securedInputFromJWS(jwsSig); + var algo = jwa(algorithm); + return algo.verify(securedInput, signature, secretOrKey); +} - /** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; +function jwsDecode(jwsSig, opts) { + opts = opts || {}; + jwsSig = toString(jwsSig); - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; - } + if (!isValidJws(jwsSig)) + return null; - /** - * A specialized version of `_.lastIndexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function strictLastIndexOf(array, value, fromIndex) { - var index = fromIndex + 1; - while (index--) { - if (array[index] === value) { - return index; - } - } - return index; - } + var header = headerFromJWS(jwsSig); - /** - * Gets the number of symbols in `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the string size. - */ - function stringSize(string) { - return hasUnicode(string) - ? unicodeSize(string) - : asciiSize(string); - } + if (!header) + return null; - /** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); - } + var payload = payloadFromJWS(jwsSig); + if (header.typ === 'JWT' || opts.json) + payload = JSON.parse(payload, opts.encoding); - /** - * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace - * character of `string`. - * - * @private - * @param {string} string The string to inspect. - * @returns {number} Returns the index of the last non-whitespace character. - */ - function trimmedEndIndex(string) { - var index = string.length; + return { + header: header, + payload: payload, + signature: signatureFromJWS(jwsSig) + }; +} - while (index-- && reWhitespace.test(string.charAt(index))) {} - return index; +function VerifyStream(opts) { + opts = opts || {}; + var secretOrKey = opts.secret||opts.publicKey||opts.key; + var secretStream = new DataStream(secretOrKey); + this.readable = true; + this.algorithm = opts.algorithm; + this.encoding = opts.encoding; + this.secret = this.publicKey = this.key = secretStream; + this.signature = new DataStream(opts.signature); + this.secret.once('close', function () { + if (!this.signature.writable && this.readable) + this.verify(); + }.bind(this)); + + this.signature.once('close', function () { + if (!this.secret.writable && this.readable) + this.verify(); + }.bind(this)); +} +util.inherits(VerifyStream, Stream); +VerifyStream.prototype.verify = function verify() { + try { + var valid = jwsVerify(this.signature.buffer, this.algorithm, this.key.buffer); + var obj = jwsDecode(this.signature.buffer, this.encoding); + this.emit('done', valid, obj); + this.emit('data', valid); + this.emit('end'); + this.readable = false; + return valid; + } catch (e) { + this.readable = false; + this.emit('error', e); + this.emit('close'); } +}; - /** - * Used by `_.unescape` to convert HTML entities to characters. - * - * @private - * @param {string} chr The matched character to unescape. - * @returns {string} Returns the unescaped character. - */ - var unescapeHtmlChar = basePropertyOf(htmlUnescapes); +VerifyStream.decode = jwsDecode; +VerifyStream.isValid = isValidJws; +VerifyStream.verify = jwsVerify; - /** - * Gets the size of a Unicode `string`. - * - * @private - * @param {string} string The string inspect. - * @returns {number} Returns the string size. - */ - function unicodeSize(string) { - var result = reUnicode.lastIndex = 0; - while (reUnicode.test(string)) { - ++result; - } - return result; - } +module.exports = VerifyStream; - /** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ - function unicodeToArray(string) { - return string.match(reUnicode) || []; - } - /** - * Splits a Unicode `string` into an array of its words. - * - * @private - * @param {string} The string to inspect. - * @returns {Array} Returns the words of `string`. - */ - function unicodeWords(string) { - return string.match(reUnicodeWord) || []; - } +/***/ }), - /*--------------------------------------------------------------------------*/ +/***/ 75978: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** - * Create a new pristine `lodash` function using the `context` object. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Util - * @param {Object} [context=root] The context object. - * @returns {Function} Returns a new `lodash` function. - * @example - * - * _.mixin({ 'foo': _.constant('foo') }); - * - * var lodash = _.runInContext(); - * lodash.mixin({ 'bar': lodash.constant('bar') }); - * - * _.isFunction(_.foo); - * // => true - * _.isFunction(_.bar); - * // => false - * - * lodash.isFunction(lodash.foo); - * // => false - * lodash.isFunction(lodash.bar); - * // => true - * - * // Create a suped-up `defer` in Node.js. - * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; - */ - var runInContext = (function runInContext(context) { - context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); +"use strict"; - /** Built-in constructor references. */ - var Array = context.Array, - Date = context.Date, - Error = context.Error, - Function = context.Function, - Math = context.Math, - Object = context.Object, - RegExp = context.RegExp, - String = context.String, - TypeError = context.TypeError; +const path = __nccwpck_require__(85622); +const fs = __nccwpck_require__(77758); +const stripBom = __nccwpck_require__(88551); +const parseJson = __nccwpck_require__(86615); +const pify = __nccwpck_require__(64810); - /** Used for built-in method references. */ - var arrayProto = Array.prototype, - funcProto = Function.prototype, - objectProto = Object.prototype; +const parse = (data, filePath, options = {}) => { + data = stripBom(data); - /** Used to detect overreaching core-js shims. */ - var coreJsData = context['__core-js_shared__']; + if (typeof options.beforeParse === 'function') { + data = options.beforeParse(data); + } - /** Used to resolve the decompiled source of functions. */ - var funcToString = funcProto.toString; + return parseJson(data, options.reviver, path.relative(process.cwd(), filePath)); +}; - /** Used to check objects for own properties. */ - var hasOwnProperty = objectProto.hasOwnProperty; +const loadJsonFile = (filePath, options) => pify(fs.readFile)(filePath, 'utf8').then(data => parse(data, filePath, options)); - /** Used to generate unique IDs. */ - var idCounter = 0; +module.exports = loadJsonFile; +// TODO: Remove this for the next major release +module.exports.default = loadJsonFile; +module.exports.sync = (filePath, options) => parse(fs.readFileSync(filePath, 'utf8'), filePath, options); - /** Used to detect methods masquerading as native. */ - var maskSrcKey = (function() { - var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); - return uid ? ('Symbol(src)_1.' + uid) : ''; - }()); - /** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ - var nativeObjectToString = objectProto.toString; +/***/ }), - /** Used to infer the `Object` constructor. */ - var objectCtorString = funcToString.call(Object); +/***/ 63447: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - /** Used to restore the original `_` reference in `_.noConflict`. */ - var oldDash = root._; +"use strict"; - /** Used to detect if a method is native. */ - var reIsNative = RegExp('^' + - funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') - .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' - ); +const path = __nccwpck_require__(85622); +const pathExists = __nccwpck_require__(96978); +const pLocate = __nccwpck_require__(90104); - /** Built-in value references. */ - var Buffer = moduleExports ? context.Buffer : undefined, - Symbol = context.Symbol, - Uint8Array = context.Uint8Array, - allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, - getPrototype = overArg(Object.getPrototypeOf, Object), - objectCreate = Object.create, - propertyIsEnumerable = objectProto.propertyIsEnumerable, - splice = arrayProto.splice, - spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, - symIterator = Symbol ? Symbol.iterator : undefined, - symToStringTag = Symbol ? Symbol.toStringTag : undefined; +module.exports = (iterable, options) => { + options = Object.assign({ + cwd: process.cwd() + }, options); - var defineProperty = (function() { - try { - var func = getNative(Object, 'defineProperty'); - func({}, '', {}); - return func; - } catch (e) {} - }()); + return pLocate(iterable, el => pathExists(path.resolve(options.cwd, el)), options); +}; - /** Mocked built-ins. */ - var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, - ctxNow = Date && Date.now !== root.Date.now && Date.now, - ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; +module.exports.sync = (iterable, options) => { + options = Object.assign({ + cwd: process.cwd() + }, options); - /* Built-in method references for those with the same name as other `lodash` methods. */ - var nativeCeil = Math.ceil, - nativeFloor = Math.floor, - nativeGetSymbols = Object.getOwnPropertySymbols, - nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, - nativeIsFinite = context.isFinite, - nativeJoin = arrayProto.join, - nativeKeys = overArg(Object.keys, Object), - nativeMax = Math.max, - nativeMin = Math.min, - nativeNow = Date.now, - nativeParseInt = context.parseInt, - nativeRandom = Math.random, - nativeReverse = arrayProto.reverse; + for (const el of iterable) { + if (pathExists.sync(path.resolve(options.cwd, el))) { + return el; + } + } +}; - /* Built-in method references that are verified to be native. */ - var DataView = getNative(context, 'DataView'), - Map = getNative(context, 'Map'), - Promise = getNative(context, 'Promise'), - Set = getNative(context, 'Set'), - WeakMap = getNative(context, 'WeakMap'), - nativeCreate = getNative(Object, 'create'); - /** Used to store function metadata. */ - var metaMap = WeakMap && new WeakMap; +/***/ }), - /** Used to lookup unminified function names. */ - var realNames = {}; +/***/ 11289: +/***/ ((module) => { - /** Used to detect maps, sets, and weakmaps. */ - var dataViewCtorString = toSource(DataView), - mapCtorString = toSource(Map), - promiseCtorString = toSource(Promise), - setCtorString = toSource(Set), - weakMapCtorString = toSource(WeakMap); +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** Used to convert symbols to primitives and strings. */ - var symbolProto = Symbol ? Symbol.prototype : undefined, - symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, - symbolToString = symbolProto ? symbolProto.toString : undefined; +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - /*------------------------------------------------------------------------*/ +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; - /** - * Creates a `lodash` object which wraps `value` to enable implicit method - * chain sequences. Methods that operate on and return arrays, collections, - * and functions can be chained together. Methods that retrieve a single value - * or may return a primitive value will automatically end the chain sequence - * and return the unwrapped value. Otherwise, the value must be unwrapped - * with `_#value`. - * - * Explicit chain sequences, which must be unwrapped with `_#value`, may be - * enabled using `_.chain`. - * - * The execution of chained methods is lazy, that is, it's deferred until - * `_#value` is implicitly or explicitly called. - * - * Lazy evaluation allows several methods to support shortcut fusion. - * Shortcut fusion is an optimization to merge iteratee calls; this avoids - * the creation of intermediate arrays and can greatly reduce the number of - * iteratee executions. Sections of a chain sequence qualify for shortcut - * fusion if the section is applied to an array and iteratees accept only - * one argument. The heuristic for whether a section qualifies for shortcut - * fusion is subject to change. - * - * Chaining is supported in custom builds as long as the `_#value` method is - * directly or indirectly included in the build. - * - * In addition to lodash methods, wrappers have `Array` and `String` methods. - * - * The wrapper `Array` methods are: - * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` - * - * The wrapper `String` methods are: - * `replace` and `split` - * - * The wrapper methods that support shortcut fusion are: - * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, - * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, - * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` - * - * The chainable wrapper methods are: - * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, - * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, - * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, - * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, - * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, - * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, - * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, - * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, - * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, - * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, - * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, - * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, - * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, - * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, - * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, - * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, - * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, - * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, - * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, - * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, - * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, - * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, - * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, - * `zipObject`, `zipObjectDeep`, and `zipWith` - * - * The wrapper methods that are **not** chainable by default are: - * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, - * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, - * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, - * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, - * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, - * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, - * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, - * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, - * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, - * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, - * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, - * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, - * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, - * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, - * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, - * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, - * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, - * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, - * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, - * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, - * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, - * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, - * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, - * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, - * `upperFirst`, `value`, and `words` - * - * @name _ - * @constructor - * @category Seq - * @param {*} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } - * - * var wrapped = _([1, 2, 3]); - * - * // Returns an unwrapped value. - * wrapped.reduce(_.add); - * // => 6 - * - * // Returns a wrapped value. - * var squares = wrapped.map(square); - * - * _.isArray(squares); - * // => false - * - * _.isArray(squares.value()); - * // => true - */ - function lodash(value) { - if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { - if (value instanceof LodashWrapper) { - return value; - } - if (hasOwnProperty.call(value, '__wrapped__')) { - return wrapperClone(value); - } - } - return new LodashWrapper(value); - } +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} proto The object to inherit from. - * @returns {Object} Returns the new object. - */ - var baseCreate = (function() { - function object() {} - return function(proto) { - if (!isObject(proto)) { - return {}; - } - if (objectCreate) { - return objectCreate(proto); - } - object.prototype = proto; - var result = new object; - object.prototype = undefined; - return result; - }; - }()); +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} - /** - * The function whose prototype chain sequence wrappers inherit from. - * - * @private - */ - function baseLodash() { - // No operation performed. - } +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); - /** - * The base constructor for creating `lodash` wrapper objects. - * - * @private - * @param {*} value The value to wrap. - * @param {boolean} [chainAll] Enable explicit method chain sequences. - */ - function LodashWrapper(value, chainAll) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__chain__ = !!chainAll; - this.__index__ = 0; - this.__values__ = undefined; - } + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} - /** - * By default, the template delimiters used by lodash are like those in - * embedded Ruby (ERB) as well as ES2015 template strings. Change the - * following template settings to use alternative delimiters. - * - * @static - * @memberOf _ - * @type {Object} - */ - lodash.templateSettings = { +/** Used for built-in method references. */ +var objectProto = Object.prototype; - /** - * Used to detect `data` property values to be HTML-escaped. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'escape': reEscape, +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - /** - * Used to detect code to be evaluated. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'evaluate': reEvaluate, +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - /** - * Used to detect `data` property values to inject. - * - * @memberOf _.templateSettings - * @type {RegExp} - */ - 'interpolate': reInterpolate, +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; - /** - * Used to reference the data object in the template text. - * - * @memberOf _.templateSettings - * @type {string} - */ - 'variable': '', +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax = Math.max; - /** - * Used to import variables into the compiled template. - * - * @memberOf _.templateSettings - * @type {Object} - */ - 'imports': { +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; - /** - * A reference to the `lodash` function. - * - * @memberOf _.templateSettings.imports - * @type {Function} - */ - '_': lodash - } - }; + var length = result.length, + skipIndexes = !!length; - // Ensure wrappers are instances of `baseLodash`. - lodash.prototype = baseLodash.prototype; - lodash.prototype.constructor = lodash; + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); + } + } + return result; +} - LodashWrapper.prototype = baseCreate(baseLodash.prototype); - LodashWrapper.prototype.constructor = LodashWrapper; +/** + * Used by `_.defaults` to customize its `_.assignIn` use. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ +function assignInDefaults(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; +} - /*------------------------------------------------------------------------*/ +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + object[key] = value; + } +} - /** - * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. - * - * @private - * @constructor - * @param {*} value The value to wrap. - */ - function LazyWrapper(value) { - this.__wrapped__ = value; - this.__actions__ = []; - this.__dir__ = 1; - this.__filtered__ = false; - this.__iteratees__ = []; - this.__takeCount__ = MAX_ARRAY_LENGTH; - this.__views__ = []; - } +/** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; - /** - * Creates a clone of the lazy wrapper object. - * - * @private - * @name clone - * @memberOf LazyWrapper - * @returns {Object} Returns the cloned `LazyWrapper` object. - */ - function lazyClone() { - var result = new LazyWrapper(this.__wrapped__); - result.__actions__ = copyArray(this.__actions__); - result.__dir__ = this.__dir__; - result.__filtered__ = this.__filtered__; - result.__iteratees__ = copyArray(this.__iteratees__); - result.__takeCount__ = this.__takeCount__; - result.__views__ = copyArray(this.__views__); - return result; + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); } + } + return result; +} - /** - * Reverses the direction of lazy iteration. - * - * @private - * @name reverse - * @memberOf LazyWrapper - * @returns {Object} Returns the new reversed `LazyWrapper` object. - */ - function lazyReverse() { - if (this.__filtered__) { - var result = new LazyWrapper(this); - result.__dir__ = -1; - result.__filtered__ = true; - } else { - result = this.clone(); - result.__dir__ *= -1; - } - return result; +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; } + otherArgs[start] = array; + return apply(func, this, otherArgs); + }; +} - /** - * Extracts the unwrapped value from its lazy wrapper. - * - * @private - * @name value - * @memberOf LazyWrapper - * @returns {*} Returns the unwrapped value. - */ - function lazyValue() { - var array = this.__wrapped__.value(), - dir = this.__dir__, - isArr = isArray(array), - isRight = dir < 0, - arrLength = isArr ? array.length : 0, - view = getView(0, arrLength, this.__views__), - start = view.start, - end = view.end, - length = end - start, - index = isRight ? end : (start - 1), - iteratees = this.__iteratees__, - iterLength = iteratees.length, - resIndex = 0, - takeCount = nativeMin(length, this.__takeCount__); +/** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ +function copyObject(source, props, object, customizer) { + object || (object = {}); - if (!isArr || (!isRight && arrLength == length && takeCount == length)) { - return baseWrapperValue(array, this.__actions__); - } - var result = []; + var index = -1, + length = props.length; - outer: - while (length-- && resIndex < takeCount) { - index += dir; + while (++index < length) { + var key = props[index]; - var iterIndex = -1, - value = array[index]; + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; - while (++iterIndex < iterLength) { - var data = iteratees[iterIndex], - iteratee = data.iteratee, - type = data.type, - computed = iteratee(value); + assignValue(object, key, newValue === undefined ? source[key] : newValue); + } + return object; +} - if (type == LAZY_MAP_FLAG) { - value = computed; - } else if (!computed) { - if (type == LAZY_FILTER_FLAG) { - continue outer; - } else { - break outer; - } - } - } - result[resIndex++] = value; +/** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ +function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); } - return result; } + return object; + }); +} - // Ensure `LazyWrapper` is an instance of `baseLodash`. - LazyWrapper.prototype = baseCreate(baseLodash.prototype); - LazyWrapper.prototype.constructor = LazyWrapper; +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} - /*------------------------------------------------------------------------*/ +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; +} - /** - * Creates a hash object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Hash(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } + return value === proto; +} - /** - * Removes all key-value entries from the hash. - * - * @private - * @name clear - * @memberOf Hash - */ - function hashClear() { - this.__data__ = nativeCreate ? nativeCreate(null) : {}; - this.size = 0; +/** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); } + } + return result; +} - /** - * Removes `key` and its value from the hash. - * - * @private - * @name delete - * @memberOf Hash - * @param {Object} hash The hash to modify. - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function hashDelete(key) { - var result = this.has(key) && delete this.__data__[key]; - this.size -= result ? 1 : 0; - return result; - } +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} - /** - * Gets the hash value for `key`. - * - * @private - * @name get - * @memberOf Hash - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function hashGet(key) { - var data = this.__data__; - if (nativeCreate) { - var result = data[key]; - return result === HASH_UNDEFINED ? undefined : result; - } - return hasOwnProperty.call(data, key) ? data[key] : undefined; - } +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} - /** - * Checks if a hash value for `key` exists. - * - * @private - * @name has - * @memberOf Hash - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function hashHas(key) { - var data = this.__data__; - return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); - } +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - /** - * Sets the hash `key` to `value`. - * - * @private - * @name set - * @memberOf Hash - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the hash instance. - */ - function hashSet(key, value) { - var data = this.__data__; - this.size += this.has(key) ? 0 : 1; - data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; - return this; - } +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} - // Add methods to `Hash`. - Hash.prototype.clear = hashClear; - Hash.prototype['delete'] = hashDelete; - Hash.prototype.get = hashGet; - Hash.prototype.has = hashHas; - Hash.prototype.set = hashSet; +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} - /*------------------------------------------------------------------------*/ +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} - /** - * Creates an list cache object. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function ListCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - /** - * Removes all key-value entries from the list cache. - * - * @private - * @name clear - * @memberOf ListCache - */ - function listCacheClear() { - this.__data__ = []; - this.size = 0; - } +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - /** - * Removes `key` and its value from the list cache. - * - * @private - * @name delete - * @memberOf ListCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function listCacheDelete(key) { - var data = this.__data__, - index = assocIndexOf(data, key); +/** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); +}); - if (index < 0) { - return false; - } - var lastIndex = data.length - 1; - if (index == lastIndex) { - data.pop(); - } else { - splice.call(data, index, 1); - } - --this.size; - return true; - } +/** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var defaults = baseRest(function(args) { + args.push(undefined, assignInDefaults); + return apply(assignInWith, undefined, args); +}); - /** - * Gets the list cache value for `key`. - * - * @private - * @name get - * @memberOf ListCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function listCacheGet(key) { - var data = this.__data__, - index = assocIndexOf(data, key); +/** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ +function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); +} - return index < 0 ? undefined : data[index][1]; - } +module.exports = defaults; - /** - * Checks if a list cache value for `key` exists. - * - * @private - * @name has - * @memberOf ListCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function listCacheHas(key) { - return assocIndexOf(this.__data__, key) > -1; - } - /** - * Sets the list cache `key` to `value`. - * - * @private - * @name set - * @memberOf ListCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the list cache instance. - */ - function listCacheSet(key, value) { - var data = this.__data__, - index = assocIndexOf(data, key); +/***/ }), - if (index < 0) { - ++this.size; - data.push([key, value]); - } else { - data[index][1] = value; - } - return this; - } +/***/ 48919: +/***/ ((module) => { - // Add methods to `ListCache`. - ListCache.prototype.clear = listCacheClear; - ListCache.prototype['delete'] = listCacheDelete; - ListCache.prototype.get = listCacheGet; - ListCache.prototype.has = listCacheHas; - ListCache.prototype.set = listCacheSet; +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /*------------------------------------------------------------------------*/ +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - /** - * Creates a map cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function MapCache(entries) { - var index = -1, - length = entries == null ? 0 : entries.length; +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; - this.clear(); - while (++index < length) { - var entry = entries[index]; - this.set(entry[0], entry[1]); - } - } +/** Detect free variable `global` from Node.js. */ +var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - /** - * Removes all key-value entries from the map. - * - * @private - * @name clear - * @memberOf MapCache - */ - function mapCacheClear() { - this.size = 0; - this.__data__ = { - 'hash': new Hash, - 'map': new (Map || ListCache), - 'string': new Hash - }; - } +/** Detect free variable `self`. */ +var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - /** - * Removes `key` and its value from the map. - * - * @private - * @name delete - * @memberOf MapCache - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function mapCacheDelete(key) { - var result = getMapData(this, key)['delete'](key); - this.size -= result ? 1 : 0; - return result; - } +/** Used as a reference to the global object. */ +var root = freeGlobal || freeSelf || Function('return this')(); - /** - * Gets the map value for `key`. - * - * @private - * @name get - * @memberOf MapCache - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function mapCacheGet(key) { - return getMapData(this, key).get(key); - } +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; - /** - * Checks if a map value for `key` exists. - * - * @private - * @name has - * @memberOf MapCache - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function mapCacheHas(key) { - return getMapData(this, key).has(key); - } + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} - /** - * Sets the map `key` to `value`. - * - * @private - * @name set - * @memberOf MapCache - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the map cache instance. - */ - function mapCacheSet(key, value) { - var data = getMapData(this, key), - size = data.size; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - data.set(key, value); - this.size += data.size == size ? 0 : 1; - return this; - } +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - // Add methods to `MapCache`. - MapCache.prototype.clear = mapCacheClear; - MapCache.prototype['delete'] = mapCacheDelete; - MapCache.prototype.get = mapCacheGet; - MapCache.prototype.has = mapCacheHas; - MapCache.prototype.set = mapCacheSet; +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - /*------------------------------------------------------------------------*/ +/** Built-in value references. */ +var Symbol = root.Symbol, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined; - /** - * - * Creates an array cache object to store unique values. - * - * @private - * @constructor - * @param {Array} [values] The values to cache. - */ - function SetCache(values) { - var index = -1, - length = values == null ? 0 : values.length; +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; - this.__data__ = new MapCache; - while (++index < length) { - this.add(values[index]); + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); } + } else if (!isStrict) { + result[result.length] = value; } + } + return result; +} - /** - * Adds `value` to the array cache. - * - * @private - * @name add - * @memberOf SetCache - * @alias push - * @param {*} value The value to cache. - * @returns {Object} Returns the cache instance. - */ - function setCacheAdd(value) { - this.__data__.set(value, HASH_UNDEFINED); - return this; - } +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ +function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); +} - /** - * Checks if `value` is in the array cache. - * - * @private - * @name has - * @memberOf SetCache - * @param {*} value The value to search for. - * @returns {number} Returns `true` if `value` is found, else `false`. - */ - function setCacheHas(value) { - return this.__data__.has(value); - } +/** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ +function flatten(array) { + var length = array ? array.length : 0; + return length ? baseFlatten(array, 1) : []; +} - // Add methods to `SetCache`. - SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; - SetCache.prototype.has = setCacheHas; +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} - /*------------------------------------------------------------------------*/ +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - /** - * Creates a stack cache object to store key-value pairs. - * - * @private - * @constructor - * @param {Array} [entries] The key-value pairs to cache. - */ - function Stack(entries) { - var data = this.__data__ = new ListCache(entries); - this.size = data.size; - } +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} - /** - * Removes all key-value entries from the stack. - * - * @private - * @name clear - * @memberOf Stack - */ - function stackClear() { - this.__data__ = new ListCache; - this.size = 0; - } +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} - /** - * Removes `key` and its value from the stack. - * - * @private - * @name delete - * @memberOf Stack - * @param {string} key The key of the value to remove. - * @returns {boolean} Returns `true` if the entry was removed, else `false`. - */ - function stackDelete(key) { - var data = this.__data__, - result = data['delete'](key); +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} - this.size = data.size; - return result; - } +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - /** - * Gets the stack value for `key`. - * - * @private - * @name get - * @memberOf Stack - * @param {string} key The key of the value to get. - * @returns {*} Returns the entry value. - */ - function stackGet(key) { - return this.__data__.get(key); - } +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - /** - * Checks if a stack value for `key` exists. - * - * @private - * @name has - * @memberOf Stack - * @param {string} key The key of the entry to check. - * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. - */ - function stackHas(key) { - return this.__data__.has(key); - } +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - /** - * Sets the stack `key` to `value`. - * - * @private - * @name set - * @memberOf Stack - * @param {string} key The key of the value to set. - * @param {*} value The value to set. - * @returns {Object} Returns the stack cache instance. - */ - function stackSet(key, value) { - var data = this.__data__; - if (data instanceof ListCache) { - var pairs = data.__data__; - if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { - pairs.push([key, value]); - this.size = ++data.size; - return this; - } - data = this.__data__ = new MapCache(pairs); - } - data.set(key, value); - this.size = data.size; - return this; - } +module.exports = flatten; - // Add methods to `Stack`. - Stack.prototype.clear = stackClear; - Stack.prototype['delete'] = stackDelete; - Stack.prototype.get = stackGet; - Stack.prototype.has = stackHas; - Stack.prototype.set = stackSet; - /*------------------------------------------------------------------------*/ +/***/ }), - /** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ - function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; +/***/ 17931: +/***/ ((module) => { - for (var key in value) { - if ((inherited || hasOwnProperty.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; - } +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** - * A specialized version of `_.sample` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @returns {*} Returns the random element. - */ - function arraySample(array) { - var length = array.length; - return length ? array[baseRandom(0, length - 1)] : undefined; - } +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; - /** - * A specialized version of `_.sampleSize` for arrays. - * - * @private - * @param {Array} array The array to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function arraySampleSize(array, n) { - return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); - } +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + stringTag = '[object String]', + symbolTag = '[object Symbol]'; - /** - * A specialized version of `_.shuffle` for arrays. - * - * @private - * @param {Array} array The array to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function arrayShuffle(array) { - return shuffleSelf(copyArray(array)); - } +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; - /** - * This function is like `assignValue` except that it doesn't assign - * `undefined` values. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignMergeValue(object, key, value) { - if ((value !== undefined && !eq(object[key], value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - /** - * Assigns `value` to `key` of `object` if the existing value is not equivalent - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function assignValue(object, key, value) { - var objValue = object[key]; - if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || - (value === undefined && !(key in object))) { - baseAssignValue(object, key, value); - } - } +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; - /** - * Gets the index at which the `key` is found in `array` of key-value pairs. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} key The key to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - */ - function assocIndexOf(array, key) { - var length = array.length; - while (length--) { - if (eq(array[length][0], key)) { - return length; - } - } - return -1; - } +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; - /** - * Aggregates elements of `collection` on `accumulator` with keys transformed - * by `iteratee` and values set by `setter`. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform keys. - * @param {Object} accumulator The initial aggregated object. - * @returns {Function} Returns `accumulator`. - */ - function baseAggregator(collection, setter, iteratee, accumulator) { - baseEach(collection, function(value, key, collection) { - setter(accumulator, value, iteratee(value), collection); - }); - return accumulator; - } +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; - /** - * The base implementation of `_.assign` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssign(object, source) { - return object && copyObject(source, keys(source), object); - } +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; - /** - * The base implementation of `_.assignIn` without support for multiple sources - * or `customizer` functions. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @returns {Object} Returns `object`. - */ - function baseAssignIn(object, source) { - return object && copyObject(source, keysIn(source), object); - } +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array ? array.length : 0, + result = Array(length); - /** - * The base implementation of `assignValue` and `assignMergeValue` without - * value checks. - * - * @private - * @param {Object} object The object to modify. - * @param {string} key The key of the property to assign. - * @param {*} value The value to assign. - */ - function baseAssignValue(object, key, value) { - if (key == '__proto__' && defineProperty) { - defineProperty(object, key, { - 'configurable': true, - 'enumerable': true, - 'value': value, - 'writable': true - }); - } else { - object[key] = value; - } - } + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} - /** - * The base implementation of `_.at` without support for individual paths. - * - * @private - * @param {Object} object The object to iterate over. - * @param {string[]} paths The property paths to pick. - * @returns {Array} Returns the picked elements. - */ - function baseAt(object, paths) { - var index = -1, - length = paths.length, - result = Array(length), - skip = object == null; +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); - while (++index < length) { - result[index] = skip ? undefined : get(object, paths[index]); - } - return result; + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; } + } + return -1; +} - /** - * The base implementation of `_.clamp` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. - */ - function baseClamp(number, lower, upper) { - if (number === number) { - if (upper !== undefined) { - number = number <= upper ? number : upper; - } - if (lower !== undefined) { - number = number >= lower ? number : lower; - } - } - return number; +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + if (value !== value) { + return baseFindIndex(array, baseIsNaN, fromIndex); + } + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; } + } + return -1; +} - /** - * The base implementation of `_.clone` and `_.cloneDeep` which tracks - * traversed objects. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} bitmask The bitmask flags. - * 1 - Deep clone - * 2 - Flatten inherited properties - * 4 - Clone symbols - * @param {Function} [customizer] The function to customize cloning. - * @param {string} [key] The key of `value`. - * @param {Object} [object] The parent object of `value`. - * @param {Object} [stack] Tracks traversed objects and their clone counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, bitmask, customizer, key, object, stack) { - var result, - isDeep = bitmask & CLONE_DEEP_FLAG, - isFlat = bitmask & CLONE_FLAT_FLAG, - isFull = bitmask & CLONE_SYMBOLS_FLAG; +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} - if (customizer) { - result = object ? customizer(value, key, object, stack) : customizer(value); - } - if (result !== undefined) { - return result; - } - if (!isObject(value)) { - return value; - } - var isArr = isArray(value); - if (isArr) { - result = initCloneArray(value); - if (!isDeep) { - return copyArray(value, result); - } - } else { - var tag = getTag(value), - isFunc = tag == funcTag || tag == genTag; +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); - if (isBuffer(value)) { - return cloneBuffer(value, isDeep); - } - if (tag == objectTag || tag == argsTag || (isFunc && !object)) { - result = (isFlat || isFunc) ? {} : initCloneObject(value); - if (!isDeep) { - return isFlat - ? copySymbolsIn(value, baseAssignIn(result, value)) - : copySymbols(value, baseAssign(result, value)); - } - } else { - if (!cloneableTags[tag]) { - return object ? value : {}; - } - result = initCloneByTag(value, tag, isDeep); - } - } - // Check for circular references and return its corresponding clone. - stack || (stack = new Stack); - var stacked = stack.get(value); - if (stacked) { - return stacked; - } - stack.set(value, result); + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} - if (isSet(value)) { - value.forEach(function(subValue) { - result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); - }); - } else if (isMap(value)) { - value.forEach(function(subValue, key) { - result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); - }); - } +/** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ +function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); +} - var keysFunc = isFull - ? (isFlat ? getAllKeysIn : getAllKeys) - : (isFlat ? keysIn : keys); +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} - var props = isArr ? undefined : keysFunc(value); - arrayEach(props || value, function(subValue, key) { - if (props) { - key = subValue; - subValue = value[key]; - } - // Recursively populate clone (susceptible to call stack limits). - assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); - }); - return result; - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - /** - * The base implementation of `_.conforms` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property predicates to conform to. - * @returns {Function} Returns the new spec function. - */ - function baseConforms(source) { - var props = keys(source); - return function(object) { - return baseConformsTo(object, source, props); - }; - } +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - /** - * The base implementation of `_.conformsTo` which accepts `props` to check. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. - */ - function baseConformsTo(object, source, props) { - var length = props.length; - if (object == null) { - return !length; - } - object = Object(object); - while (length--) { - var key = props[length], - predicate = source[key], - value = object[key]; +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - if ((value === undefined && !(key in object)) || !predicate(value)) { - return false; - } - } - return true; - } +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; - /** - * The base implementation of `_.delay` and `_.defer` which accepts `args` - * to provide to `func`. - * - * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {Array} args The arguments to provide to `func`. - * @returns {number|Object} Returns the timer id or timeout object. - */ - function baseDelay(func, wait, args) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return setTimeout(function() { func.apply(undefined, args); }, wait); - } +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max; - /** - * The base implementation of methods like `_.difference` without support - * for excluding multiple arrays or iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Array} values The values to exclude. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - */ - function baseDifference(array, values, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - isCommon = true, - length = array.length, - result = [], - valuesLength = values.length; +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + // Safari 9 makes `arguments.length` enumerable in strict mode. + var result = (isArray(value) || isArguments(value)) + ? baseTimes(value.length, String) + : []; - if (!length) { - return result; - } - if (iteratee) { - values = arrayMap(values, baseUnary(iteratee)); - } - if (comparator) { - includes = arrayIncludesWith; - isCommon = false; - } - else if (values.length >= LARGE_ARRAY_SIZE) { - includes = cacheHas; - isCommon = false; - values = new SetCache(values); - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee == null ? value : iteratee(value); + var length = result.length, + skipIndexes = !!length; - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var valuesIndex = valuesLength; - while (valuesIndex--) { - if (values[valuesIndex] === computed) { - continue outer; - } - } - result.push(value); - } - else if (!includes(values, computed, comparator)) { - result.push(value); - } - } - return result; + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && (key == 'length' || isIndex(key, length)))) { + result.push(key); } + } + return result; +} - /** - * The base implementation of `_.forEach` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEach = createBaseEach(baseForOwn); +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} - /** - * The base implementation of `_.forEachRight` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - */ - var baseEachRight = createBaseEach(baseForOwnRight, true); +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + length = length == null ? MAX_SAFE_INTEGER : length; + return !!length && + (typeof value == 'number' || reIsUint.test(value)) && + (value > -1 && value % 1 == 0 && value < length); +} - /** - * The base implementation of `_.every` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if all elements pass the predicate check, - * else `false` - */ - function baseEvery(collection, predicate) { - var result = true; - baseEach(collection, function(value, index, collection) { - result = !!predicate(value, index, collection); - return result; - }); - return result; - } +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - /** - * The base implementation of methods like `_.max` and `_.min` which accepts a - * `comparator` to determine the extremum value. - * - * @private - * @param {Array} array The array to iterate over. - * @param {Function} iteratee The iteratee invoked per iteration. - * @param {Function} comparator The comparator used to compare values. - * @returns {*} Returns the extremum value. - */ - function baseExtremum(array, iteratee, comparator) { - var index = -1, - length = array.length; + return value === proto; +} - while (++index < length) { - var value = array[index], - current = iteratee(value); +/** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ +function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); +} + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} - if (current != null && (computed === undefined - ? (current === current && !isSymbol(current)) - : comparator(current, computed) - )) { - var computed = current, - result = value; - } - } - return result; - } +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - /** - * The base implementation of `_.fill` without an iteratee call guard. - * - * @private - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - */ - function baseFill(array, value, start, end) { - var length = array.length; +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} - start = toInteger(start); - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = (end === undefined || end > length) ? length : toInteger(end); - if (end < 0) { - end += length; - } - end = start > end ? 0 : toLength(end); - while (start < end) { - array[start++] = value; - } - return array; - } +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} - /** - * The base implementation of `_.filter` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - */ - function baseFilter(collection, predicate) { - var result = []; - baseEach(collection, function(value, index, collection) { - if (predicate(value, index, collection)) { - result.push(value); - } - }); - return result; - } +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} - /** - * The base implementation of `_.flatten` with support for restricting flattening. - * - * @private - * @param {Array} array The array to flatten. - * @param {number} depth The maximum recursion depth. - * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. - * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. - * @param {Array} [result=[]] The initial result value. - * @returns {Array} Returns the new flattened array. - */ - function baseFlatten(array, depth, predicate, isStrict, result) { - var index = -1, - length = array.length; +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - predicate || (predicate = isFlattenable); - result || (result = []); +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - while (++index < length) { - var value = array[index]; - if (depth > 0 && predicate(value)) { - if (depth > 1) { - // Recursively flatten arrays (susceptible to call stack limits). - baseFlatten(value, depth - 1, predicate, isStrict, result); - } else { - arrayPush(result, value); - } - } else if (!isStrict) { - result[result.length] = value; - } - } - return result; - } +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - /** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseFor = createBaseFor(); +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +} - /** - * This function is like `baseFor` except that it iterates over properties - * in the opposite order. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ - var baseForRight = createBaseFor(true); +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} - /** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); - } +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} - /** - * The base implementation of `_.forOwnRight` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ - function baseForOwnRight(object, iteratee) { - return object && baseForRight(object, iteratee, keys); - } +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; - /** - * The base implementation of `_.functions` which creates an array of - * `object` function property names filtered from `props`. - * - * @private - * @param {Object} object The object to inspect. - * @param {Array} props The property names to filter. - * @returns {Array} Returns the function names. - */ - function baseFunctions(object, props) { - return arrayFilter(props, function(key) { - return isFunction(object[key]); - }); - } + return result === result ? (remainder ? result - remainder : result) : 0; +} - /** - * The base implementation of `_.get` without support for default values. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @returns {*} Returns the resolved value. - */ - function baseGet(object, path) { - path = castPath(path, object); +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} - var index = 0, - length = path.length; +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} - while (object != null && index < length) { - object = object[toKey(path[index++])]; - } - return (index && index == length) ? object : undefined; - } +/** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ +function values(object) { + return object ? baseValues(object, keys(object)) : []; +} - /** - * The base implementation of `getAllKeys` and `getAllKeysIn` which uses - * `keysFunc` and `symbolsFunc` to get the enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Function} keysFunc The function to get the keys of `object`. - * @param {Function} symbolsFunc The function to get the symbols of `object`. - * @returns {Array} Returns the array of property names and symbols. - */ - function baseGetAllKeys(object, keysFunc, symbolsFunc) { - var result = keysFunc(object); - return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); - } +module.exports = includes; - /** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - return (symToStringTag && symToStringTag in Object(value)) - ? getRawTag(value) - : objectToString(value); - } - /** - * The base implementation of `_.gt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - */ - function baseGt(value, other) { - return value > other; - } +/***/ }), - /** - * The base implementation of `_.has` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHas(object, key) { - return object != null && hasOwnProperty.call(object, key); - } +/***/ 44130: +/***/ ((module) => { - /** - * The base implementation of `_.hasIn` without support for deep paths. - * - * @private - * @param {Object} [object] The object to query. - * @param {Array|string} key The key to check. - * @returns {boolean} Returns `true` if `key` exists, else `false`. - */ - function baseHasIn(object, key) { - return object != null && key in Object(object); - } +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** - * The base implementation of `_.inRange` which doesn't coerce arguments. - * - * @private - * @param {number} number The number to check. - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - */ - function baseInRange(number, start, end) { - return number >= nativeMin(start, end) && number < nativeMax(start, end); - } +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER = 9007199254740991; - /** - * The base implementation of methods like `_.intersection`, without support - * for iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of shared values. - */ - function baseIntersection(arrays, iteratee, comparator) { - var includes = comparator ? arrayIncludesWith : arrayIncludes, - length = arrays[0].length, - othLength = arrays.length, - othIndex = othLength, - caches = Array(othLength), - maxLength = Infinity, - result = []; +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]'; - while (othIndex--) { - var array = arrays[othIndex]; - if (othIndex && iteratee) { - array = arrayMap(array, baseUnary(iteratee)); - } - maxLength = nativeMin(array.length, maxLength); - caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) - ? new SetCache(othIndex && array) - : undefined; - } - array = arrays[0]; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - var index = -1, - seen = caches[0]; +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - outer: - while (++index < length && result.length < maxLength) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - value = (comparator || value !== 0) ? value : 0; - if (!(seen - ? cacheHas(seen, computed) - : includes(result, computed, comparator) - )) { - othIndex = othLength; - while (--othIndex) { - var cache = caches[othIndex]; - if (!(cache - ? cacheHas(cache, computed) - : includes(arrays[othIndex], computed, comparator)) - ) { - continue outer; - } - } - if (seen) { - seen.push(computed); - } - result.push(value); - } - } - return result; - } +/** Built-in value references. */ +var propertyIsEnumerable = objectProto.propertyIsEnumerable; - /** - * The base implementation of `_.invert` and `_.invertBy` which inverts - * `object` with values transformed by `iteratee` and set by `setter`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} setter The function to set `accumulator` values. - * @param {Function} iteratee The iteratee to transform values. - * @param {Object} accumulator The initial inverted object. - * @returns {Function} Returns `accumulator`. - */ - function baseInverter(object, setter, iteratee, accumulator) { - baseForOwn(object, function(value, key, object) { - setter(accumulator, iteratee(value), key, object); - }); - return accumulator; - } +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +function isArguments(value) { + // Safari 8.1 makes `arguments.callee` enumerable in strict mode. + return isArrayLikeObject(value) && hasOwnProperty.call(value, 'callee') && + (!propertyIsEnumerable.call(value, 'callee') || objectToString.call(value) == argsTag); +} - /** - * The base implementation of `_.invoke` without support for individual - * method arguments. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {Array} args The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - */ - function baseInvoke(object, path, args) { - path = castPath(path, object); - object = parent(object, path); - var func = object == null ? object : object[toKey(last(path))]; - return func == null ? undefined : apply(func, object, args); - } +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} - /** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ - function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; - } +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} - /** - * The base implementation of `_.isArrayBuffer` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - */ - function baseIsArrayBuffer(value) { - return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; - } +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 8-9 which returns 'object' for typed array and other constructors. + var tag = isObject(value) ? objectToString.call(value) : ''; + return tag == funcTag || tag == genTag; +} - /** - * The base implementation of `_.isDate` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - */ - function baseIsDate(value) { - return isObjectLike(value) && baseGetTag(value) == dateTag; - } +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; +} - /** - * The base implementation of `_.isEqual` which supports partial comparisons - * and tracks traversed objects. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {boolean} bitmask The bitmask flags. - * 1 - Unordered comparison - * 2 - Partial comparison - * @param {Function} [customizer] The function to customize comparisons. - * @param {Object} [stack] Tracks traversed `value` and `other` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(value, other, bitmask, customizer, stack) { - if (value === other) { - return true; - } - if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { - return value !== value && other !== other; - } - return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); - } +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - /** - * A specialized version of `baseIsEqual` for arrays and objects which performs - * deep comparisons and tracks traversed objects enabling objects with circular - * references to be compared. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} [stack] Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { - var objIsArr = isArray(object), - othIsArr = isArray(other), - objTag = objIsArr ? arrayTag : getTag(object), - othTag = othIsArr ? arrayTag : getTag(other); +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - objTag = objTag == argsTag ? objectTag : objTag; - othTag = othTag == argsTag ? objectTag : othTag; +module.exports = isArguments; - var objIsObj = objTag == objectTag, - othIsObj = othTag == objectTag, - isSameTag = objTag == othTag; - if (isSameTag && isBuffer(object)) { - if (!isBuffer(other)) { - return false; - } - objIsArr = true; - objIsObj = false; - } - if (isSameTag && !objIsObj) { - stack || (stack = new Stack); - return (objIsArr || isTypedArray(object)) - ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) - : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); - } - if (!(bitmask & COMPARE_PARTIAL_FLAG)) { - var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), - othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); +/***/ }), - if (objIsWrapped || othIsWrapped) { - var objUnwrapped = objIsWrapped ? object.value() : object, - othUnwrapped = othIsWrapped ? other.value() : other; +/***/ 16501: +/***/ ((module) => { - stack || (stack = new Stack); - return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); - } - } - if (!isSameTag) { - return false; - } - stack || (stack = new Stack); - return equalObjects(object, other, bitmask, customizer, equalFunc, stack); - } +/** + * lodash 3.0.3 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ - /** - * The base implementation of `_.isMap` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - */ - function baseIsMap(value) { - return isObjectLike(value) && getTag(value) == mapTag; - } +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]'; - /** - * The base implementation of `_.isMatch` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Array} matchData The property names, values, and compare flags to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - */ - function baseIsMatch(object, source, matchData, customizer) { - var index = matchData.length, - length = index, - noCustomizer = !customizer; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - if (object == null) { - return !length; - } - object = Object(object); - while (index--) { - var data = matchData[index]; - if ((noCustomizer && data[2]) - ? data[1] !== object[data[0]] - : !(data[0] in object) - ) { - return false; - } - } - while (++index < length) { - data = matchData[index]; - var key = data[0], - objValue = object[key], - srcValue = data[1]; +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - if (noCustomizer && data[2]) { - if (objValue === undefined && !(key in object)) { - return false; - } - } else { - var stack = new Stack; - if (customizer) { - var result = customizer(objValue, srcValue, key, object, source, stack); - } - if (!(result === undefined - ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) - : result - )) { - return false; - } - } - } - return true; - } +/** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ +function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && objectToString.call(value) == boolTag); +} - /** - * The base implementation of `_.isNative` without bad shim checks. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - */ - function baseIsNative(value) { - if (!isObject(value) || isMasked(value)) { - return false; - } - var pattern = isFunction(value) ? reIsNative : reIsHostCtor; - return pattern.test(toSource(value)); - } +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - /** - * The base implementation of `_.isRegExp` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - */ - function baseIsRegExp(value) { - return isObjectLike(value) && baseGetTag(value) == regexpTag; - } +module.exports = isBoolean; - /** - * The base implementation of `_.isSet` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - */ - function baseIsSet(value) { - return isObjectLike(value) && getTag(value) == setTag; - } - /** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ - function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; - } +/***/ }), - /** - * The base implementation of `_.iteratee`. - * - * @private - * @param {*} [value=_.identity] The value to convert to an iteratee. - * @returns {Function} Returns the iteratee. - */ - function baseIteratee(value) { - // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. - // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. - if (typeof value == 'function') { - return value; - } - if (value == null) { - return identity; - } - if (typeof value == 'object') { - return isArray(value) - ? baseMatchesProperty(value[0], value[1]) - : baseMatches(value); - } - return property(value); - } +/***/ 21441: +/***/ ((module) => { - /** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; - } +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** - * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ - function baseKeysIn(object) { - if (!isObject(object)) { - return nativeKeysIn(object); - } - var isProto = isPrototype(object), - result = []; +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; - for (var key in object) { - if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { - result.push(key); - } - } - return result; - } +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; - /** - * The base implementation of `_.lt` which doesn't coerce arguments. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - */ - function baseLt(value, other) { - return value < other; - } +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; - /** - * The base implementation of `_.map` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ - function baseMap(collection, iteratee) { - var index = -1, - result = isArrayLike(collection) ? Array(collection.length) : []; +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - baseEach(collection, function(value, key, collection) { - result[++index] = iteratee(value, key, collection); - }); - return result; - } +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; - /** - * The base implementation of `_.matches` which doesn't clone `source`. - * - * @private - * @param {Object} source The object of property values to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatches(source) { - var matchData = getMatchData(source); - if (matchData.length == 1 && matchData[0][2]) { - return matchesStrictComparable(matchData[0][0], matchData[0][1]); - } - return function(object) { - return object === source || baseIsMatch(object, source, matchData); - }; - } +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; - /** - * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. - * - * @private - * @param {string} path The path of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. - */ - function baseMatchesProperty(path, srcValue) { - if (isKey(path) && isStrictComparable(srcValue)) { - return matchesStrictComparable(toKey(path), srcValue); - } - return function(object) { - var objValue = get(object, path); - return (objValue === undefined && objValue === srcValue) - ? hasIn(object, path) - : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); - }; - } +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; - /** - * The base implementation of `_.merge` without support for multiple sources. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {number} srcIndex The index of `source`. - * @param {Function} [customizer] The function to customize merged values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMerge(object, source, srcIndex, customizer, stack) { - if (object === source) { - return; - } - baseFor(source, function(srcValue, key) { - stack || (stack = new Stack); - if (isObject(srcValue)) { - baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); - } - else { - var newValue = customizer - ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) - : undefined; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - if (newValue === undefined) { - newValue = srcValue; - } - assignMergeValue(object, key, newValue); - } - }, keysIn); - } +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - /** - * A specialized version of `baseMerge` for arrays and objects which performs - * deep merges and tracks traversed objects enabling objects with circular - * references to be merged. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {string} key The key of the value to merge. - * @param {number} srcIndex The index of `source`. - * @param {Function} mergeFunc The function to merge values. - * @param {Function} [customizer] The function to customize assigned values. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - */ - function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { - var objValue = safeGet(object, key), - srcValue = safeGet(source, key), - stacked = stack.get(srcValue); +/** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ +function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); +} - if (stacked) { - assignMergeValue(object, key, stacked); - return; - } - var newValue = customizer - ? customizer(objValue, srcValue, (key + ''), object, source, stack) - : undefined; +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} + +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - var isCommon = newValue === undefined; +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} - if (isCommon) { - var isArr = isArray(srcValue), - isBuff = !isArr && isBuffer(srcValue), - isTyped = !isArr && !isBuff && isTypedArray(srcValue); +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} - newValue = srcValue; - if (isArr || isBuff || isTyped) { - if (isArray(objValue)) { - newValue = objValue; - } - else if (isArrayLikeObject(objValue)) { - newValue = copyArray(objValue); - } - else if (isBuff) { - isCommon = false; - newValue = cloneBuffer(srcValue, true); - } - else if (isTyped) { - isCommon = false; - newValue = cloneTypedArray(srcValue, true); - } - else { - newValue = []; - } - } - else if (isPlainObject(srcValue) || isArguments(srcValue)) { - newValue = objValue; - if (isArguments(objValue)) { - newValue = toPlainObject(objValue); - } - else if (!isObject(objValue) || isFunction(objValue)) { - newValue = initCloneObject(srcValue); - } - } - else { - isCommon = false; - } - } - if (isCommon) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, newValue); - mergeFunc(newValue, srcValue, srcIndex, customizer, stack); - stack['delete'](srcValue); - } - assignMergeValue(object, key, newValue); - } +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; - /** - * The base implementation of `_.nth` which doesn't coerce arguments. - * - * @private - * @param {Array} array The array to query. - * @param {number} n The index of the element to return. - * @returns {*} Returns the nth element of `array`. - */ - function baseNth(array, n) { - var length = array.length; - if (!length) { - return; - } - n += n < 0 ? length : 0; - return isIndex(n, length) ? array[n] : undefined; - } + return result === result ? (remainder ? result - remainder : result) : 0; +} - /** - * The base implementation of `_.orderBy` without param guards. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. - * @param {string[]} orders The sort orders of `iteratees`. - * @returns {Array} Returns the new sorted array. - */ - function baseOrderBy(collection, iteratees, orders) { - if (iteratees.length) { - iteratees = arrayMap(iteratees, function(iteratee) { - if (isArray(iteratee)) { - return function(value) { - return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); - } - } - return iteratee; - }); - } else { - iteratees = [identity]; - } +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} - var index = -1; - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); +module.exports = isInteger; - var result = baseMap(collection, function(value, key, collection) { - var criteria = arrayMap(iteratees, function(iteratee) { - return iteratee(value); - }); - return { 'criteria': criteria, 'index': ++index, 'value': value }; - }); - return baseSortBy(result, function(object, other) { - return compareMultiple(object, other, orders); - }); - } +/***/ }), - /** - * The base implementation of `_.pick` without support for individual - * property identifiers. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @returns {Object} Returns the new object. - */ - function basePick(object, paths) { - return basePickBy(object, paths, function(value, path) { - return hasIn(object, path); - }); - } +/***/ 40298: +/***/ ((module) => { - /** - * The base implementation of `_.pickBy` without support for iteratee shorthands. - * - * @private - * @param {Object} object The source object. - * @param {string[]} paths The property paths to pick. - * @param {Function} predicate The function invoked per property. - * @returns {Object} Returns the new object. - */ - function basePickBy(object, paths, predicate) { - var index = -1, - length = paths.length, - result = {}; +/** + * lodash 3.0.3 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ - while (++index < length) { - var path = paths[index], - value = baseGet(object, path); +/** `Object#toString` result references. */ +var numberTag = '[object Number]'; - if (predicate(value, path)) { - baseSet(result, castPath(path, object), value); - } - } - return result; - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - /** - * A specialized version of `baseProperty` which supports deep paths. - * - * @private - * @param {Array|string} path The path of the property to get. - * @returns {Function} Returns the new accessor function. - */ - function basePropertyDeep(path) { - return function(object) { - return baseGet(object, path); - }; - } +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - /** - * The base implementation of `_.pullAllBy` without support for iteratee - * shorthands. - * - * @private - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns `array`. - */ - function basePullAll(array, values, iteratee, comparator) { - var indexOf = comparator ? baseIndexOfWith : baseIndexOf, - index = -1, - length = values.length, - seen = array; +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - if (array === values) { - values = copyArray(values); - } - if (iteratee) { - seen = arrayMap(array, baseUnary(iteratee)); - } - while (++index < length) { - var fromIndex = 0, - value = values[index], - computed = iteratee ? iteratee(value) : value; +/** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are classified + * as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ +function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && objectToString.call(value) == numberTag); +} - while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { - if (seen !== array) { - splice.call(seen, fromIndex, 1); - } - splice.call(array, fromIndex, 1); - } - } - return array; - } +module.exports = isNumber; - /** - * The base implementation of `_.pullAt` without support for individual - * indexes or capturing the removed elements. - * - * @private - * @param {Array} array The array to modify. - * @param {number[]} indexes The indexes of elements to remove. - * @returns {Array} Returns `array`. - */ - function basePullAt(array, indexes) { - var length = array ? indexes.length : 0, - lastIndex = length - 1; - while (length--) { - var index = indexes[length]; - if (length == lastIndex || index !== previous) { - var previous = index; - if (isIndex(index)) { - splice.call(array, index, 1); - } else { - baseUnset(array, index); - } - } - } - return array; - } +/***/ }), - /** - * The base implementation of `_.random` without support for returning - * floating-point numbers. - * - * @private - * @param {number} lower The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the random number. - */ - function baseRandom(lower, upper) { - return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); - } +/***/ 25723: +/***/ ((module) => { - /** - * The base implementation of `_.range` and `_.rangeRight` which doesn't - * coerce arguments. - * - * @private - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @param {number} step The value to increment or decrement by. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the range of numbers. - */ - function baseRange(start, end, step, fromRight) { - var index = -1, - length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), - result = Array(length); +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; - } - return result; - } +/** `Object#toString` result references. */ +var objectTag = '[object Object]'; - /** - * The base implementation of `_.repeat` which doesn't coerce arguments. - * - * @private - * @param {string} string The string to repeat. - * @param {number} n The number of times to repeat the string. - * @returns {string} Returns the repeated string. - */ - function baseRepeat(string, n) { - var result = ''; - if (!string || n < 1 || n > MAX_SAFE_INTEGER) { - return result; - } - // Leverage the exponentiation by squaring algorithm for a faster repeat. - // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. - do { - if (n % 2) { - result += string; - } - n = nativeFloor(n / 2); - if (n) { - string += string; - } - } while (n); +/** + * Checks if `value` is a host object in IE < 9. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a host object, else `false`. + */ +function isHostObject(value) { + // Many host objects are `Object` objects that can coerce to strings + // despite having improperly defined `toString` methods. + var result = false; + if (value != null && typeof value.toString != 'function') { + try { + result = !!(value + ''); + } catch (e) {} + } + return result; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} - return result; - } +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto = Object.prototype; - /** - * The base implementation of `_.rest` which doesn't validate or coerce arguments. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - */ - function baseRest(func, start) { - return setToString(overRest(func, start, identity), func + ''); - } +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; - /** - * The base implementation of `_.sample`. - * - * @private - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - */ - function baseSample(collection) { - return arraySample(values(collection)); - } +/** Used to check objects for own properties. */ +var hasOwnProperty = objectProto.hasOwnProperty; - /** - * The base implementation of `_.sampleSize` without param guards. - * - * @private - * @param {Array|Object} collection The collection to sample. - * @param {number} n The number of elements to sample. - * @returns {Array} Returns the random elements. - */ - function baseSampleSize(collection, n) { - var array = values(collection); - return shuffleSelf(array, baseClamp(n, 0, array.length)); - } +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); - /** - * The base implementation of `_.set`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseSet(object, path, value, customizer) { - if (!isObject(object)) { - return object; - } - path = castPath(path, object); +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - var index = -1, - length = path.length, - lastIndex = length - 1, - nested = object; +/** Built-in value references. */ +var getPrototype = overArg(Object.getPrototypeOf, Object); - while (nested != null && ++index < length) { - var key = toKey(path[index]), - newValue = value; +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - if (key === '__proto__' || key === 'constructor' || key === 'prototype') { - return object; - } +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || + objectToString.call(value) != objectTag || isHostObject(value)) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; + return (typeof Ctor == 'function' && + Ctor instanceof Ctor && funcToString.call(Ctor) == objectCtorString); +} - if (index != lastIndex) { - var objValue = nested[key]; - newValue = customizer ? customizer(objValue, key, nested) : undefined; - if (newValue === undefined) { - newValue = isObject(objValue) - ? objValue - : (isIndex(path[index + 1]) ? [] : {}); - } - } - assignValue(nested, key, newValue); - nested = nested[key]; - } - return object; - } +module.exports = isPlainObject; - /** - * The base implementation of `setData` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. - */ - var baseSetData = !metaMap ? identity : function(func, data) { - metaMap.set(func, data); - return func; - }; - /** - * The base implementation of `setToString` without support for hot loop shorting. - * - * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. - */ - var baseSetToString = !defineProperty ? identity : function(func, string) { - return defineProperty(func, 'toString', { - 'configurable': true, - 'enumerable': false, - 'value': constant(string), - 'writable': true - }); - }; +/***/ }), - /** - * The base implementation of `_.shuffle`. - * - * @private - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - */ - function baseShuffle(collection) { - return shuffleSelf(values(collection)); - } +/***/ 25180: +/***/ ((module) => { - /** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ - function baseSlice(array, start, end) { - var index = -1, - length = array.length; +/** + * lodash 4.0.1 (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright 2012-2016 The Dojo Foundation + * Based on Underscore.js 1.8.3 + * Copyright 2009-2016 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + * Available under MIT license + */ - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; +/** `Object#toString` result references. */ +var stringTag = '[object String]'; - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; - } +/** Used for built-in method references. */ +var objectProto = Object.prototype; - /** - * The base implementation of `_.some` without support for iteratee shorthands. - * - * @private - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} predicate The function invoked per iteration. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - */ - function baseSome(collection, predicate) { - var result; +/** + * Used to resolve the [`toStringTag`](http://ecma-international.org/ecma-262/6.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - baseEach(collection, function(value, index, collection) { - result = predicate(value, index, collection); - return !result; - }); - return !!result; - } +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @type Function + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; - /** - * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which - * performs a binary search of `array` to determine the index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ - function baseSortedIndex(array, value, retHighest) { - var low = 0, - high = array == null ? low : array.length; +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { - while (low < high) { - var mid = (low + high) >>> 1, - computed = array[mid]; +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is correctly classified, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && objectToString.call(value) == stringTag); +} - if (computed !== null && !isSymbol(computed) && - (retHighest ? (computed <= value) : (computed < value))) { - low = mid + 1; - } else { - high = mid; - } - } - return high; - } - return baseSortedIndexBy(array, value, identity, retHighest); - } +module.exports = isString; - /** - * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` - * which invokes `iteratee` for `value` and each element of `array` to compute - * their sort ranking. The iteratee is invoked with one argument; (value). - * - * @private - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} iteratee The iteratee invoked per element. - * @param {boolean} [retHighest] Specify returning the highest qualified index. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - */ - function baseSortedIndexBy(array, value, iteratee, retHighest) { - var low = 0, - high = array == null ? 0 : array.length; - if (high === 0) { - return 0; - } - value = iteratee(value); - var valIsNaN = value !== value, - valIsNull = value === null, - valIsSymbol = isSymbol(value), - valIsUndefined = value === undefined; +/***/ }), - while (low < high) { - var mid = nativeFloor((low + high) / 2), - computed = iteratee(array[mid]), - othIsDefined = computed !== undefined, - othIsNull = computed === null, - othIsReflexive = computed === computed, - othIsSymbol = isSymbol(computed); +/***/ 94499: +/***/ ((module) => { - if (valIsNaN) { - var setLow = retHighest || othIsReflexive; - } else if (valIsUndefined) { - setLow = othIsReflexive && (retHighest || othIsDefined); - } else if (valIsNull) { - setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); - } else if (valIsSymbol) { - setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); - } else if (othIsNull || othIsSymbol) { - setLow = false; - } else { - setLow = retHighest ? (computed <= value) : (computed < value); - } - if (setLow) { - low = mid + 1; - } else { - high = mid; - } - } - return nativeMin(high, MAX_ARRAY_INDEX); - } +/** + * lodash (Custom Build) + * Build: `lodash modularize exports="npm" -o ./` + * Copyright jQuery Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ - /** - * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ - function baseSortedUniq(array, iteratee) { - var index = -1, - length = array.length, - resIndex = 0, - result = []; +/** Used as the `TypeError` message for "Functions" methods. */ +var FUNC_ERROR_TEXT = 'Expected a function'; - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; +/** Used as references for various `Number` constants. */ +var INFINITY = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; - if (!index || !eq(computed, seen)) { - var seen = computed; - result[resIndex++] = value === 0 ? 0 : value; - } - } - return result; - } +/** `Object#toString` result references. */ +var symbolTag = '[object Symbol]'; - /** - * The base implementation of `_.toNumber` which doesn't ensure correct - * conversions of binary, hexadecimal, or octal string values. - * - * @private - * @param {*} value The value to process. - * @returns {number} Returns the number. - */ - function baseToNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - return +value; - } +/** Used to match leading and trailing whitespace. */ +var reTrim = /^\s+|\s+$/g; - /** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ - function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; - } +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; - /** - * The base implementation of `_.uniqBy` without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - */ - function baseUniq(array, iteratee, comparator) { - var index = -1, - includes = arrayIncludes, - length = array.length, - isCommon = true, - result = [], - seen = result; +/** Used for built-in method references. */ +var objectProto = Object.prototype; - if (comparator) { - isCommon = false; - includes = arrayIncludesWith; - } - else if (length >= LARGE_ARRAY_SIZE) { - var set = iteratee ? null : createSet(array); - if (set) { - return setToArray(set); - } - isCommon = false; - includes = cacheHas; - seen = new SetCache; - } - else { - seen = iteratee ? [] : result; - } - outer: - while (++index < length) { - var value = array[index], - computed = iteratee ? iteratee(value) : value; +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var objectToString = objectProto.toString; - value = (comparator || value !== 0) ? value : 0; - if (isCommon && computed === computed) { - var seenIndex = seen.length; - while (seenIndex--) { - if (seen[seenIndex] === computed) { - continue outer; - } - } - if (iteratee) { - seen.push(computed); - } - result.push(value); - } - else if (!includes(seen, computed, comparator)) { - if (seen !== result) { - seen.push(computed); - } - result.push(value); - } - } - return result; +/** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ +function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); } - - /** - * The base implementation of `_.unset`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The property path to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. - */ - function baseUnset(object, path) { - path = castPath(path, object); - object = parent(object, path); - return object == null || delete object[toKey(last(path))]; + if (n <= 1) { + func = undefined; } + return result; + }; +} - /** - * The base implementation of `_.update`. - * - * @private - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to update. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize path creation. - * @returns {Object} Returns `object`. - */ - function baseUpdate(object, path, updater, customizer) { - return baseSet(object, path, updater(baseGet(object, path)), customizer); - } +/** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ +function once(func) { + return before(2, func); +} - /** - * The base implementation of methods like `_.dropWhile` and `_.takeWhile` - * without support for iteratee shorthands. - * - * @private - * @param {Array} array The array to query. - * @param {Function} predicate The function invoked per iteration. - * @param {boolean} [isDrop] Specify dropping elements instead of taking them. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the slice of `array`. - */ - function baseWhile(array, predicate, isDrop, fromRight) { - var length = array.length, - index = fromRight ? length : -1; +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return !!value && (type == 'object' || type == 'function'); +} - while ((fromRight ? index-- : ++index < length) && - predicate(array[index], index, array)) {} +/** + * Checks if `value` is object-like. A value is object-like if it's not `null` + * and has a `typeof` result of "object". + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is object-like, else `false`. + * @example + * + * _.isObjectLike({}); + * // => true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return !!value && typeof value == 'object'; +} - return isDrop - ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) - : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); - } +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && objectToString.call(value) == symbolTag); +} - /** - * The base implementation of `wrapperValue` which returns the result of - * performing a sequence of actions on the unwrapped `value`, where each - * successive action is supplied the return value of the previous. - * - * @private - * @param {*} value The unwrapped value. - * @param {Array} actions Actions to perform to resolve the unwrapped value. - * @returns {*} Returns the resolved value. - */ - function baseWrapperValue(value, actions) { - var result = value; - if (result instanceof LazyWrapper) { - result = result.value(); - } - return arrayReduce(actions, function(result, action) { - return action.func.apply(action.thisArg, arrayPush([result], action.args)); - }, result); - } +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY || value === -INFINITY) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} - /** - * The base implementation of methods like `_.xor`, without support for - * iteratee shorthands, that accepts an array of arrays to inspect. - * - * @private - * @param {Array} arrays The arrays to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of values. - */ - function baseXor(arrays, iteratee, comparator) { - var length = arrays.length; - if (length < 2) { - return length ? baseUniq(arrays[0]) : []; - } - var index = -1, - result = Array(length); +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; - while (++index < length) { - var array = arrays[index], - othIndex = -1; + return result === result ? (remainder ? result - remainder : result) : 0; +} - while (++othIndex < length) { - if (othIndex != index) { - result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); - } - } - } - return baseUniq(baseFlatten(result, 1), iteratee, comparator); - } +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = value.replace(reTrim, ''); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN : +value); +} - /** - * This base implementation of `_.zipObject` which assigns values using `assignFunc`. - * - * @private - * @param {Array} props The property identifiers. - * @param {Array} values The property values. - * @param {Function} assignFunc The function to assign values. - * @returns {Object} Returns the new object. - */ - function baseZipObject(props, values, assignFunc) { - var index = -1, - length = props.length, - valsLength = values.length, - result = {}; +module.exports = once; - while (++index < length) { - var value = index < valsLength ? values[index] : undefined; - assignFunc(result, props[index], value); - } - return result; - } - /** - * Casts `value` to an empty array if it's not an array like object. - * - * @private - * @param {*} value The value to inspect. - * @returns {Array|Object} Returns the cast array-like object. - */ - function castArrayLikeObject(value) { - return isArrayLikeObject(value) ? value : []; - } +/***/ }), - /** - * Casts `value` to `identity` if it's not a function. - * - * @private - * @param {*} value The value to inspect. - * @returns {Function} Returns cast function. - */ - function castFunction(value) { - return typeof value == 'function' ? value : identity; - } +/***/ 90250: +/***/ (function(module, exports, __nccwpck_require__) { - /** - * Casts `value` to a path array if it's not one. - * - * @private - * @param {*} value The value to inspect. - * @param {Object} [object] The object to query keys on. - * @returns {Array} Returns the cast property path array. - */ - function castPath(value, object) { - if (isArray(value)) { - return value; - } - return isKey(value, object) ? [value] : stringToPath(toString(value)); - } +/* module decorator */ module = __nccwpck_require__.nmd(module); +/** + * @license + * Lodash + * Copyright OpenJS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */ +;(function() { - /** - * A `baseRest` alias which can be replaced with `identity` by module - * replacement plugins. - * - * @private - * @type {Function} - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - var castRest = baseRest; + /** Used as a safe reference for `undefined` in pre-ES5 environments. */ + var undefined; - /** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ - function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); - } + /** Used as the semantic version number. */ + var VERSION = '4.17.21'; - /** - * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). - * - * @private - * @param {number|Object} id The timer id or timeout object of the timer to clear. - */ - var clearTimeout = ctxClearTimeout || function(id) { - return root.clearTimeout(id); - }; + /** Used as the size to enable large array optimizations. */ + var LARGE_ARRAY_SIZE = 200; + + /** Error message constants. */ + var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.', + FUNC_ERROR_TEXT = 'Expected a function', + INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; + + /** Used to stand-in for `undefined` hash values. */ + var HASH_UNDEFINED = '__lodash_hash_undefined__'; + + /** Used as the maximum memoize cache size. */ + var MAX_MEMOIZE_SIZE = 500; - /** - * Creates a clone of `buffer`. - * - * @private - * @param {Buffer} buffer The buffer to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Buffer} Returns the cloned buffer. - */ - function cloneBuffer(buffer, isDeep) { - if (isDeep) { - return buffer.slice(); - } - var length = buffer.length, - result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + /** Used as the internal argument placeholder. */ + var PLACEHOLDER = '__lodash_placeholder__'; - buffer.copy(result); - return result; - } + /** Used to compose bitmasks for cloning. */ + var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; - /** - * Creates a clone of `arrayBuffer`. - * - * @private - * @param {ArrayBuffer} arrayBuffer The array buffer to clone. - * @returns {ArrayBuffer} Returns the cloned array buffer. - */ - function cloneArrayBuffer(arrayBuffer) { - var result = new arrayBuffer.constructor(arrayBuffer.byteLength); - new Uint8Array(result).set(new Uint8Array(arrayBuffer)); - return result; - } + /** Used to compose bitmasks for value comparisons. */ + var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; - /** - * Creates a clone of `dataView`. - * - * @private - * @param {Object} dataView The data view to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned data view. - */ - function cloneDataView(dataView, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; - return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); - } + /** Used to compose bitmasks for function metadata. */ + var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG = 8, + WRAP_CURRY_RIGHT_FLAG = 16, + WRAP_PARTIAL_FLAG = 32, + WRAP_PARTIAL_RIGHT_FLAG = 64, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG = 256, + WRAP_FLIP_FLAG = 512; - /** - * Creates a clone of `regexp`. - * - * @private - * @param {Object} regexp The regexp to clone. - * @returns {Object} Returns the cloned regexp. - */ - function cloneRegExp(regexp) { - var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); - result.lastIndex = regexp.lastIndex; - return result; - } + /** Used as default options for `_.truncate`. */ + var DEFAULT_TRUNC_LENGTH = 30, + DEFAULT_TRUNC_OMISSION = '...'; - /** - * Creates a clone of the `symbol` object. - * - * @private - * @param {Object} symbol The symbol object to clone. - * @returns {Object} Returns the cloned symbol object. - */ - function cloneSymbol(symbol) { - return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; - } + /** Used to detect hot functions by number of calls within a span of milliseconds. */ + var HOT_COUNT = 800, + HOT_SPAN = 16; - /** - * Creates a clone of `typedArray`. - * - * @private - * @param {Object} typedArray The typed array to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the cloned typed array. - */ - function cloneTypedArray(typedArray, isDeep) { - var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; - return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); - } + /** Used to indicate the type of lazy iteratees. */ + var LAZY_FILTER_FLAG = 1, + LAZY_MAP_FLAG = 2, + LAZY_WHILE_FLAG = 3; - /** - * Compares values to sort them in ascending order. - * - * @private - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {number} Returns the sort order indicator for `value`. - */ - function compareAscending(value, other) { - if (value !== other) { - var valIsDefined = value !== undefined, - valIsNull = value === null, - valIsReflexive = value === value, - valIsSymbol = isSymbol(value); + /** Used as references for various `Number` constants. */ + var INFINITY = 1 / 0, + MAX_SAFE_INTEGER = 9007199254740991, + MAX_INTEGER = 1.7976931348623157e+308, + NAN = 0 / 0; - var othIsDefined = other !== undefined, - othIsNull = other === null, - othIsReflexive = other === other, - othIsSymbol = isSymbol(other); + /** Used as references for the maximum length and index of an array. */ + var MAX_ARRAY_LENGTH = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; - if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || - (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || - (valIsNull && othIsDefined && othIsReflexive) || - (!valIsDefined && othIsReflexive) || - !valIsReflexive) { - return 1; - } - if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || - (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || - (othIsNull && valIsDefined && valIsReflexive) || - (!othIsDefined && valIsReflexive) || - !othIsReflexive) { - return -1; - } - } - return 0; - } + /** Used to associate wrap methods with their bit flags. */ + var wrapFlags = [ + ['ary', WRAP_ARY_FLAG], + ['bind', WRAP_BIND_FLAG], + ['bindKey', WRAP_BIND_KEY_FLAG], + ['curry', WRAP_CURRY_FLAG], + ['curryRight', WRAP_CURRY_RIGHT_FLAG], + ['flip', WRAP_FLIP_FLAG], + ['partial', WRAP_PARTIAL_FLAG], + ['partialRight', WRAP_PARTIAL_RIGHT_FLAG], + ['rearg', WRAP_REARG_FLAG] + ]; - /** - * Used by `_.orderBy` to compare multiple properties of a value to another - * and stable sort them. - * - * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, - * specify an order of "desc" for descending or "asc" for ascending sort order - * of corresponding values. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {boolean[]|string[]} orders The order to sort by for each property. - * @returns {number} Returns the sort order indicator for `object`. - */ - function compareMultiple(object, other, orders) { - var index = -1, - objCriteria = object.criteria, - othCriteria = other.criteria, - length = objCriteria.length, - ordersLength = orders.length; + /** `Object#toString` result references. */ + var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + asyncTag = '[object AsyncFunction]', + boolTag = '[object Boolean]', + dateTag = '[object Date]', + domExcTag = '[object DOMException]', + errorTag = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag = '[object Map]', + numberTag = '[object Number]', + nullTag = '[object Null]', + objectTag = '[object Object]', + promiseTag = '[object Promise]', + proxyTag = '[object Proxy]', + regexpTag = '[object RegExp]', + setTag = '[object Set]', + stringTag = '[object String]', + symbolTag = '[object Symbol]', + undefinedTag = '[object Undefined]', + weakMapTag = '[object WeakMap]', + weakSetTag = '[object WeakSet]'; - while (++index < length) { - var result = compareAscending(objCriteria[index], othCriteria[index]); - if (result) { - if (index >= ordersLength) { - return result; - } - var order = orders[index]; - return result * (order == 'desc' ? -1 : 1); - } - } - // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications - // that causes it, under certain circumstances, to provide the same value for - // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 - // for more details. - // - // This also ensures a stable sort in V8 and other engines. - // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. - return object.index - other.index; - } + var arrayBufferTag = '[object ArrayBuffer]', + dataViewTag = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; - /** - * Creates an array that is the composition of partially applied arguments, - * placeholders, and provided arguments into a single array of arguments. - * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to prepend to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgs(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersLength = holders.length, - leftIndex = -1, - leftLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(leftLength + rangeLength), - isUncurried = !isCurried; + /** Used to match empty string literals in compiled template source. */ + var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - while (++leftIndex < leftLength) { - result[leftIndex] = partials[leftIndex]; - } - while (++argsIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[holders[argsIndex]] = args[argsIndex]; - } - } - while (rangeLength--) { - result[leftIndex++] = args[argsIndex++]; - } - return result; - } + /** Used to match HTML entities and HTML characters. */ + var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g, + reUnescapedHtml = /[&<>"']/g, + reHasEscapedHtml = RegExp(reEscapedHtml.source), + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); - /** - * This function is like `composeArgs` except that the arguments composition - * is tailored for `_.partialRight`. - * - * @private - * @param {Array} args The provided arguments. - * @param {Array} partials The arguments to append to those provided. - * @param {Array} holders The `partials` placeholder indexes. - * @params {boolean} [isCurried] Specify composing for a curried function. - * @returns {Array} Returns the new array of composed arguments. - */ - function composeArgsRight(args, partials, holders, isCurried) { - var argsIndex = -1, - argsLength = args.length, - holdersIndex = -1, - holdersLength = holders.length, - rightIndex = -1, - rightLength = partials.length, - rangeLength = nativeMax(argsLength - holdersLength, 0), - result = Array(rangeLength + rightLength), - isUncurried = !isCurried; + /** Used to match template delimiters. */ + var reEscape = /<%-([\s\S]+?)%>/g, + reEvaluate = /<%([\s\S]+?)%>/g, + reInterpolate = /<%=([\s\S]+?)%>/g; - while (++argsIndex < rangeLength) { - result[argsIndex] = args[argsIndex]; - } - var offset = argsIndex; - while (++rightIndex < rightLength) { - result[offset + rightIndex] = partials[rightIndex]; - } - while (++holdersIndex < holdersLength) { - if (isUncurried || argsIndex < argsLength) { - result[offset + holders[holdersIndex]] = args[argsIndex++]; - } - } - return result; - } + /** Used to match property names within property paths. */ + var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/, + rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; - /** - * Copies the values of `source` to `array`. - * - * @private - * @param {Array} source The array to copy values from. - * @param {Array} [array=[]] The array to copy values to. - * @returns {Array} Returns `array`. - */ - function copyArray(source, array) { - var index = -1, - length = source.length; + /** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ + var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); - array || (array = Array(length)); - while (++index < length) { - array[index] = source[index]; - } - return array; - } + /** Used to match leading whitespace. */ + var reTrimStart = /^\s+/; - /** - * Copies properties of `source` to `object`. - * - * @private - * @param {Object} source The object to copy properties from. - * @param {Array} props The property identifiers to copy. - * @param {Object} [object={}] The object to copy properties to. - * @param {Function} [customizer] The function to customize copied values. - * @returns {Object} Returns `object`. - */ - function copyObject(source, props, object, customizer) { - var isNew = !object; - object || (object = {}); + /** Used to match a single whitespace character. */ + var reWhitespace = /\s/; - var index = -1, - length = props.length; + /** Used to match wrap detail comments. */ + var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/, + reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; - while (++index < length) { - var key = props[index]; + /** Used to match words composed of alphanumeric characters. */ + var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; - var newValue = customizer - ? customizer(object[key], source[key], key, object, source) - : undefined; + /** + * Used to validate the `validate` option in `_.template` variable. + * + * Forbids characters which could potentially change the meaning of the function argument definition: + * - "()," (modification of function parameters) + * - "=" (default value) + * - "[]{}" (destructuring of function parameters) + * - "/" (beginning of a comment) + * - whitespace + */ + var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; - if (newValue === undefined) { - newValue = source[key]; - } - if (isNew) { - baseAssignValue(object, key, newValue); - } else { - assignValue(object, key, newValue); - } - } - return object; - } + /** Used to match backslashes in property paths. */ + var reEscapeChar = /\\(\\)?/g; - /** - * Copies own symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbols(source, object) { - return copyObject(source, getSymbols(source), object); - } + /** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ + var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - /** - * Copies own and inherited symbols of `source` to `object`. - * - * @private - * @param {Object} source The object to copy symbols from. - * @param {Object} [object={}] The object to copy symbols to. - * @returns {Object} Returns `object`. - */ - function copySymbolsIn(source, object) { - return copyObject(source, getSymbolsIn(source), object); - } + /** Used to match `RegExp` flags from their coerced string values. */ + var reFlags = /\w*$/; - /** - * Creates a function like `_.groupBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} [initializer] The accumulator object initializer. - * @returns {Function} Returns the new aggregator function. - */ - function createAggregator(setter, initializer) { - return function(collection, iteratee) { - var func = isArray(collection) ? arrayAggregator : baseAggregator, - accumulator = initializer ? initializer() : {}; + /** Used to detect bad signed hexadecimal string values. */ + var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; - return func(collection, setter, getIteratee(iteratee, 2), accumulator); - }; - } + /** Used to detect binary string values. */ + var reIsBinary = /^0b[01]+$/i; - /** - * Creates a function like `_.assign`. - * - * @private - * @param {Function} assigner The function to assign values. - * @returns {Function} Returns the new assigner function. - */ - function createAssigner(assigner) { - return baseRest(function(object, sources) { - var index = -1, - length = sources.length, - customizer = length > 1 ? sources[length - 1] : undefined, - guard = length > 2 ? sources[2] : undefined; + /** Used to detect host constructors (Safari). */ + var reIsHostCtor = /^\[object .+?Constructor\]$/; - customizer = (assigner.length > 3 && typeof customizer == 'function') - ? (length--, customizer) - : undefined; + /** Used to detect octal string values. */ + var reIsOctal = /^0o[0-7]+$/i; - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - customizer = length < 3 ? undefined : customizer; - length = 1; - } - object = Object(object); - while (++index < length) { - var source = sources[index]; - if (source) { - assigner(object, source, index, customizer); - } - } - return object; - }); - } + /** Used to detect unsigned integer values. */ + var reIsUint = /^(?:0|[1-9]\d*)$/; - /** - * Creates a `baseEach` or `baseEachRight` function. - * - * @private - * @param {Function} eachFunc The function to iterate over a collection. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseEach(eachFunc, fromRight) { - return function(collection, iteratee) { - if (collection == null) { - return collection; - } - if (!isArrayLike(collection)) { - return eachFunc(collection, iteratee); - } - var length = collection.length, - index = fromRight ? length : -1, - iterable = Object(collection); + /** Used to match Latin Unicode letters (excluding mathematical operators). */ + var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; - while ((fromRight ? index-- : ++index < length)) { - if (iteratee(iterable[index], index, iterable) === false) { - break; - } - } - return collection; - }; - } + /** Used to ensure capturing order of template delimiters. */ + var reNoMatch = /($^)/; - /** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ - function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; + /** Used to match unescaped characters in compiled string literals. */ + var reUnescapedString = /['\n\r\u2028\u2029\\]/g; - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; - } + /** Used to compose unicode character classes. */ + var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; - /** - * Creates a function that wraps `func` to invoke it with the optional `this` - * binding of `thisArg`. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createBind(func, bitmask, thisArg) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); + /** Used to compose unicode capture groups. */ + var rsApos = "['\u2019]", + rsAstral = '[' + rsAstralRange + ']', + rsBreak = '[' + rsBreakRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ = '\\u200d'; - function wrapper() { - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return fn.apply(isBind ? thisArg : this, arguments); - } - return wrapper; - } + /** Used to compose unicode regexes. */ + var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', + rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?', + rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', + rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - /** - * Creates a function like `_.lowerFirst`. - * - * @private - * @param {string} methodName The name of the `String` case method to use. - * @returns {Function} Returns the new case function. - */ - function createCaseFirst(methodName) { - return function(string) { - string = toString(string); + /** Used to match apostrophes. */ + var reApos = RegExp(rsApos, 'g'); - var strSymbols = hasUnicode(string) - ? stringToArray(string) - : undefined; + /** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ + var reComboMark = RegExp(rsCombo, 'g'); - var chr = strSymbols - ? strSymbols[0] - : string.charAt(0); + /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ + var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - var trailing = strSymbols - ? castSlice(strSymbols, 1).join('') - : string.slice(1); + /** Used to match complex or compound words. */ + var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', + rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, + rsUpper + '+' + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji + ].join('|'), 'g'); - return chr[methodName]() + trailing; - }; - } + /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ + var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']'); - /** - * Creates a function like `_.camelCase`. - * - * @private - * @param {Function} callback The function to combine each word. - * @returns {Function} Returns the new compounder function. - */ - function createCompounder(callback) { - return function(string) { - return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); - }; - } + /** Used to detect strings that need a more robust regexp to match words. */ + var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; - /** - * Creates a function that produces an instance of `Ctor` regardless of - * whether it was invoked as part of a `new` expression or by `call` or `apply`. - * - * @private - * @param {Function} Ctor The constructor to wrap. - * @returns {Function} Returns the new wrapped function. - */ - function createCtor(Ctor) { - return function() { - // Use a `switch` statement to work with class constructors. See - // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist - // for more details. - var args = arguments; - switch (args.length) { - case 0: return new Ctor; - case 1: return new Ctor(args[0]); - case 2: return new Ctor(args[0], args[1]); - case 3: return new Ctor(args[0], args[1], args[2]); - case 4: return new Ctor(args[0], args[1], args[2], args[3]); - case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); - case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); - case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); - } - var thisBinding = baseCreate(Ctor.prototype), - result = Ctor.apply(thisBinding, args); + /** Used to assign default `context` object properties. */ + var contextProps = [ + 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array', + 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object', + 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array', + 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap', + '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout' + ]; - // Mimic the constructor's `return` behavior. - // See https://es5.github.io/#x13.2.2 for more details. - return isObject(result) ? result : thisBinding; - }; - } + /** Used to make template sourceURLs easier to identify. */ + var templateCounter = -1; - /** - * Creates a function that wraps `func` to enable currying. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {number} arity The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createCurry(func, bitmask, arity) { - var Ctor = createCtor(func); + /** Used to identify `toStringTag` values of typed arrays. */ + var typedArrayTags = {}; + typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = + typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = + typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = + typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = + typedArrayTags[uint32Tag] = true; + typedArrayTags[argsTag] = typedArrayTags[arrayTag] = + typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = + typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = + typedArrayTags[errorTag] = typedArrayTags[funcTag] = + typedArrayTags[mapTag] = typedArrayTags[numberTag] = + typedArrayTags[objectTag] = typedArrayTags[regexpTag] = + typedArrayTags[setTag] = typedArrayTags[stringTag] = + typedArrayTags[weakMapTag] = false; - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length, - placeholder = getHolder(wrapper); + /** Used to identify `toStringTag` values supported by `_.clone`. */ + var cloneableTags = {}; + cloneableTags[argsTag] = cloneableTags[arrayTag] = + cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] = + cloneableTags[boolTag] = cloneableTags[dateTag] = + cloneableTags[float32Tag] = cloneableTags[float64Tag] = + cloneableTags[int8Tag] = cloneableTags[int16Tag] = + cloneableTags[int32Tag] = cloneableTags[mapTag] = + cloneableTags[numberTag] = cloneableTags[objectTag] = + cloneableTags[regexpTag] = cloneableTags[setTag] = + cloneableTags[stringTag] = cloneableTags[symbolTag] = + cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = + cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; + cloneableTags[errorTag] = cloneableTags[funcTag] = + cloneableTags[weakMapTag] = false; - while (index--) { - args[index] = arguments[index]; - } - var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) - ? [] - : replaceHolders(args, placeholder); + /** Used to map Latin Unicode letters to basic Latin letters. */ + var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' + }; - length -= holders.length; - if (length < arity) { - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, undefined, - args, holders, undefined, undefined, arity - length); - } - var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - return apply(fn, this, args); - } - return wrapper; - } + /** Used to map characters to HTML entities. */ + var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' + }; - /** - * Creates a `_.find` or `_.findLast` function. - * - * @private - * @param {Function} findIndexFunc The function to find the collection index. - * @returns {Function} Returns the new find function. - */ - function createFind(findIndexFunc) { - return function(collection, predicate, fromIndex) { - var iterable = Object(collection); - if (!isArrayLike(collection)) { - var iteratee = getIteratee(predicate, 3); - collection = keys(collection); - predicate = function(key) { return iteratee(iterable[key], key, iterable); }; - } - var index = findIndexFunc(collection, predicate, fromIndex); - return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; - }; - } + /** Used to map HTML entities to characters. */ + var htmlUnescapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + ''': "'" + }; - /** - * Creates a `_.flow` or `_.flowRight` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new flow function. - */ - function createFlow(fromRight) { - return flatRest(function(funcs) { - var length = funcs.length, - index = length, - prereq = LodashWrapper.prototype.thru; + /** Used to escape characters for inclusion in compiled string literals. */ + var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' + }; - if (fromRight) { - funcs.reverse(); - } - while (index--) { - var func = funcs[index]; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - if (prereq && !wrapper && getFuncName(func) == 'wrapper') { - var wrapper = new LodashWrapper([], true); - } - } - index = wrapper ? index : length; - while (++index < length) { - func = funcs[index]; + /** Built-in method references without a dependency on `root`. */ + var freeParseFloat = parseFloat, + freeParseInt = parseInt; - var funcName = getFuncName(func), - data = funcName == 'wrapper' ? getData(func) : undefined; + /** Detect free variable `global` from Node.js. */ + var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - if (data && isLaziable(data[0]) && - data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && - !data[4].length && data[9] == 1 - ) { - wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); - } else { - wrapper = (func.length == 1 && isLaziable(func)) - ? wrapper[funcName]() - : wrapper.thru(func); - } - } - return function() { - var args = arguments, - value = args[0]; + /** Detect free variable `self`. */ + var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - if (wrapper && args.length == 1 && isArray(value)) { - return wrapper.plant(value).value(); - } - var index = 0, - result = length ? funcs[index].apply(this, args) : value; + /** Used as a reference to the global object. */ + var root = freeGlobal || freeSelf || Function('return this')(); - while (++index < length) { - result = funcs[index].call(this, result); - } - return result; - }; - }); - } + /** Detect free variable `exports`. */ + var freeExports = true && exports && !exports.nodeType && exports; - /** - * Creates a function that wraps `func` to invoke it with optional `this` - * binding of `thisArg`, partial application, and currying. - * - * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [partialsRight] The arguments to append to those provided - * to the new function. - * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { - var isAry = bitmask & WRAP_ARY_FLAG, - isBind = bitmask & WRAP_BIND_FLAG, - isBindKey = bitmask & WRAP_BIND_KEY_FLAG, - isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), - isFlip = bitmask & WRAP_FLIP_FLAG, - Ctor = isBindKey ? undefined : createCtor(func); + /** Detect free variable `module`. */ + var freeModule = freeExports && "object" == 'object' && module && !module.nodeType && module; - function wrapper() { - var length = arguments.length, - args = Array(length), - index = length; + /** Detect the popular CommonJS extension `module.exports`. */ + var moduleExports = freeModule && freeModule.exports === freeExports; - while (index--) { - args[index] = arguments[index]; - } - if (isCurried) { - var placeholder = getHolder(wrapper), - holdersCount = countHolders(args, placeholder); - } - if (partials) { - args = composeArgs(args, partials, holders, isCurried); - } - if (partialsRight) { - args = composeArgsRight(args, partialsRight, holdersRight, isCurried); - } - length -= holdersCount; - if (isCurried && length < arity) { - var newHolders = replaceHolders(args, placeholder); - return createRecurry( - func, bitmask, createHybrid, wrapper.placeholder, thisArg, - args, newHolders, argPos, ary, arity - length - ); - } - var thisBinding = isBind ? thisArg : this, - fn = isBindKey ? thisBinding[func] : func; + /** Detect free variable `process` from Node.js. */ + var freeProcess = moduleExports && freeGlobal.process; - length = args.length; - if (argPos) { - args = reorder(args, argPos); - } else if (isFlip && length > 1) { - args.reverse(); - } - if (isAry && ary < length) { - args.length = ary; - } - if (this && this !== root && this instanceof wrapper) { - fn = Ctor || createCtor(fn); - } - return fn.apply(thisBinding, args); + /** Used to access faster Node.js helpers. */ + var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule && freeModule.require && freeModule.require('util').types; + + if (types) { + return types; } - return wrapper; - } - /** - * Creates a function like `_.invertBy`. - * - * @private - * @param {Function} setter The function to set accumulator values. - * @param {Function} toIteratee The function to resolve iteratees. - * @returns {Function} Returns the new inverter function. - */ - function createInverter(setter, toIteratee) { - return function(object, iteratee) { - return baseInverter(object, setter, toIteratee(iteratee), {}); - }; - } + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} + }()); + + /* Node.js helper references. */ + var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer, + nodeIsDate = nodeUtil && nodeUtil.isDate, + nodeIsMap = nodeUtil && nodeUtil.isMap, + nodeIsRegExp = nodeUtil && nodeUtil.isRegExp, + nodeIsSet = nodeUtil && nodeUtil.isSet, + nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + + /*--------------------------------------------------------------------------*/ - /** - * Creates a function that performs a mathematical operation on two values. - * - * @private - * @param {Function} operator The function to perform the operation. - * @param {number} [defaultValue] The value used for `undefined` arguments. - * @returns {Function} Returns the new mathematical operation function. - */ - function createMathOperation(operator, defaultValue) { - return function(value, other) { - var result; - if (value === undefined && other === undefined) { - return defaultValue; - } - if (value !== undefined) { - result = value; - } - if (other !== undefined) { - if (result === undefined) { - return other; - } - if (typeof value == 'string' || typeof other == 'string') { - value = baseToString(value); - other = baseToString(other); - } else { - value = baseToNumber(value); - other = baseToNumber(other); - } - result = operator(value, other); - } - return result; - }; + /** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ + function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); } + return func.apply(thisArg, args); + } - /** - * Creates a function like `_.over`. - * - * @private - * @param {Function} arrayFunc The function to iterate over iteratees. - * @returns {Function} Returns the new over function. - */ - function createOver(arrayFunc) { - return flatRest(function(iteratees) { - iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - return baseRest(function(args) { - var thisArg = this; - return arrayFunc(iteratees, function(iteratee) { - return apply(iteratee, thisArg, args); - }); - }); - }); + /** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); } + return accumulator; + } - /** - * Creates the padding for `string` based on `length`. The `chars` string - * is truncated if the number of characters exceeds `length`. - * - * @private - * @param {number} length The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padding for `string`. - */ - function createPadding(length, chars) { - chars = chars === undefined ? ' ' : baseToString(chars); + /** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; - var charsLength = chars.length; - if (charsLength < 2) { - return charsLength ? baseRepeat(chars, length) : chars; + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; } - var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); - return hasUnicode(chars) - ? castSlice(stringToArray(result), 0, length).join('') - : result.slice(0, length); } + return array; + } - /** - * Creates a function that wraps `func` to invoke it with the `this` binding - * of `thisArg` and `partials` prepended to the arguments it receives. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {*} thisArg The `this` binding of `func`. - * @param {Array} partials The arguments to prepend to those provided to - * the new function. - * @returns {Function} Returns the new wrapped function. - */ - function createPartial(func, bitmask, thisArg, partials) { - var isBind = bitmask & WRAP_BIND_FLAG, - Ctor = createCtor(func); - - function wrapper() { - var argsIndex = -1, - argsLength = arguments.length, - leftIndex = -1, - leftLength = partials.length, - args = Array(leftLength + argsLength), - fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + /** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ + function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; - while (++leftIndex < leftLength) { - args[leftIndex] = partials[leftIndex]; - } - while (argsLength--) { - args[leftIndex++] = arguments[++argsIndex]; - } - return apply(fn, isBind ? thisArg : this, args); + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; } - return wrapper; } + return array; + } - /** - * Creates a `_.range` or `_.rangeRight` function. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new range function. - */ - function createRange(fromRight) { - return function(start, end, step) { - if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { - end = step = undefined; - } - // Ensure the sign of `-0` is preserved. - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); - } - step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); - return baseRange(start, end, step, fromRight); - }; + /** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ + function arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } } + return true; + } - /** - * Creates a function that performs a relational operation on two values. - * - * @private - * @param {Function} operator The function to perform the operation. - * @returns {Function} Returns the new relational operation function. - */ - function createRelationalOperation(operator) { - return function(value, other) { - if (!(typeof value == 'string' && typeof other == 'string')) { - value = toNumber(value); - other = toNumber(other); - } - return operator(value, other); - }; + /** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ + function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } } + return result; + } - /** - * Creates a function that wraps `func` to continue currying. - * - * @private - * @param {Function} func The function to wrap. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @param {Function} wrapFunc The function to create the `func` wrapper. - * @param {*} placeholder The placeholder value. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to prepend to those provided to - * the new function. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { - var isCurry = bitmask & WRAP_CURRY_FLAG, - newHolders = isCurry ? holders : undefined, - newHoldersRight = isCurry ? undefined : holders, - newPartials = isCurry ? partials : undefined, - newPartialsRight = isCurry ? undefined : partials; + /** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; + } - bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); - bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + /** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ + function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; - if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { - bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); + while (++index < length) { + if (comparator(value, array[index])) { + return true; } - var newData = [ - func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, - newHoldersRight, argPos, ary, arity - ]; + } + return false; + } - var result = wrapFunc.apply(undefined, newData); - if (isLaziable(func)) { - setData(result, newData); - } - result.placeholder = placeholder; - return setWrapToString(result, func, bitmask); + /** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ + function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); } + return result; + } - /** - * Creates a function like `_.round`. - * - * @private - * @param {string} methodName The name of the `Math` method to use when rounding. - * @returns {Function} Returns the new round function. - */ - function createRound(methodName) { - var func = Math[methodName]; - return function(number, precision) { - number = toNumber(number); - precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); - if (precision && nativeIsFinite(number)) { - // Shift with exponential notation to avoid floating-point issues. - // See [MDN](https://mdn.io/round#Examples) for more details. - var pair = (toString(number) + 'e').split('e'), - value = func(pair[0] + 'e' + (+pair[1] + precision)); + /** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ + function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; - pair = (toString(value) + 'e').split('e'); - return +(pair[0] + 'e' + (+pair[1] - precision)); - } - return func(number); - }; + while (++index < length) { + array[offset + index] = values[index]; } + return array; + } - /** - * Creates a set object of `values`. - * - * @private - * @param {Array} values The values to add to the set. - * @returns {Object} Returns the new set. - */ - var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { - return new Set(values); - }; + /** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; - /** - * Creates a `_.toPairs` or `_.toPairsIn` function. - * - * @private - * @param {Function} keysFunc The function to get the keys of a given object. - * @returns {Function} Returns the new pairs function. - */ - function createToPairs(keysFunc) { - return function(object) { - var tag = getTag(object); - if (tag == mapTag) { - return mapToArray(object); - } - if (tag == setTag) { - return setToPairs(object); - } - return baseToPairs(object, keysFunc(object)); - }; + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); } + return accumulator; + } - /** - * Creates a function that either curries or invokes `func` with optional - * `this` binding and partially applied arguments. - * - * @private - * @param {Function|string} func The function or method name to wrap. - * @param {number} bitmask The bitmask flags. - * 1 - `_.bind` - * 2 - `_.bindKey` - * 4 - `_.curry` or `_.curryRight` of a bound function - * 8 - `_.curry` - * 16 - `_.curryRight` - * 32 - `_.partial` - * 64 - `_.partialRight` - * 128 - `_.rearg` - * 256 - `_.ary` - * 512 - `_.flip` - * @param {*} [thisArg] The `this` binding of `func`. - * @param {Array} [partials] The arguments to be partially applied. - * @param {Array} [holders] The `partials` placeholder indexes. - * @param {Array} [argPos] The argument positions of the new function. - * @param {number} [ary] The arity cap of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new wrapped function. - */ - function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { - var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; - if (!isBindKey && typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - var length = partials ? partials.length : 0; - if (!length) { - bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); - partials = holders = undefined; - } - ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); - arity = arity === undefined ? arity : toInteger(arity); - length -= holders ? holders.length : 0; + /** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ + function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; + } - if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { - var partialsRight = partials, - holdersRight = holders; + /** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ + function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; - partials = holders = undefined; + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; } - var data = isBindKey ? undefined : getData(func); + } + return false; + } - var newData = [ - func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, - argPos, ary, arity - ]; + /** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + var asciiSize = baseProperty('length'); - if (data) { - mergeData(newData, data); - } - func = newData[0]; - bitmask = newData[1]; - thisArg = newData[2]; - partials = newData[3]; - holders = newData[4]; - arity = newData[9] = newData[9] === undefined - ? (isBindKey ? 0 : func.length) - : nativeMax(newData[9] - length, 0); + /** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function asciiToArray(string) { + return string.split(''); + } - if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { - bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); - } - if (!bitmask || bitmask == WRAP_BIND_FLAG) { - var result = createBind(func, bitmask, thisArg); - } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { - result = createCurry(func, bitmask, arity); - } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { - result = createPartial(func, bitmask, thisArg, partials); - } else { - result = createHybrid.apply(undefined, newData); + /** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function asciiWords(string) { + return string.match(reAsciiWord) || []; + } + + /** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ + function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; } - var setter = data ? baseSetData : setData; - return setWrapToString(setter(result, newData), func, bitmask); - } + }); + return result; + } - /** - * Used by `_.defaults` to customize its `_.assignIn` use to assign properties - * of source objects to the destination object for all destination properties - * that resolve to `undefined`. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to assign. - * @param {Object} object The parent object of `objValue`. - * @returns {*} Returns the value to assign. - */ - function customDefaultsAssignIn(objValue, srcValue, key, object) { - if (objValue === undefined || - (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { - return srcValue; + /** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; } - return objValue; } + return -1; + } - /** - * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source - * objects into destination objects that are passed thru. - * - * @private - * @param {*} objValue The destination value. - * @param {*} srcValue The source value. - * @param {string} key The key of the property to merge. - * @param {Object} object The parent object of `objValue`. - * @param {Object} source The parent object of `srcValue`. - * @param {Object} [stack] Tracks traversed source values and their merged - * counterparts. - * @returns {*} Returns the value to assign. - */ - function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { - if (isObject(objValue) && isObject(srcValue)) { - // Recursively merge objects and arrays (susceptible to call stack limits). - stack.set(srcValue, objValue); - baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); - stack['delete'](srcValue); + /** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); + } + + /** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; } - return objValue; } + return -1; + } - /** - * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain - * objects. - * - * @private - * @param {*} value The value to inspect. - * @param {string} key The key of the property to inspect. - * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. - */ - function customOmitClone(value) { - return isPlainObject(value) ? undefined : value; - } + /** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ + function baseIsNaN(value) { + return value !== value; + } - /** - * A specialized version of `baseIsEqualDeep` for arrays with support for - * partial deep comparisons. - * - * @private - * @param {Array} array The array to compare. - * @param {Array} other The other array to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `array` and `other` objects. - * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. - */ - function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - arrLength = array.length, - othLength = other.length; + /** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ + function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? (baseSum(array, iteratee) / length) : NAN; + } - if (arrLength != othLength && !(isPartial && othLength > arrLength)) { - return false; - } - // Check that cyclic values are equal. - var arrStacked = stack.get(array); - var othStacked = stack.get(other); - if (arrStacked && othStacked) { - return arrStacked == other && othStacked == array; - } - var index = -1, - result = true, - seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + /** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ + function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; + } - stack.set(array, other); - stack.set(other, array); + /** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ + function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; + } - // Ignore non-index properties. - while (++index < arrLength) { - var arrValue = array[index], - othValue = other[index]; + /** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ + function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; + } - if (customizer) { - var compared = isPartial - ? customizer(othValue, arrValue, index, other, array, stack) - : customizer(arrValue, othValue, index, array, other, stack); - } - if (compared !== undefined) { - if (compared) { - continue; - } - result = false; - break; - } - // Recursively compare arrays (susceptible to call stack limits). - if (seen) { - if (!arraySome(other, function(othValue, othIndex) { - if (!cacheHas(seen, othIndex) && - (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { - return seen.push(othIndex); - } - })) { - result = false; - break; - } - } else if (!( - arrValue === othValue || - equalFunc(arrValue, othValue, bitmask, customizer, stack) - )) { - result = false; - break; - } + /** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ + function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; + } + + /** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ + function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; + + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); } - stack['delete'](array); - stack['delete'](other); - return result; } + return result; + } - /** - * A specialized version of `baseIsEqualDeep` for comparing objects of - * the same `toStringTag`. - * - * **Note:** This function only supports comparing values with tags of - * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {string} tag The `toStringTag` of the objects to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { - switch (tag) { - case dataViewTag: - if ((object.byteLength != other.byteLength) || - (object.byteOffset != other.byteOffset)) { - return false; - } - object = object.buffer; - other = other.buffer; + /** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ + function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); - case arrayBufferTag: - if ((object.byteLength != other.byteLength) || - !equalFunc(new Uint8Array(object), new Uint8Array(other))) { - return false; - } - return true; + while (++index < n) { + result[index] = iteratee(index); + } + return result; + } - case boolTag: - case dateTag: - case numberTag: - // Coerce booleans to `1` or `0` and dates to milliseconds. - // Invalid dates are coerced to `NaN`. - return eq(+object, +other); + /** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ + function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); + } - case errorTag: - return object.name == other.name && object.message == other.message; + /** + * The base implementation of `_.trim`. + * + * @private + * @param {string} string The string to trim. + * @returns {string} Returns the trimmed string. + */ + function baseTrim(string) { + return string + ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart, '') + : string; + } - case regexpTag: - case stringTag: - // Coerce regexes to strings and treat strings, primitives and objects, - // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring - // for more details. - return object == (other + ''); + /** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ + function baseUnary(func) { + return function(value) { + return func(value); + }; + } - case mapTag: - var convert = mapToArray; + /** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ + function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); + } + + /** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ + function cacheHas(cache, key) { + return cache.has(key); + } + + /** + * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the first unmatched string symbol. + */ + function charsStartIndex(strSymbols, chrSymbols) { + var index = -1, + length = strSymbols.length; + + while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } - case setTag: - var isPartial = bitmask & COMPARE_PARTIAL_FLAG; - convert || (convert = setToArray); + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol + * that is not found in the character symbols. + * + * @private + * @param {Array} strSymbols The string symbols to inspect. + * @param {Array} chrSymbols The character symbols to find. + * @returns {number} Returns the index of the last unmatched string symbol. + */ + function charsEndIndex(strSymbols, chrSymbols) { + var index = strSymbols.length; - if (object.size != other.size && !isPartial) { - return false; - } - // Assume cyclic values are equal. - var stacked = stack.get(object); - if (stacked) { - return stacked == other; - } - bitmask |= COMPARE_UNORDERED_FLAG; + while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} + return index; + } - // Recursively compare objects (susceptible to call stack limits). - stack.set(object, other); - var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); - stack['delete'](object); - return result; + /** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ + function countHolders(array, placeholder) { + var length = array.length, + result = 0; - case symbolTag: - if (symbolValueOf) { - return symbolValueOf.call(object) == symbolValueOf.call(other); - } + while (length--) { + if (array[length] === placeholder) { + ++result; } - return false; } + return result; + } - /** - * A specialized version of `baseIsEqualDeep` for objects with support for - * partial deep comparisons. - * - * @private - * @param {Object} object The object to compare. - * @param {Object} other The other object to compare. - * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. - * @param {Function} customizer The function to customize comparisons. - * @param {Function} equalFunc The function to determine equivalents of values. - * @param {Object} stack Tracks traversed `object` and `other` objects. - * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. - */ - function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { - var isPartial = bitmask & COMPARE_PARTIAL_FLAG, - objProps = getAllKeys(object), - objLength = objProps.length, - othProps = getAllKeys(other), - othLength = othProps.length; + /** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ + var deburrLetter = basePropertyOf(deburredLetters); - if (objLength != othLength && !isPartial) { - return false; - } - var index = objLength; - while (index--) { - var key = objProps[index]; - if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { - return false; - } - } - // Check that cyclic values are equal. - var objStacked = stack.get(object); - var othStacked = stack.get(other); - if (objStacked && othStacked) { - return objStacked == other && othStacked == object; - } - var result = true; - stack.set(object, other); - stack.set(other, object); + /** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + var escapeHtmlChar = basePropertyOf(htmlEscapes); - var skipCtor = isPartial; - while (++index < objLength) { - key = objProps[index]; - var objValue = object[key], - othValue = other[key]; + /** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ + function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; + } - if (customizer) { - var compared = isPartial - ? customizer(othValue, objValue, key, other, object, stack) - : customizer(objValue, othValue, key, object, other, stack); - } - // Recursively compare objects (susceptible to call stack limits). - if (!(compared === undefined - ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) - : compared - )) { - result = false; - break; - } - skipCtor || (skipCtor = key == 'constructor'); - } - if (result && !skipCtor) { - var objCtor = object.constructor, - othCtor = other.constructor; + /** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ + function getValue(object, key) { + return object == null ? undefined : object[key]; + } - // Non `Object` object instances with different constructors are not equal. - if (objCtor != othCtor && - ('constructor' in object && 'constructor' in other) && - !(typeof objCtor == 'function' && objCtor instanceof objCtor && - typeof othCtor == 'function' && othCtor instanceof othCtor)) { - result = false; - } - } - stack['delete'](object); - stack['delete'](other); - return result; - } + /** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ + function hasUnicode(string) { + return reHasUnicode.test(string); + } - /** - * A specialized version of `baseRest` which flattens the rest array. - * - * @private - * @param {Function} func The function to apply a rest parameter to. - * @returns {Function} Returns the new function. - */ - function flatRest(func) { - return setToString(overRest(func, undefined, flatten), func + ''); - } + /** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ + function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); + } - /** - * Creates an array of own enumerable property names and symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeys(object) { - return baseGetAllKeys(object, keys, getSymbols); - } + /** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ + function iteratorToArray(iterator) { + var data, + result = []; - /** - * Creates an array of own and inherited enumerable property names and - * symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names and symbols. - */ - function getAllKeysIn(object) { - return baseGetAllKeys(object, keysIn, getSymbolsIn); + while (!(data = iterator.next()).done) { + result.push(data.value); } + return result; + } - /** - * Gets metadata for `func`. - * - * @private - * @param {Function} func The function to query. - * @returns {*} Returns the metadata for `func`. - */ - var getData = !metaMap ? noop : function(func) { - return metaMap.get(func); + /** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ + function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; + } + + /** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ + function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); }; + } - /** - * Gets the name of `func`. - * - * @private - * @param {Function} func The function to query. - * @returns {string} Returns the function name. - */ - function getFuncName(func) { - var result = (func.name + ''), - array = realNames[result], - length = hasOwnProperty.call(realNames, result) ? array.length : 0; + /** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ + function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; - while (length--) { - var data = array[length], - otherFunc = data.func; - if (otherFunc == null || otherFunc == func) { - return data.name; - } + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER) { + array[index] = PLACEHOLDER; + result[resIndex++] = index; } - return result; } + return result; + } - /** - * Gets the argument placeholder value for `func`. - * - * @private - * @param {Function} func The function to inspect. - * @returns {*} Returns the placeholder value. - */ - function getHolder(func) { - var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; - return object.placeholder; - } + /** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ + function setToArray(set) { + var index = -1, + result = Array(set.size); - /** - * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, - * this function returns the custom method, otherwise it returns `baseIteratee`. - * If arguments are provided, the chosen function is invoked with them and - * its result is returned. - * - * @private - * @param {*} [value] The value to convert to an iteratee. - * @param {number} [arity] The arity of the created iteratee. - * @returns {Function} Returns the chosen function or its result. - */ - function getIteratee() { - var result = lodash.iteratee || iteratee; - result = result === iteratee ? baseIteratee : result; - return arguments.length ? result(arguments[0], arguments[1]) : result; - } + set.forEach(function(value) { + result[++index] = value; + }); + return result; + } - /** - * Gets the data for `map`. - * - * @private - * @param {Object} map The map to query. - * @param {string} key The reference key. - * @returns {*} Returns the map data. - */ - function getMapData(map, key) { - var data = map.__data__; - return isKeyable(key) - ? data[typeof key == 'string' ? 'string' : 'hash'] - : data.map; - } + /** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ + function setToPairs(set) { + var index = -1, + result = Array(set.size); - /** - * Gets the property names, values, and compare flags of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the match data of `object`. - */ - function getMatchData(object) { - var result = keys(object), - length = result.length; + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; + } - while (length--) { - var key = result[length], - value = object[key]; + /** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; - result[length] = [key, value, isStrictComparable(value)]; + while (++index < length) { + if (array[index] === value) { + return index; } - return result; } + return -1; + } - /** - * Gets the native function at `key` of `object`. - * - * @private - * @param {Object} object The object to query. - * @param {string} key The key of the method to get. - * @returns {*} Returns the function if it's native, else `undefined`. - */ - function getNative(object, key) { - var value = getValue(object, key); - return baseIsNative(value) ? value : undefined; + /** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } } + return index; + } - /** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ - function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag), - tag = value[symToStringTag]; + /** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ + function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); + } - try { - value[symToStringTag] = undefined; - var unmasked = true; - } catch (e) {} + /** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); + } - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag] = tag; - } else { - delete value[symToStringTag]; - } - } - return result; + /** + * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace + * character of `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the index of the last non-whitespace character. + */ + function trimmedEndIndex(string) { + var index = string.length; + + while (index-- && reWhitespace.test(string.charAt(index))) {} + return index; + } + + /** + * Used by `_.unescape` to convert HTML entities to characters. + * + * @private + * @param {string} chr The matched character to unescape. + * @returns {string} Returns the unescaped character. + */ + var unescapeHtmlChar = basePropertyOf(htmlUnescapes); + + /** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ + function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; } + return result; + } - /** - * Creates an array of the own enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbols = !nativeGetSymbols ? stubArray : function(object) { - if (object == null) { - return []; - } - object = Object(object); - return arrayFilter(nativeGetSymbols(object), function(symbol) { - return propertyIsEnumerable.call(object, symbol); - }); - }; - - /** - * Creates an array of the own and inherited enumerable symbols of `object`. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of symbols. - */ - var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { - var result = []; - while (object) { - arrayPush(result, getSymbols(object)); - object = getPrototype(object); - } - return result; - }; + /** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ + function unicodeToArray(string) { + return string.match(reUnicode) || []; + } - /** - * Gets the `toStringTag` of `value`. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ - var getTag = baseGetTag; + /** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ + function unicodeWords(string) { + return string.match(reUnicodeWord) || []; + } - // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. - if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || - (Map && getTag(new Map) != mapTag) || - (Promise && getTag(Promise.resolve()) != promiseTag) || - (Set && getTag(new Set) != setTag) || - (WeakMap && getTag(new WeakMap) != weakMapTag)) { - getTag = function(value) { - var result = baseGetTag(value), - Ctor = result == objectTag ? value.constructor : undefined, - ctorString = Ctor ? toSource(Ctor) : ''; + /*--------------------------------------------------------------------------*/ - if (ctorString) { - switch (ctorString) { - case dataViewCtorString: return dataViewTag; - case mapCtorString: return mapTag; - case promiseCtorString: return promiseTag; - case setCtorString: return setTag; - case weakMapCtorString: return weakMapTag; - } - } - return result; - }; - } + /** + * Create a new pristine `lodash` function using the `context` object. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Util + * @param {Object} [context=root] The context object. + * @returns {Function} Returns a new `lodash` function. + * @example + * + * _.mixin({ 'foo': _.constant('foo') }); + * + * var lodash = _.runInContext(); + * lodash.mixin({ 'bar': lodash.constant('bar') }); + * + * _.isFunction(_.foo); + * // => true + * _.isFunction(_.bar); + * // => false + * + * lodash.isFunction(lodash.foo); + * // => false + * lodash.isFunction(lodash.bar); + * // => true + * + * // Create a suped-up `defer` in Node.js. + * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer; + */ + var runInContext = (function runInContext(context) { + context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps)); - /** - * Gets the view, applying any `transforms` to the `start` and `end` positions. - * - * @private - * @param {number} start The start of the view. - * @param {number} end The end of the view. - * @param {Array} transforms The transformations to apply to the view. - * @returns {Object} Returns an object containing the `start` and `end` - * positions of the view. - */ - function getView(start, end, transforms) { - var index = -1, - length = transforms.length; + /** Built-in constructor references. */ + var Array = context.Array, + Date = context.Date, + Error = context.Error, + Function = context.Function, + Math = context.Math, + Object = context.Object, + RegExp = context.RegExp, + String = context.String, + TypeError = context.TypeError; - while (++index < length) { - var data = transforms[index], - size = data.size; + /** Used for built-in method references. */ + var arrayProto = Array.prototype, + funcProto = Function.prototype, + objectProto = Object.prototype; - switch (data.type) { - case 'drop': start += size; break; - case 'dropRight': end -= size; break; - case 'take': end = nativeMin(end, start + size); break; - case 'takeRight': start = nativeMax(start, end - size); break; - } - } - return { 'start': start, 'end': end }; - } + /** Used to detect overreaching core-js shims. */ + var coreJsData = context['__core-js_shared__']; - /** - * Extracts wrapper details from the `source` body comment. - * - * @private - * @param {string} source The source to inspect. - * @returns {Array} Returns the wrapper details. - */ - function getWrapDetails(source) { - var match = source.match(reWrapDetails); - return match ? match[1].split(reSplitDetails) : []; - } + /** Used to resolve the decompiled source of functions. */ + var funcToString = funcProto.toString; - /** - * Checks if `path` exists on `object`. - * - * @private - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @param {Function} hasFunc The function to check properties. - * @returns {boolean} Returns `true` if `path` exists, else `false`. - */ - function hasPath(object, path, hasFunc) { - path = castPath(path, object); + /** Used to check objects for own properties. */ + var hasOwnProperty = objectProto.hasOwnProperty; - var index = -1, - length = path.length, - result = false; + /** Used to generate unique IDs. */ + var idCounter = 0; - while (++index < length) { - var key = toKey(path[index]); - if (!(result = object != null && hasFunc(object, key))) { - break; - } - object = object[key]; - } - if (result || ++index != length) { - return result; - } - length = object == null ? 0 : object.length; - return !!length && isLength(length) && isIndex(key, length) && - (isArray(object) || isArguments(object)); - } + /** Used to detect methods masquerading as native. */ + var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; + }()); /** - * Initializes an array clone. - * - * @private - * @param {Array} array The array to clone. - * @returns {Array} Returns the initialized clone. + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. */ - function initCloneArray(array) { - var length = array.length, - result = new array.constructor(length); + var nativeObjectToString = objectProto.toString; - // Add properties assigned by `RegExp#exec`. - if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { - result.index = array.index; - result.input = array.input; - } - return result; - } + /** Used to infer the `Object` constructor. */ + var objectCtorString = funcToString.call(Object); - /** - * Initializes an object clone. - * - * @private - * @param {Object} object The object to clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneObject(object) { - return (typeof object.constructor == 'function' && !isPrototype(object)) - ? baseCreate(getPrototype(object)) - : {}; - } + /** Used to restore the original `_` reference in `_.noConflict`. */ + var oldDash = root._; - /** - * Initializes an object clone based on its `toStringTag`. - * - * **Note:** This function only supports cloning values with tags of - * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. - * - * @private - * @param {Object} object The object to clone. - * @param {string} tag The `toStringTag` of the object to clone. - * @param {boolean} [isDeep] Specify a deep clone. - * @returns {Object} Returns the initialized clone. - */ - function initCloneByTag(object, tag, isDeep) { - var Ctor = object.constructor; - switch (tag) { - case arrayBufferTag: - return cloneArrayBuffer(object); + /** Used to detect if a method is native. */ + var reIsNative = RegExp('^' + + funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' + ); - case boolTag: - case dateTag: - return new Ctor(+object); + /** Built-in value references. */ + var Buffer = moduleExports ? context.Buffer : undefined, + Symbol = context.Symbol, + Uint8Array = context.Uint8Array, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined, + getPrototype = overArg(Object.getPrototypeOf, Object), + objectCreate = Object.create, + propertyIsEnumerable = objectProto.propertyIsEnumerable, + splice = arrayProto.splice, + spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined, + symIterator = Symbol ? Symbol.iterator : undefined, + symToStringTag = Symbol ? Symbol.toStringTag : undefined; - case dataViewTag: - return cloneDataView(object, isDeep); + var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} + }()); - case float32Tag: case float64Tag: - case int8Tag: case int16Tag: case int32Tag: - case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: - return cloneTypedArray(object, isDeep); + /** Mocked built-ins. */ + var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout, + ctxNow = Date && Date.now !== root.Date.now && Date.now, + ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout; - case mapTag: - return new Ctor; + /* Built-in method references for those with the same name as other `lodash` methods. */ + var nativeCeil = Math.ceil, + nativeFloor = Math.floor, + nativeGetSymbols = Object.getOwnPropertySymbols, + nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined, + nativeIsFinite = context.isFinite, + nativeJoin = arrayProto.join, + nativeKeys = overArg(Object.keys, Object), + nativeMax = Math.max, + nativeMin = Math.min, + nativeNow = Date.now, + nativeParseInt = context.parseInt, + nativeRandom = Math.random, + nativeReverse = arrayProto.reverse; - case numberTag: - case stringTag: - return new Ctor(object); + /* Built-in method references that are verified to be native. */ + var DataView = getNative(context, 'DataView'), + Map = getNative(context, 'Map'), + Promise = getNative(context, 'Promise'), + Set = getNative(context, 'Set'), + WeakMap = getNative(context, 'WeakMap'), + nativeCreate = getNative(Object, 'create'); - case regexpTag: - return cloneRegExp(object); + /** Used to store function metadata. */ + var metaMap = WeakMap && new WeakMap; - case setTag: - return new Ctor; + /** Used to lookup unminified function names. */ + var realNames = {}; - case symbolTag: - return cloneSymbol(object); - } - } + /** Used to detect maps, sets, and weakmaps. */ + var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map), + promiseCtorString = toSource(Promise), + setCtorString = toSource(Set), + weakMapCtorString = toSource(WeakMap); - /** - * Inserts wrapper `details` in a comment at the top of the `source` body. - * - * @private - * @param {string} source The source to modify. - * @returns {Array} details The details to insert. - * @returns {string} Returns the modified source. - */ - function insertWrapDetails(source, details) { - var length = details.length; - if (!length) { - return source; - } - var lastIndex = length - 1; - details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; - details = details.join(length > 2 ? ', ' : ' '); - return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); - } + /** Used to convert symbols to primitives and strings. */ + var symbolProto = Symbol ? Symbol.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined, + symbolToString = symbolProto ? symbolProto.toString : undefined; - /** - * Checks if `value` is a flattenable `arguments` object or array. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. - */ - function isFlattenable(value) { - return isArray(value) || isArguments(value) || - !!(spreadableSymbol && value && value[spreadableSymbol]); - } + /*------------------------------------------------------------------------*/ /** - * Checks if `value` is a valid array-like index. + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true */ - function isIndex(value, length) { - var type = typeof value; - length = length == null ? MAX_SAFE_INTEGER : length; - - return !!length && - (type == 'number' || - (type != 'symbol' && reIsUint.test(value))) && - (value > -1 && value % 1 == 0 && value < length); + function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); } /** - * Checks if the given arguments are from an iteratee call. + * The base implementation of `_.create` without support for assigning + * properties to the created object. * * @private - * @param {*} value The potential iteratee value argument. - * @param {*} index The potential iteratee index or key argument. - * @param {*} object The potential iteratee object argument. - * @returns {boolean} Returns `true` if the arguments are from an iteratee call, - * else `false`. + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. */ - function isIterateeCall(value, index, object) { - if (!isObject(object)) { - return false; - } - var type = typeof index; - if (type == 'number' - ? (isArrayLike(object) && isIndex(index, object.length)) - : (type == 'string' && index in object) - ) { - return eq(object[index], value); - } - return false; - } + var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; + }()); /** - * Checks if `value` is a property name and not a property path. + * The function whose prototype chain sequence wrappers inherit from. * * @private - * @param {*} value The value to check. - * @param {Object} [object] The object to query keys on. - * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ - function isKey(value, object) { - if (isArray(value)) { - return false; - } - var type = typeof value; - if (type == 'number' || type == 'symbol' || type == 'boolean' || - value == null || isSymbol(value)) { - return true; - } - return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || - (object != null && value in Object(object)); + function baseLodash() { + // No operation performed. } /** - * Checks if `value` is suitable for use as unique object key. + * The base constructor for creating `lodash` wrapper objects. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. */ - function isKeyable(value) { - var type = typeof value; - return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') - ? (value !== '__proto__') - : (value === null); + function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; } /** - * Checks if `func` has a lazy counterpart. + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB) as well as ES2015 template strings. Change the + * following template settings to use alternative delimiters. * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` has a lazy counterpart, - * else `false`. + * @static + * @memberOf _ + * @type {Object} */ - function isLaziable(func) { - var funcName = getFuncName(func), - other = lodash[funcName]; + lodash.templateSettings = { - if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { - return false; - } - if (func === other) { - return true; + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + '_': lodash } - var data = getData(other); - return !!data && func === data[0]; - } + }; - /** - * Checks if `func` has its source masked. - * - * @private - * @param {Function} func The function to check. - * @returns {boolean} Returns `true` if `func` is masked, else `false`. - */ - function isMasked(func) { - return !!maskSrcKey && (maskSrcKey in func); - } + // Ensure wrappers are instances of `baseLodash`. + lodash.prototype = baseLodash.prototype; + lodash.prototype.constructor = lodash; - /** - * Checks if `func` is capable of being masked. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `func` is maskable, else `false`. - */ - var isMaskable = coreJsData ? isFunction : stubFalse; + LodashWrapper.prototype = baseCreate(baseLodash.prototype); + LodashWrapper.prototype.constructor = LodashWrapper; + + /*------------------------------------------------------------------------*/ /** - * Checks if `value` is likely a prototype object. + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + * @constructor + * @param {*} value The value to wrap. */ - function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; - - return value === proto; + function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH; + this.__views__ = []; } /** - * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * Creates a clone of the lazy wrapper object. * * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` if suitable for strict - * equality comparisons, else `false`. + * @name clone + * @memberOf LazyWrapper + * @returns {Object} Returns the cloned `LazyWrapper` object. */ - function isStrictComparable(value) { - return value === value && !isObject(value); + function lazyClone() { + var result = new LazyWrapper(this.__wrapped__); + result.__actions__ = copyArray(this.__actions__); + result.__dir__ = this.__dir__; + result.__filtered__ = this.__filtered__; + result.__iteratees__ = copyArray(this.__iteratees__); + result.__takeCount__ = this.__takeCount__; + result.__views__ = copyArray(this.__views__); + return result; } /** - * A specialized version of `matchesProperty` for source values suitable - * for strict equality comparisons, i.e. `===`. + * Reverses the direction of lazy iteration. * * @private - * @param {string} key The key of the property to get. - * @param {*} srcValue The value to match. - * @returns {Function} Returns the new spec function. + * @name reverse + * @memberOf LazyWrapper + * @returns {Object} Returns the new reversed `LazyWrapper` object. */ - function matchesStrictComparable(key, srcValue) { - return function(object) { - if (object == null) { - return false; - } - return object[key] === srcValue && - (srcValue !== undefined || (key in Object(object))); - }; + function lazyReverse() { + if (this.__filtered__) { + var result = new LazyWrapper(this); + result.__dir__ = -1; + result.__filtered__ = true; + } else { + result = this.clone(); + result.__dir__ *= -1; + } + return result; } /** - * A specialized version of `_.memoize` which clears the memoized function's - * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * Extracts the unwrapped value from its lazy wrapper. * * @private - * @param {Function} func The function to have its output memoized. - * @returns {Function} Returns the new memoized function. + * @name value + * @memberOf LazyWrapper + * @returns {*} Returns the unwrapped value. */ - function memoizeCapped(func) { - var result = memoize(func, function(key) { - if (cache.size === MAX_MEMOIZE_SIZE) { - cache.clear(); - } - return key; - }); + function lazyValue() { + var array = this.__wrapped__.value(), + dir = this.__dir__, + isArr = isArray(array), + isRight = dir < 0, + arrLength = isArr ? array.length : 0, + view = getView(0, arrLength, this.__views__), + start = view.start, + end = view.end, + length = end - start, + index = isRight ? end : (start - 1), + iteratees = this.__iteratees__, + iterLength = iteratees.length, + resIndex = 0, + takeCount = nativeMin(length, this.__takeCount__); - var cache = result.cache; + if (!isArr || (!isRight && arrLength == length && takeCount == length)) { + return baseWrapperValue(array, this.__actions__); + } + var result = []; + + outer: + while (length-- && resIndex < takeCount) { + index += dir; + + var iterIndex = -1, + value = array[index]; + + while (++iterIndex < iterLength) { + var data = iteratees[iterIndex], + iteratee = data.iteratee, + type = data.type, + computed = iteratee(value); + + if (type == LAZY_MAP_FLAG) { + value = computed; + } else if (!computed) { + if (type == LAZY_FILTER_FLAG) { + continue outer; + } else { + break outer; + } + } + } + result[resIndex++] = value; + } return result; } + // Ensure `LazyWrapper` is an instance of `baseLodash`. + LazyWrapper.prototype = baseCreate(baseLodash.prototype); + LazyWrapper.prototype.constructor = LazyWrapper; + + /*------------------------------------------------------------------------*/ + /** - * Merges the function metadata of `source` into `data`. - * - * Merging metadata reduces the number of wrappers used to invoke a function. - * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` - * may be applied regardless of execution order. Methods like `_.ary` and - * `_.rearg` modify function arguments, making the order in which they are - * executed important, preventing the merging of metadata. However, we make - * an exception for a safe combined case where curried functions have `_.ary` - * and or `_.rearg` applied. + * Creates a hash object. * * @private - * @param {Array} data The destination metadata. - * @param {Array} source The source metadata. - * @returns {Array} Returns `data`. + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - function mergeData(data, source) { - var bitmask = data[1], - srcBitmask = source[1], - newBitmask = bitmask | srcBitmask, - isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); - - var isCombo = - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || - ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || - ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); + function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; - // Exit early if metadata can't be merged. - if (!(isCommon || isCombo)) { - return data; - } - // Use source `thisArg` if available. - if (srcBitmask & WRAP_BIND_FLAG) { - data[2] = source[2]; - // Set when currying a bound function. - newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; - } - // Compose partial arguments. - var value = source[3]; - if (value) { - var partials = data[3]; - data[3] = partials ? composeArgs(partials, value, source[4]) : value; - data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; - } - // Compose partial right arguments. - value = source[5]; - if (value) { - partials = data[5]; - data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; - data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; - } - // Use source `argPos` if available. - value = source[7]; - if (value) { - data[7] = value; - } - // Use source `ary` if it's smaller. - if (srcBitmask & WRAP_ARY_FLAG) { - data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); - } - // Use source `arity` if one is not provided. - if (data[9] == null) { - data[9] = source[9]; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } - // Use source `func` and merge bitmasks. - data[0] = source[0]; - data[1] = newBitmask; - - return data; } /** - * This function is like - * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * except that it includes inherited enumerable properties. + * Removes all key-value entries from the hash. * * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. + * @name clear + * @memberOf Hash */ - function nativeKeysIn(object) { - var result = []; - if (object != null) { - for (var key in Object(object)) { - result.push(key); - } - } - return result; + function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; } /** - * Converts `value` to a string using `Object.prototype.toString`. + * Removes `key` and its value from the hash. * * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ - function objectToString(value) { - return nativeObjectToString.call(value); + function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; } /** - * A specialized version of `baseRest` which transforms the rest array. + * Gets the hash value for `key`. * * @private - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @param {Function} transform The rest array transform. - * @returns {Function} Returns the new function. + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - function overRest(func, start, transform) { - start = nativeMax(start === undefined ? (func.length - 1) : start, 0); - return function() { - var args = arguments, - index = -1, - length = nativeMax(args.length - start, 0), - array = Array(length); - - while (++index < length) { - array[index] = args[start + index]; - } - index = -1; - var otherArgs = Array(start + 1); - while (++index < start) { - otherArgs[index] = args[index]; - } - otherArgs[start] = transform(array); - return apply(func, this, otherArgs); - }; + function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED ? undefined : result; + } + return hasOwnProperty.call(data, key) ? data[key] : undefined; } /** - * Gets the parent value at `path` of `object`. + * Checks if a hash value for `key` exists. * * @private - * @param {Object} object The object to query. - * @param {Array} path The path to get the parent value of. - * @returns {*} Returns the parent value. + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ - function parent(object, path) { - return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); + function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key); } /** - * Reorder `array` according to the specified indexes where the element at - * the first index is assigned as the first element, the element at - * the second index is assigned as the second element, and so on. + * Sets the hash `key` to `value`. * * @private - * @param {Array} array The array to reorder. - * @param {Array} indexes The arranged array indexes. - * @returns {Array} Returns `array`. + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. */ - function reorder(array, indexes) { - var arrLength = array.length, - length = nativeMin(indexes.length, arrLength), - oldArray = copyArray(array); - - while (length--) { - var index = indexes[length]; - array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; - } - return array; + function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value; + return this; } + // Add methods to `Hash`. + Hash.prototype.clear = hashClear; + Hash.prototype['delete'] = hashDelete; + Hash.prototype.get = hashGet; + Hash.prototype.has = hashHas; + Hash.prototype.set = hashSet; + + /*------------------------------------------------------------------------*/ + /** - * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * Creates an list cache object. * * @private - * @param {Object} object The object to query. - * @param {string} key The key of the property to get. - * @returns {*} Returns the property value. + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - function safeGet(object, key) { - if (key === 'constructor' && typeof object[key] === 'function') { - return; - } + function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; - if (key == '__proto__') { - return; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } - - return object[key]; } /** - * Sets metadata for `func`. - * - * **Note:** If this function becomes hot, i.e. is invoked a lot in a short - * period of time, it will trip its breaker and transition to an identity - * function to avoid garbage collection pauses in V8. See - * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) - * for more details. + * Removes all key-value entries from the list cache. * * @private - * @param {Function} func The function to associate metadata with. - * @param {*} data The metadata. - * @returns {Function} Returns `func`. + * @name clear + * @memberOf ListCache */ - var setData = shortOut(baseSetData); + function listCacheClear() { + this.__data__ = []; + this.size = 0; + } /** - * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). + * Removes `key` and its value from the list cache. * * @private - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @returns {number|Object} Returns the timer id or timeout object. + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ - var setTimeout = ctxSetTimeout || function(func, wait) { - return root.setTimeout(func, wait); - }; + function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice.call(data, index, 1); + } + --this.size; + return true; + } /** - * Sets the `toString` method of `func` to return `string`. + * Gets the list cache value for `key`. * * @private - * @param {Function} func The function to modify. - * @param {Function} string The `toString` result. - * @returns {Function} Returns `func`. + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - var setToString = shortOut(baseSetToString); + function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; + } /** - * Sets the `toString` method of `wrapper` to mimic the source of `reference` - * with wrapper details in a comment at the top of the source body. + * Checks if a list cache value for `key` exists. * * @private - * @param {Function} wrapper The function to modify. - * @param {Function} reference The reference function. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Function} Returns `wrapper`. + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ - function setWrapToString(wrapper, reference, bitmask) { - var source = (reference + ''); - return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; } /** - * Creates a function that'll short out and invoke `identity` instead - * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` - * milliseconds. + * Sets the list cache `key` to `value`. * * @private - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new shortable function. + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. */ - function shortOut(func) { - var count = 0, - lastCalled = 0; - - return function() { - var stamp = nativeNow(), - remaining = HOT_SPAN - (stamp - lastCalled); + function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); - lastCalled = stamp; - if (remaining > 0) { - if (++count >= HOT_COUNT) { - return arguments[0]; - } - } else { - count = 0; - } - return func.apply(undefined, arguments); - }; + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; } + // Add methods to `ListCache`. + ListCache.prototype.clear = listCacheClear; + ListCache.prototype['delete'] = listCacheDelete; + ListCache.prototype.get = listCacheGet; + ListCache.prototype.has = listCacheHas; + ListCache.prototype.set = listCacheSet; + + /*------------------------------------------------------------------------*/ + /** - * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * Creates a map cache object to store key-value pairs. * * @private - * @param {Array} array The array to shuffle. - * @param {number} [size=array.length] The size of `array`. - * @returns {Array} Returns `array`. + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - function shuffleSelf(array, size) { + function MapCache(entries) { var index = -1, - length = array.length, - lastIndex = length - 1; - - size = size === undefined ? length : size; - while (++index < size) { - var rand = baseRandom(index, lastIndex), - value = array[rand]; + length = entries == null ? 0 : entries.length; - array[rand] = array[index]; - array[index] = value; + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); } - array.length = size; - return array; } /** - * Converts `string` to a property path array. + * Removes all key-value entries from the map. * * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the property path array. + * @name clear + * @memberOf MapCache */ - var stringToPath = memoizeCapped(function(string) { - var result = []; - if (string.charCodeAt(0) === 46 /* . */) { - result.push(''); - } - string.replace(rePropName, function(match, number, quote, subString) { - result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); - }); - return result; - }); + function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map || ListCache), + 'string': new Hash + }; + } /** - * Converts `value` to a string key if it's not a string or symbol. + * Removes `key` and its value from the map. * * @private - * @param {*} value The value to inspect. - * @returns {string|symbol} Returns the key. + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ - function toKey(value) { - if (typeof value == 'string' || isSymbol(value)) { - return value; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; + function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; } /** - * Converts `func` to its source code. + * Gets the map value for `key`. * * @private - * @param {Function} func The function to convert. - * @returns {string} Returns the source code. + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - function toSource(func) { - if (func != null) { - try { - return funcToString.call(func); - } catch (e) {} - try { - return (func + ''); - } catch (e) {} - } - return ''; + function mapCacheGet(key) { + return getMapData(this, key).get(key); } /** - * Updates wrapper `details` based on `bitmask` flags. + * Checks if a map value for `key` exists. * * @private - * @returns {Array} details The details to modify. - * @param {number} bitmask The bitmask flags. See `createWrap` for more details. - * @returns {Array} Returns `details`. + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ - function updateWrapDetails(details, bitmask) { - arrayEach(wrapFlags, function(pair) { - var value = '_.' + pair[0]; - if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { - details.push(value); - } - }); - return details.sort(); + function mapCacheHas(key) { + return getMapData(this, key).has(key); } /** - * Creates a clone of `wrapper`. + * Sets the map `key` to `value`. * * @private - * @param {Object} wrapper The wrapper to clone. - * @returns {Object} Returns the cloned wrapper. + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. */ - function wrapperClone(wrapper) { - if (wrapper instanceof LazyWrapper) { - return wrapper.clone(); - } - var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); - result.__actions__ = copyArray(wrapper.__actions__); - result.__index__ = wrapper.__index__; - result.__values__ = wrapper.__values__; - return result; - } + function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; - /*------------------------------------------------------------------------*/ + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; + } - /** - * Creates an array of elements split into groups the length of `size`. - * If `array` can't be split evenly, the final chunk will be the remaining - * elements. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to process. - * @param {number} [size=1] The length of each chunk - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the new array of chunks. - * @example - * - * _.chunk(['a', 'b', 'c', 'd'], 2); - * // => [['a', 'b'], ['c', 'd']] - * - * _.chunk(['a', 'b', 'c', 'd'], 3); - * // => [['a', 'b', 'c'], ['d']] - */ - function chunk(array, size, guard) { - if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { - size = 1; - } else { - size = nativeMax(toInteger(size), 0); - } - var length = array == null ? 0 : array.length; - if (!length || size < 1) { - return []; - } - var index = 0, - resIndex = 0, - result = Array(nativeCeil(length / size)); + // Add methods to `MapCache`. + MapCache.prototype.clear = mapCacheClear; + MapCache.prototype['delete'] = mapCacheDelete; + MapCache.prototype.get = mapCacheGet; + MapCache.prototype.has = mapCacheHas; + MapCache.prototype.set = mapCacheSet; - while (index < length) { - result[resIndex++] = baseSlice(array, index, (index += size)); - } - return result; - } + /*------------------------------------------------------------------------*/ /** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are falsey. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to compact. - * @returns {Array} Returns the new array of filtered values. - * @example + * Creates an array cache object to store unique values. * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] + * @private + * @constructor + * @param {Array} [values] The values to cache. */ - function compact(array) { + function SetCache(values) { var index = -1, - length = array == null ? 0 : array.length, - resIndex = 0, - result = []; + length = values == null ? 0 : values.length; + this.__data__ = new MapCache; while (++index < length) { - var value = array[index]; - if (value) { - result[resIndex++] = value; - } + this.add(values[index]); } - return result; } /** - * Creates a new array concatenating `array` with any additional arrays - * and/or values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to concatenate. - * @param {...*} [values] The values to concatenate. - * @returns {Array} Returns the new concatenated array. - * @example - * - * var array = [1]; - * var other = _.concat(array, 2, [3], [[4]]); - * - * console.log(other); - * // => [1, 2, 3, [4]] + * Adds `value` to the array cache. * - * console.log(array); - * // => [1] + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. */ - function concat() { - var length = arguments.length; - if (!length) { - return []; - } - var args = Array(length - 1), - array = arguments[0], - index = length; - - while (index--) { - args[index - 1] = arguments[index]; - } - return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; } /** - * Creates an array of `array` values not included in the other given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * **Note:** Unlike `_.pullAll`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.without, _.xor - * @example + * Checks if `value` is in the array cache. * - * _.difference([2, 1], [2, 3]); - * // => [1] + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. */ - var difference = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) - : []; - }); + function setCacheHas(value) { + return this.__data__.has(value); + } - /** - * This method is like `_.difference` except that it accepts `iteratee` which - * is invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * **Note:** Unlike `_.pullAllBy`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2] - * - * // The `_.property` iteratee shorthand. - * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] - */ - var differenceBy = baseRest(function(array, values) { - var iteratee = last(values); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) - : []; - }); + // Add methods to `SetCache`. + SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; + SetCache.prototype.has = setCacheHas; - /** - * This method is like `_.difference` except that it accepts `comparator` - * which is invoked to compare elements of `array` to `values`. The order and - * references of result values are determined by the first array. The comparator - * is invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.pullAllWith`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...Array} [values] The values to exclude. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * - * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); - * // => [{ 'x': 2, 'y': 1 }] - */ - var differenceWith = baseRest(function(array, values) { - var comparator = last(values); - if (isArrayLikeObject(comparator)) { - comparator = undefined; - } - return isArrayLikeObject(array) - ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) - : []; - }); + /*------------------------------------------------------------------------*/ /** - * Creates a slice of `array` with `n` elements dropped from the beginning. - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.drop([1, 2, 3]); - * // => [2, 3] - * - * _.drop([1, 2, 3], 2); - * // => [3] - * - * _.drop([1, 2, 3], 5); - * // => [] + * Creates a stack cache object to store key-value pairs. * - * _.drop([1, 2, 3], 0); - * // => [1, 2, 3] + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. */ - function drop(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, n < 0 ? 0 : n, length); + function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; } /** - * Creates a slice of `array` with `n` elements dropped from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to drop. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.dropRight([1, 2, 3]); - * // => [1, 2] - * - * _.dropRight([1, 2, 3], 2); - * // => [1] - * - * _.dropRight([1, 2, 3], 5); - * // => [] + * Removes all key-value entries from the stack. * - * _.dropRight([1, 2, 3], 0); - * // => [1, 2, 3] + * @private + * @name clear + * @memberOf Stack */ - function dropRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, 0, n < 0 ? 0 : n); + function stackClear() { + this.__data__ = new ListCache; + this.size = 0; } /** - * Creates a slice of `array` excluding elements dropped from the end. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.dropRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney'] - * - * // The `_.matches` iteratee shorthand. - * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropRightWhile(users, ['active', false]); - * // => objects for ['barney'] + * Removes `key` and its value from the stack. * - * // The `_.property` iteratee shorthand. - * _.dropRightWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. */ - function dropRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true, true) - : []; + function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; } /** - * Creates a slice of `array` excluding elements dropped from the beginning. - * Elements are dropped until `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.dropWhile(users, function(o) { return !o.active; }); - * // => objects for ['pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.dropWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.dropWhile(users, ['active', false]); - * // => objects for ['pebbles'] + * Gets the stack value for `key`. * - * // The `_.property` iteratee shorthand. - * _.dropWhile(users, 'active'); - * // => objects for ['barney', 'fred', 'pebbles'] + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. */ - function dropWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), true) - : []; + function stackGet(key) { + return this.__data__.get(key); } /** - * Fills elements of `array` with `value` from `start` up to, but not - * including, `end`. - * - * **Note:** This method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Array - * @param {Array} array The array to fill. - * @param {*} value The value to fill `array` with. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3]; - * - * _.fill(array, 'a'); - * console.log(array); - * // => ['a', 'a', 'a'] - * - * _.fill(Array(3), 2); - * // => [2, 2, 2] + * Checks if a stack value for `key` exists. * - * _.fill([4, 6, 8, 10], '*', 1, 3); - * // => [4, '*', '*', 10] + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. */ - function fill(array, value, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { - start = 0; - end = length; - } - return baseFill(array, value, start, end); + function stackHas(key) { + return this.__data__.has(key); } /** - * This method is like `_.find` except that it returns the index of the first - * element `predicate` returns truthy for instead of the element itself. - * - * @static - * @memberOf _ - * @since 1.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.findIndex(users, function(o) { return o.user == 'barney'; }); - * // => 0 - * - * // The `_.matches` iteratee shorthand. - * _.findIndex(users, { 'user': 'fred', 'active': false }); - * // => 1 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findIndex(users, ['active', false]); - * // => 0 + * Sets the stack `key` to `value`. * - * // The `_.property` iteratee shorthand. - * _.findIndex(users, 'active'); - * // => 2 + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. */ - function findIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); + function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); } - return baseFindIndex(array, getIteratee(predicate, 3), index); + data.set(key, value); + this.size = data.size; + return this; } + // Add methods to `Stack`. + Stack.prototype.clear = stackClear; + Stack.prototype['delete'] = stackDelete; + Stack.prototype.get = stackGet; + Stack.prototype.has = stackHas; + Stack.prototype.set = stackSet; + + /*------------------------------------------------------------------------*/ + /** - * This method is like `_.findIndex` except that it iterates over elements - * of `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); - * // => 2 - * - * // The `_.matches` iteratee shorthand. - * _.findLastIndex(users, { 'user': 'barney', 'active': true }); - * // => 0 - * - * // The `_.matchesProperty` iteratee shorthand. - * _.findLastIndex(users, ['active', false]); - * // => 2 + * Creates an array of the enumerable property names of the array-like `value`. * - * // The `_.property` iteratee shorthand. - * _.findLastIndex(users, 'active'); - * // => 0 + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. */ - function findLastIndex(array, predicate, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = length - 1; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = fromIndex < 0 - ? nativeMax(length + index, 0) - : nativeMin(index, length - 1); + function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } } - return baseFindIndex(array, getIteratee(predicate, 3), index, true); + return result; } /** - * Flattens `array` a single level deep. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example + * A specialized version of `_.sample` for arrays. * - * _.flatten([1, [2, [3, [4]], 5]]); - * // => [1, 2, [3, [4]], 5] + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. */ - function flatten(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, 1) : []; + function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; } /** - * Recursively flattens `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to flatten. - * @returns {Array} Returns the new flattened array. - * @example + * A specialized version of `_.sampleSize` for arrays. * - * _.flattenDeep([1, [2, [3, [4]], 5]]); - * // => [1, 2, 3, 4, 5] + * @private + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. */ - function flattenDeep(array) { - var length = array == null ? 0 : array.length; - return length ? baseFlatten(array, INFINITY) : []; + function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); } /** - * Recursively flatten `array` up to `depth` times. - * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Array - * @param {Array} array The array to flatten. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example - * - * var array = [1, [2, [3, [4]], 5]]; + * A specialized version of `_.shuffle` for arrays. * - * _.flattenDepth(array, 1); - * // => [1, 2, [3, [4]], 5] + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. + */ + function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); + } + + /** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. * - * _.flattenDepth(array, 2); - * // => [1, 2, 3, [4], 5] + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. */ - function flattenDepth(array, depth) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; + function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); } - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(array, depth); } /** - * The inverse of `_.toPairs`; this method returns an object composed - * from key-value `pairs`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} pairs The key-value pairs. - * @returns {Object} Returns the new object. - * @example + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. * - * _.fromPairs([['a', 1], ['b', 2]]); - * // => { 'a': 1, 'b': 2 } + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. */ - function fromPairs(pairs) { - var index = -1, - length = pairs == null ? 0 : pairs.length, - result = {}; - - while (++index < length) { - var pair = pairs[index]; - result[pair[0]] = pair[1]; + function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); } - return result; } /** - * Gets the first element of `array`. + * Gets the index at which the `key` is found in `array` of key-value pairs. * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias first - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the first element of `array`. - * @example + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ + function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; + } + + /** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. * - * _.head([1, 2, 3]); - * // => 1 + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ + function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; + } + + /** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. * - * _.head([]); - * // => undefined + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. */ - function head(array) { - return (array && array.length) ? array[0] : undefined; + function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); + } + + /** + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ + function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); } /** - * Gets the index at which the first occurrence of `value` is found in `array` - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. If `fromIndex` is negative, it's used as the - * offset from the end of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.indexOf([1, 2, 1, 2], 2); - * // => 1 + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. * - * // Search from the `fromIndex`. - * _.indexOf([1, 2, 1, 2], 2, 2); - * // => 3 + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. */ - function indexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; - if (!length) { - return -1; - } - var index = fromIndex == null ? 0 : toInteger(fromIndex); - if (index < 0) { - index = nativeMax(length + index, 0); + function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; } - return baseIndexOf(array, value, index); } /** - * Gets all but the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example + * The base implementation of `_.at` without support for individual paths. * - * _.initial([1, 2, 3]); - * // => [1, 2] + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. */ - function initial(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 0, -1) : []; + function baseAt(object, paths) { + var index = -1, + length = paths.length, + result = Array(length), + skip = object == null; + + while (++index < length) { + result[index] = skip ? undefined : get(object, paths[index]); + } + return result; } /** - * Creates an array of unique values that are included in all given arrays - * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. The order and references of result values are - * determined by the first array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of intersecting values. - * @example + * The base implementation of `_.clamp` which doesn't coerce arguments. * - * _.intersection([2, 1], [2, 3]); - * // => [2] + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. */ - var intersection = baseRest(function(arrays) { - var mapped = arrayMap(arrays, castArrayLikeObject); - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped) - : []; - }); + function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; + } /** - * This method is like `_.intersection` except that it accepts `iteratee` - * which is invoked for each element of each `arrays` to generate the criterion - * by which they're compared. The order and references of result values are - * determined by the first array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [2.1] + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. * - * // The `_.property` iteratee shorthand. - * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }] + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. */ - var intersectionBy = baseRest(function(arrays) { - var iteratee = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); + function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG, + isFlat = bitmask & CLONE_FLAT_FLAG, + isFull = bitmask & CLONE_SYMBOLS_FLAG; - if (iteratee === last(mapped)) { - iteratee = undefined; + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } } else { - mapped.pop(); + var tag = getTag(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag || tag == argsTag || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, isDeep); + } } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, getIteratee(iteratee, 2)) - : []; - }); + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (isSet(value)) { + value.forEach(function(subValue) { + result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); + }); + } else if (isMap(value)) { + value.forEach(function(subValue, key) { + result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + } + + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys) + : (isFlat ? keysIn : keys); + + var props = isArr ? undefined : keysFunc(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + return result; + } /** - * This method is like `_.intersection` except that it accepts `comparator` - * which is invoked to compare elements of `arrays`. The order and references - * of result values are determined by the first array. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of intersecting values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * The base implementation of `_.conforms` which doesn't clone `source`. * - * _.intersectionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }] + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. */ - var intersectionWith = baseRest(function(arrays) { - var comparator = last(arrays), - mapped = arrayMap(arrays, castArrayLikeObject); - - comparator = typeof comparator == 'function' ? comparator : undefined; - if (comparator) { - mapped.pop(); - } - return (mapped.length && mapped[0] === arrays[0]) - ? baseIntersection(mapped, undefined, comparator) - : []; - }); + function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; + } /** - * Converts all elements in `array` into a string separated by `separator`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to convert. - * @param {string} [separator=','] The element separator. - * @returns {string} Returns the joined string. - * @example + * The base implementation of `_.conformsTo` which accepts `props` to check. * - * _.join(['a', 'b', 'c'], '~'); - * // => 'a~b~c' + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. */ - function join(array, separator) { - return array == null ? '' : nativeJoin.call(array, separator); + function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } + } + return true; } /** - * Gets the last element of `array`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @returns {*} Returns the last element of `array`. - * @example + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. * - * _.last([1, 2, 3]); - * // => 3 + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. */ - function last(array) { - var length = array == null ? 0 : array.length; - return length ? array[length - 1] : undefined; + function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); } /** - * This method is like `_.indexOf` except that it iterates over elements of - * `array` from right to left. + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array + * @private * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example - * - * _.lastIndexOf([1, 2, 1, 2], 2); - * // => 3 - * - * // Search from the `fromIndex`. - * _.lastIndexOf([1, 2, 1, 2], 2, 2); - * // => 1 + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. */ - function lastIndexOf(array, value, fromIndex) { - var length = array == null ? 0 : array.length; + function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + if (!length) { - return -1; + return result; } - var index = length; - if (fromIndex !== undefined) { - index = toInteger(fromIndex); - index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); } - return value === value - ? strictLastIndexOf(array, value, index) - : baseFindIndex(array, baseIsNaN, index, true); - } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); - /** - * Gets the element at index `n` of `array`. If `n` is negative, the nth - * element from the end is returned. - * - * @static - * @memberOf _ - * @since 4.11.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=0] The index of the element to return. - * @returns {*} Returns the nth element of `array`. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * - * _.nth(array, 1); - * // => 'b' - * - * _.nth(array, -2); - * // => 'c'; - */ - function nth(array, n) { - return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; } /** - * Removes all given values from `array` using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` - * to remove elements from an array by predicate. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...*} [values] The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * The base implementation of `_.forEach` without support for iteratee shorthands. * - * _.pull(array, 'a', 'c'); - * console.log(array); - * // => ['b', 'b'] + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. */ - var pull = baseRest(pullAll); + var baseEach = createBaseEach(baseForOwn); /** - * This method is like `_.pull` except that it accepts an array of values to remove. - * - * **Note:** Unlike `_.difference`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * The base implementation of `_.forEachRight` without support for iteratee shorthands. * - * _.pullAll(array, ['a', 'c']); - * console.log(array); - * // => ['b', 'b'] + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. */ - function pullAll(array, values) { - return (array && array.length && values && values.length) - ? basePullAll(array, values) - : array; - } + var baseEachRight = createBaseEach(baseForOwnRight, true); /** - * This method is like `_.pullAll` except that it accepts `iteratee` which is - * invoked for each element of `array` and `values` to generate the criterion - * by which they're compared. The iteratee is invoked with one argument: (value). - * - * **Note:** Unlike `_.differenceBy`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns `array`. - * @example + * The base implementation of `_.every` without support for iteratee shorthands. * - * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ + function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; + } + + /** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. * - * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); - * console.log(array); - * // => [{ 'x': 2 }] + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. */ - function pullAllBy(array, values, iteratee) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, getIteratee(iteratee, 2)) - : array; + function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; } /** - * This method is like `_.pullAll` except that it accepts `comparator` which - * is invoked to compare elements of `array` to `values`. The comparator is - * invoked with two arguments: (arrVal, othVal). - * - * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * The base implementation of `_.fill` without an iteratee call guard. * - * @static - * @memberOf _ - * @since 4.6.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Array} values The values to remove. - * @param {Function} [comparator] The comparator invoked per element. + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. * @returns {Array} Returns `array`. - * @example - * - * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; - * - * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); - * console.log(array); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ - function pullAllWith(array, values, comparator) { - return (array && array.length && values && values.length) - ? basePullAll(array, values, undefined, comparator) - : array; + function baseFill(array, value, start, end) { + var length = array.length; + + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; } /** - * Removes elements from `array` corresponding to `indexes` and returns an - * array of removed elements. - * - * **Note:** Unlike `_.at`, this method mutates `array`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {...(number|number[])} [indexes] The indexes of elements to remove. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = ['a', 'b', 'c', 'd']; - * var pulled = _.pullAt(array, [1, 3]); - * - * console.log(array); - * // => ['a', 'c'] + * The base implementation of `_.filter` without support for iteratee shorthands. * - * console.log(pulled); - * // => ['b', 'd'] + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. */ - var pullAt = flatRest(function(array, indexes) { - var length = array == null ? 0 : array.length, - result = baseAt(array, indexes); - - basePullAt(array, arrayMap(indexes, function(index) { - return isIndex(index, length) ? +index : index; - }).sort(compareAscending)); - + function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); return result; - }); + } /** - * Removes all elements from `array` that `predicate` returns truthy for - * and returns an array of the removed elements. The predicate is invoked - * with three arguments: (value, index, array). - * - * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` - * to pull elements from an array by value. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Array - * @param {Array} array The array to modify. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new array of removed elements. - * @example - * - * var array = [1, 2, 3, 4]; - * var evens = _.remove(array, function(n) { - * return n % 2 == 0; - * }); - * - * console.log(array); - * // => [1, 3] + * The base implementation of `_.flatten` with support for restricting flattening. * - * console.log(evens); - * // => [2, 4] + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. */ - function remove(array, predicate) { - var result = []; - if (!(array && array.length)) { - return result; - } + function baseFlatten(array, depth, predicate, isStrict, result) { var index = -1, - indexes = [], length = array.length; - predicate = getIteratee(predicate, 3); + predicate || (predicate = isFlattenable); + result || (result = []); + while (++index < length) { var value = array[index]; - if (predicate(value, index, array)) { - result.push(value); - indexes.push(index); + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; } } - basePullAt(array, indexes); return result; } /** - * Reverses `array` so that the first element becomes the last, the second - * element becomes the second to last, and so on. - * - * **Note:** This method mutates `array` and is based on - * [`Array#reverse`](https://mdn.io/Array/reverse). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to modify. - * @returns {Array} Returns `array`. - * @example + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. * - * var array = [1, 2, 3]; + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseFor = createBaseFor(); + + /** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. * - * _.reverse(array); - * // => [3, 2, 1] + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ + var baseForRight = createBaseFor(true); + + /** + * The base implementation of `_.forOwn` without support for iteratee shorthands. * - * console.log(array); - * // => [3, 2, 1] + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. */ - function reverse(array) { - return array == null ? array : nativeReverse.call(array); + function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); } /** - * Creates a slice of `array` from `start` up to, but not including, `end`. - * - * **Note:** This method is used instead of - * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are - * returned. + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. */ - function slice(array, start, end) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { - start = 0; - end = length; - } - else { - start = start == null ? 0 : toInteger(start); - end = end === undefined ? length : toInteger(end); - } - return baseSlice(array, start, end); + function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); } /** - * Uses a binary search to determine the lowest index at which `value` - * should be inserted into `array` in order to maintain its sort order. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. * - * _.sortedIndex([30, 50], 40); - * // => 1 + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. */ - function sortedIndex(array, value) { - return baseSortedIndex(array, value); + function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); } /** - * This method is like `_.sortedIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; - * - * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 0 + * The base implementation of `_.get` without support for default values. * - * // The `_.property` iteratee shorthand. - * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); - * // => 0 + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. */ - function sortedIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; } /** - * This method is like `_.indexOf` except that it performs a binary - * search on a sorted `array`. + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ + function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); + } + + /** + * The base implementation of `getTag` without fallbacks for buggy environments. * - * _.sortedIndexOf([4, 5, 5, 5, 6], 5); - * // => 1 + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. */ - function sortedIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value); - if (index < length && eq(array[index], value)) { - return index; - } + function baseGetTag(value) { + if (value == null) { + return value === undefined ? undefinedTag : nullTag; } - return -1; + return (symToStringTag && symToStringTag in Object(value)) + ? getRawTag(value) + : objectToString(value); } /** - * This method is like `_.sortedIndex` except that it returns the highest - * index at which `value` should be inserted into `array` in order to - * maintain its sort order. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example + * The base implementation of `_.gt` which doesn't coerce arguments. * - * _.sortedLastIndex([4, 5, 5, 5, 6], 5); - * // => 4 + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. */ - function sortedLastIndex(array, value) { - return baseSortedIndex(array, value, true); + function baseGt(value, other) { + return value > other; } /** - * This method is like `_.sortedLastIndex` except that it accepts `iteratee` - * which is invoked for `value` and each element of `array` to compute their - * sort ranking. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The sorted array to inspect. - * @param {*} value The value to evaluate. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * The base implementation of `_.has` without support for deep paths. * - * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); - * // => 1 + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ + function baseHas(object, key) { + return object != null && hasOwnProperty.call(object, key); + } + + /** + * The base implementation of `_.hasIn` without support for deep paths. * - * // The `_.property` iteratee shorthand. - * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); - * // => 1 + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. */ - function sortedLastIndexBy(array, value, iteratee) { - return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); + function baseHasIn(object, key) { + return object != null && key in Object(object); } /** - * This method is like `_.lastIndexOf` except that it performs a binary - * search on a sorted `array`. + * The base implementation of `_.inRange` which doesn't coerce arguments. * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns the index of the matched value, else `-1`. - * @example + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */ + function baseInRange(number, start, end) { + return number >= nativeMin(start, end) && number < nativeMax(start, end); + } + + /** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. * - * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); - * // => 3 + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. */ - function sortedLastIndexOf(array, value) { - var length = array == null ? 0 : array.length; - if (length) { - var index = baseSortedIndex(array, value, true) - 1; - if (eq(array[index], value)) { - return index; + function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; + } + array = arrays[0]; + + var index = -1, + seen = caches[0]; + + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); } } - return -1; + return result; } /** - * This method is like `_.uniq` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. * - * _.sortedUniq([1, 1, 2]); - * // => [1, 2] + * @private + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. */ - function sortedUniq(array) { - return (array && array.length) - ? baseSortedUniq(array) - : []; + function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; } /** - * This method is like `_.uniqBy` except that it's designed and optimized - * for sorted arrays. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example + * The base implementation of `_.invoke` without support for individual + * method arguments. * - * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); - * // => [1.1, 2.3] + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. */ - function sortedUniqBy(array, iteratee) { - return (array && array.length) - ? baseSortedUniq(array, getIteratee(iteratee, 2)) - : []; + function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined : apply(func, object, args); } /** - * Gets all but the first element of `array`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to query. - * @returns {Array} Returns the slice of `array`. - * @example + * The base implementation of `_.isArguments`. * - * _.tail([1, 2, 3]); - * // => [2, 3] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, */ - function tail(array) { - var length = array == null ? 0 : array.length; - return length ? baseSlice(array, 1, length) : []; + function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag; } /** - * Creates a slice of `array` with `n` elements taken from the beginning. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.take([1, 2, 3]); - * // => [1] - * - * _.take([1, 2, 3], 2); - * // => [1, 2] - * - * _.take([1, 2, 3], 5); - * // => [1, 2, 3] + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. * - * _.take([1, 2, 3], 0); - * // => [] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. */ - function take(array, n, guard) { - if (!(array && array.length)) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - return baseSlice(array, 0, n < 0 ? 0 : n); + function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; } /** - * Creates a slice of `array` with `n` elements taken from the end. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {number} [n=1] The number of elements to take. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the slice of `array`. - * @example - * - * _.takeRight([1, 2, 3]); - * // => [3] - * - * _.takeRight([1, 2, 3], 2); - * // => [2, 3] - * - * _.takeRight([1, 2, 3], 5); - * // => [1, 2, 3] + * The base implementation of `_.isDate` without Node.js optimizations. * - * _.takeRight([1, 2, 3], 0); - * // => [] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. */ - function takeRight(array, n, guard) { - var length = array == null ? 0 : array.length; - if (!length) { - return []; - } - n = (guard || n === undefined) ? 1 : toInteger(n); - n = length - n; - return baseSlice(array, n < 0 ? 0 : n, length); + function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; } /** - * Creates a slice of `array` with elements taken from the end. Elements are - * taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': false } - * ]; - * - * _.takeRightWhile(users, function(o) { return !o.active; }); - * // => objects for ['fred', 'pebbles'] - * - * // The `_.matches` iteratee shorthand. - * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); - * // => objects for ['pebbles'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeRightWhile(users, ['active', false]); - * // => objects for ['fred', 'pebbles'] + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. * - * // The `_.property` iteratee shorthand. - * _.takeRightWhile(users, 'active'); - * // => [] + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. */ - function takeRightWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3), false, true) - : []; + function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); } /** - * Creates a slice of `array` with elements taken from the beginning. Elements - * are taken until `predicate` returns falsey. The predicate is invoked with - * three arguments: (value, index, array). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Array - * @param {Array} array The array to query. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the slice of `array`. - * @example - * - * var users = [ - * { 'user': 'barney', 'active': false }, - * { 'user': 'fred', 'active': false }, - * { 'user': 'pebbles', 'active': true } - * ]; - * - * _.takeWhile(users, function(o) { return !o.active; }); - * // => objects for ['barney', 'fred'] - * - * // The `_.matches` iteratee shorthand. - * _.takeWhile(users, { 'user': 'barney', 'active': false }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.takeWhile(users, ['active', false]); - * // => objects for ['barney', 'fred'] + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. * - * // The `_.property` iteratee shorthand. - * _.takeWhile(users, 'active'); - * // => [] + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ - function takeWhile(array, predicate) { - return (array && array.length) - ? baseWhile(array, getIteratee(predicate, 3)) - : []; + function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag(object), + othTag = othIsArr ? arrayTag : getTag(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG)) { + var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); } /** - * Creates an array of unique values, in order, from all given arrays using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of combined values. - * @example + * The base implementation of `_.isMap` without Node.js optimizations. * - * _.union([2], [1, 2]); - * // => [2, 1] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. */ - var union = baseRest(function(arrays) { - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); - }); + function baseIsMap(value) { + return isObjectLike(value) && getTag(value) == mapTag; + } /** - * This method is like `_.union` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which uniqueness is computed. Result values are chosen from the first - * array in which the value occurs. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * _.unionBy([2.1], [1.2, 2.3], Math.floor); - * // => [2.1, 1.2] + * The base implementation of `_.isMatch` without support for iteratee shorthands. * - * // The `_.property` iteratee shorthand. - * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. */ - var unionBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; + function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; } - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); - }); + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; - /** - * This method is like `_.union` except that it accepts `comparator` which - * is invoked to compare elements of `arrays`. Result values are chosen from - * the first array in which the value occurs. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of combined values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; - * - * _.unionWith(objects, others, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] - */ - var unionWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); - }); + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack) + : result + )) { + return false; + } + } + } + return true; + } /** - * Creates a duplicate-free version of an array, using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons, in which only the first occurrence of each element - * is kept. The order of result values is determined by the order they occur - * in the array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @returns {Array} Returns the new duplicate free array. - * @example + * The base implementation of `_.isNative` without bad shim checks. * - * _.uniq([2, 1, 2]); - * // => [2, 1] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. */ - function uniq(array) { - return (array && array.length) ? baseUniq(array) : []; + function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); } /** - * This method is like `_.uniq` except that it accepts `iteratee` which is - * invoked for each element in `array` to generate the criterion by which - * uniqueness is computed. The order of result values is determined by the - * order they occur in the array. The iteratee is invoked with one argument: - * (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * _.uniqBy([2.1, 1.2, 2.3], Math.floor); - * // => [2.1, 1.2] + * The base implementation of `_.isRegExp` without Node.js optimizations. * - * // The `_.property` iteratee shorthand. - * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. */ - function uniqBy(array, iteratee) { - return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; + function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; } /** - * This method is like `_.uniq` except that it accepts `comparator` which - * is invoked to compare elements of `array`. The order of result values is - * determined by the order they occur in the array.The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new duplicate free array. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * The base implementation of `_.isSet` without Node.js optimizations. * - * _.uniqWith(objects, _.isEqual); - * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. */ - function uniqWith(array, comparator) { - comparator = typeof comparator == 'function' ? comparator : undefined; - return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + function baseIsSet(value) { + return isObjectLike(value) && getTag(value) == setTag; } /** - * This method is like `_.zip` except that it accepts an array of grouped - * elements and creates an array regrouping the elements to their pre-zip - * configuration. + * The base implementation of `_.isTypedArray` without Node.js optimizations. * - * @static - * @memberOf _ - * @since 1.2.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @returns {Array} Returns the new array of regrouped elements. - * @example + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ + function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; + } + + /** + * The base implementation of `_.iteratee`. * - * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ + function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); + } + + /** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. * - * _.unzip(zipped); - * // => [['a', 'b'], [1, 2], [true, false]] + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. */ - function unzip(array) { - if (!(array && array.length)) { - return []; + function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); } - var length = 0; - array = arrayFilter(array, function(group) { - if (isArrayLikeObject(group)) { - length = nativeMax(group.length, length); - return true; + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty.call(object, key) && key != 'constructor') { + result.push(key); } - }); - return baseTimes(length, function(index) { - return arrayMap(array, baseProperty(index)); - }); + } + return result; } /** - * This method is like `_.unzip` except that it accepts `iteratee` to specify - * how regrouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {Array} array The array of grouped elements to process. - * @param {Function} [iteratee=_.identity] The function to combine - * regrouped values. - * @returns {Array} Returns the new array of regrouped elements. - * @example - * - * var zipped = _.zip([1, 2], [10, 20], [100, 200]); - * // => [[1, 10, 100], [2, 20, 200]] + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. * - * _.unzipWith(zipped, _.add); - * // => [3, 30, 300] + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. */ - function unzipWith(array, iteratee) { - if (!(array && array.length)) { - return []; + function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); } - var result = unzip(array); - if (iteratee == null) { - return result; + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { + result.push(key); + } } - return arrayMap(result, function(group) { - return apply(iteratee, undefined, group); - }); + return result; } /** - * Creates an array excluding all given values using - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * for equality comparisons. - * - * **Note:** Unlike `_.pull`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {Array} array The array to inspect. - * @param {...*} [values] The values to exclude. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.xor - * @example + * The base implementation of `_.lt` which doesn't coerce arguments. * - * _.without([2, 1, 2, 3], 1, 2); - * // => [3] + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. */ - var without = baseRest(function(array, values) { - return isArrayLikeObject(array) - ? baseDifference(array, values) - : []; - }); + function baseLt(value, other) { + return value < other; + } /** - * Creates an array of unique values that is the - * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) - * of the given arrays. The order of result values is determined by the order - * they occur in the arrays. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @returns {Array} Returns the new array of filtered values. - * @see _.difference, _.without - * @example + * The base implementation of `_.map` without support for iteratee shorthands. * - * _.xor([2, 1], [2, 3]); - * // => [1, 3] + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. */ - var xor = baseRest(function(arrays) { - return baseXor(arrayFilter(arrays, isArrayLikeObject)); - }); + function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; + } /** - * This method is like `_.xor` except that it accepts `iteratee` which is - * invoked for each element of each `arrays` to generate the criterion by - * which by which they're compared. The order of result values is determined - * by the order they occur in the arrays. The iteratee is invoked with one - * argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); - * // => [1.2, 3.4] + * The base implementation of `_.matches` which doesn't clone `source`. * - * // The `_.property` iteratee shorthand. - * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 2 }] + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. */ - var xorBy = baseRest(function(arrays) { - var iteratee = last(arrays); - if (isArrayLikeObject(iteratee)) { - iteratee = undefined; + function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); } - return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); - }); + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; + } /** - * This method is like `_.xor` except that it accepts `comparator` which is - * invoked to compare elements of `arrays`. The order of result values is - * determined by the order they occur in the arrays. The comparator is invoked - * with two arguments: (arrVal, othVal). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Array - * @param {...Array} [arrays] The arrays to inspect. - * @param {Function} [comparator] The comparator invoked per element. - * @returns {Array} Returns the new array of filtered values. - * @example - * - * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; - * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. * - * _.xorWith(objects, others, _.isEqual); - * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. */ - var xorWith = baseRest(function(arrays) { - var comparator = last(arrays); - comparator = typeof comparator == 'function' ? comparator : undefined; - return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); - }); + function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; + } /** - * Creates an array of grouped elements, the first of which contains the - * first elements of the given arrays, the second of which contains the - * second elements of the given arrays, and so on. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @returns {Array} Returns the new array of grouped elements. - * @example + * The base implementation of `_.merge` without support for multiple sources. * - * _.zip(['a', 'b'], [1, 2], [true, false]); - * // => [['a', 1, true], ['b', 2, false]] + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. */ - var zip = baseRest(unzip); + function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); + } /** - * This method is like `_.fromPairs` except that it accepts two arrays, - * one of property identifiers and one of corresponding values. - * - * @static - * @memberOf _ - * @since 0.4.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. * - * _.zipObject(['a', 'b'], [1, 2]); - * // => { 'a': 1, 'b': 2 } + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. */ - function zipObject(props, values) { - return baseZipObject(props || [], values || [], assignValue); + function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); } /** - * This method is like `_.zipObject` except that it supports property paths. - * - * @static - * @memberOf _ - * @since 4.1.0 - * @category Array - * @param {Array} [props=[]] The property identifiers. - * @param {Array} [values=[]] The property values. - * @returns {Object} Returns the new object. - * @example + * The base implementation of `_.nth` which doesn't coerce arguments. * - * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); - * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } + * @private + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. */ - function zipObjectDeep(props, values) { - return baseZipObject(props || [], values || [], baseSet); + function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; } /** - * This method is like `_.zip` except that it accepts `iteratee` to specify - * how grouped values should be combined. The iteratee is invoked with the - * elements of each group: (...group). - * - * @static - * @memberOf _ - * @since 3.8.0 - * @category Array - * @param {...Array} [arrays] The arrays to process. - * @param {Function} [iteratee=_.identity] The function to combine - * grouped values. - * @returns {Array} Returns the new array of grouped elements. - * @example + * The base implementation of `_.orderBy` without param guards. * - * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { - * return a + b + c; - * }); - * // => [111, 222] + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. */ - var zipWith = baseRest(function(arrays) { - var length = arrays.length, - iteratee = length > 1 ? arrays[length - 1] : undefined; + function baseOrderBy(collection, iteratees, orders) { + if (iteratees.length) { + iteratees = arrayMap(iteratees, function(iteratee) { + if (isArray(iteratee)) { + return function(value) { + return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); + } + } + return iteratee; + }); + } else { + iteratees = [identity]; + } - iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; - return unzipWith(arrays, iteratee); - }); + var index = -1; + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); - /*------------------------------------------------------------------------*/ + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); + } /** - * Creates a `lodash` wrapper instance that wraps `value` with explicit method - * chain sequences enabled. The result of such sequences must be unwrapped - * with `_#value`. - * - * @static - * @memberOf _ - * @since 1.3.0 - * @category Seq - * @param {*} value The value to wrap. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example + * The base implementation of `_.pick` without support for individual + * property identifiers. * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'pebbles', 'age': 1 } - * ]; + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. + */ + function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); + } + + /** + * The base implementation of `_.pickBy` without support for iteratee shorthands. * - * var youngest = _ - * .chain(users) - * .sortBy('age') - * .map(function(o) { - * return o.user + ' is ' + o.age; - * }) - * .head() - * .value(); - * // => 'pebbles is 1' + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. */ - function chain(value) { - var result = lodash(value); - result.__chain__ = true; + function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } return result; } /** - * This method invokes `interceptor` and returns `value`. The interceptor - * is invoked with one argument; (value). The purpose of this method is to - * "tap into" a method chain sequence in order to modify intermediate results. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns `value`. - * @example + * A specialized version of `baseProperty` which supports deep paths. * - * _([1, 2, 3]) - * .tap(function(array) { - * // Mutate input array. - * array.pop(); - * }) - * .reverse() - * .value(); - * // => [2, 1] + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. */ - function tap(value, interceptor) { - interceptor(value); - return value; + function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; } /** - * This method is like `_.tap` except that it returns the result of `interceptor`. - * The purpose of this method is to "pass thru" values replacing intermediate - * results in a method chain sequence. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Seq - * @param {*} value The value to provide to `interceptor`. - * @param {Function} interceptor The function to invoke. - * @returns {*} Returns the result of `interceptor`. - * @example + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. * - * _(' abc ') - * .chain() - * .trim() - * .thru(function(value) { - * return [value]; - * }) - * .value(); - * // => ['abc'] + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. */ - function thru(value, interceptor) { - return interceptor(value); + function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice.call(seen, fromIndex, 1); + } + splice.call(array, fromIndex, 1); + } + } + return array; } /** - * This method is the wrapper version of `_.at`. - * - * @name at - * @memberOf _ - * @since 1.0.0 - * @category Seq - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. * - * _(object).at(['a[0].b.c', 'a[1]']).value(); - * // => [3, 4] + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. */ - var wrapperAt = flatRest(function(paths) { - var length = paths.length, - start = length ? paths[0] : 0, - value = this.__wrapped__, - interceptor = function(object) { return baseAt(object, paths); }; + function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; - if (length > 1 || this.__actions__.length || - !(value instanceof LazyWrapper) || !isIndex(start)) { - return this.thru(interceptor); - } - value = value.slice(start, +start + (length ? 1 : 0)); - value.__actions__.push({ - 'func': thru, - 'args': [interceptor], - 'thisArg': undefined - }); - return new LodashWrapper(value, this.__chain__).thru(function(array) { - if (length && !array.length) { - array.push(undefined); + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } } - return array; - }); - }); + } + return array; + } /** - * Creates a `lodash` wrapper instance with explicit method chain sequences enabled. - * - * @name chain - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 40 } - * ]; - * - * // A sequence without explicit chaining. - * _(users).head(); - * // => { 'user': 'barney', 'age': 36 } + * The base implementation of `_.random` without support for returning + * floating-point numbers. * - * // A sequence with explicit chaining. - * _(users) - * .chain() - * .head() - * .pick('user') - * .value(); - * // => { 'user': 'barney' } + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. */ - function wrapperChain() { - return chain(this); + function baseRandom(lower, upper) { + return lower + nativeFloor(nativeRandom() * (upper - lower + 1)); } /** - * Executes the chain sequence and returns the wrapped result. - * - * @name commit - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2]; - * var wrapped = _(array).push(3); - * - * console.log(array); - * // => [1, 2] - * - * wrapped = wrapped.commit(); - * console.log(array); - * // => [1, 2, 3] - * - * wrapped.last(); - * // => 3 + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. * - * console.log(array); - * // => [1, 2, 3] + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. */ - function wrapperCommit() { - return new LodashWrapper(this.value(), this.__chain__); + function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; } /** - * Gets the next value on a wrapped object following the - * [iterator protocol](https://mdn.io/iteration_protocols#iterator). - * - * @name next - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the next iterator value. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped.next(); - * // => { 'done': false, 'value': 1 } - * - * wrapped.next(); - * // => { 'done': false, 'value': 2 } + * The base implementation of `_.repeat` which doesn't coerce arguments. * - * wrapped.next(); - * // => { 'done': true, 'value': undefined } + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. */ - function wrapperNext() { - if (this.__values__ === undefined) { - this.__values__ = toArray(this.value()); + function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER) { + return result; } - var done = this.__index__ >= this.__values__.length, - value = done ? undefined : this.__values__[this.__index__++]; + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor(n / 2); + if (n) { + string += string; + } + } while (n); - return { 'done': done, 'value': value }; + return result; } /** - * Enables the wrapper to be iterable. - * - * @name Symbol.iterator - * @memberOf _ - * @since 4.0.0 - * @category Seq - * @returns {Object} Returns the wrapper object. - * @example - * - * var wrapped = _([1, 2]); - * - * wrapped[Symbol.iterator]() === wrapped; - * // => true + * The base implementation of `_.rest` which doesn't validate or coerce arguments. * - * Array.from(wrapped); - * // => [1, 2] + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. */ - function wrapperToIterator() { - return this; + function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); } /** - * Creates a clone of the chain sequence planting `value` as the wrapped value. - * - * @name plant - * @memberOf _ - * @since 3.2.0 - * @category Seq - * @param {*} value The value to plant. - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * function square(n) { - * return n * n; - * } + * The base implementation of `_.sample`. * - * var wrapped = _([1, 2]).map(square); - * var other = wrapped.plant([3, 4]); + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */ + function baseSample(collection) { + return arraySample(values(collection)); + } + + /** + * The base implementation of `_.sampleSize` without param guards. * - * other.value(); - * // => [9, 16] + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ + function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); + } + + /** + * The base implementation of `_.set`. * - * wrapped.value(); - * // => [1, 4] + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. */ - function wrapperPlant(value) { - var result, - parent = this; + function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); - while (parent instanceof baseLodash) { - var clone = wrapperClone(parent); - clone.__index__ = 0; - clone.__values__ = undefined; - if (result) { - previous.__wrapped__ = clone; - } else { - result = clone; + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { + return object; } - var previous = clone; - parent = parent.__wrapped__; + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; } - previous.__wrapped__ = value; - return result; + return object; } /** - * This method is the wrapper version of `_.reverse`. - * - * **Note:** This method mutates the wrapped array. - * - * @name reverse - * @memberOf _ - * @since 0.1.0 - * @category Seq - * @returns {Object} Returns the new `lodash` wrapper instance. - * @example - * - * var array = [1, 2, 3]; - * - * _(array).reverse().value() - * // => [3, 2, 1] + * The base implementation of `setData` without support for hot loop shorting. * - * console.log(array); - * // => [3, 2, 1] + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. */ - function wrapperReverse() { - var value = this.__wrapped__; - if (value instanceof LazyWrapper) { - var wrapped = value; - if (this.__actions__.length) { - wrapped = new LazyWrapper(this); - } - wrapped = wrapped.reverse(); - wrapped.__actions__.push({ - 'func': thru, - 'args': [reverse], - 'thisArg': undefined - }); - return new LodashWrapper(wrapped, this.__chain__); - } - return this.thru(reverse); - } + var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; + }; /** - * Executes the chain sequence to resolve the unwrapped value. + * The base implementation of `setToString` without support for hot loop shorting. * - * @name value - * @memberOf _ - * @since 0.1.0 - * @alias toJSON, valueOf - * @category Seq - * @returns {*} Returns the resolved unwrapped value. - * @example + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ + var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); + }; + + /** + * The base implementation of `_.shuffle`. * - * _([1, 2, 3]).value(); - * // => [1, 2, 3] + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. */ - function wrapperValue() { - return baseWrapperValue(this.__wrapped__, this.__actions__); + function baseShuffle(collection) { + return shuffleSelf(values(collection)); } - /*------------------------------------------------------------------------*/ - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the number of times the key was returned by `iteratee`. The - * iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.5.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.countBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': 1, '6': 2 } + * The base implementation of `_.slice` without an iteratee call guard. * - * // The `_.property` iteratee shorthand. - * _.countBy(['one', 'two', 'three'], 'length'); - * // => { '3': 2, '5': 1 } + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. */ - var countBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - ++result[key]; - } else { - baseAssignValue(result, key, 1); + function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; } - }); + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; + } /** - * Checks if `predicate` returns truthy for **all** elements of `collection`. - * Iteration is stopped once `predicate` returns falsey. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * **Note:** This method returns `true` for - * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because - * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of - * elements of empty collections. + * The base implementation of `_.some` without support for iteratee shorthands. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection + * @private * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if all elements pass the predicate check, + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, * else `false`. - * @example - * - * _.every([true, 1, null, 'yes'], Boolean); - * // => false - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.every(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.every(users, ['active', false]); - * // => true - * - * // The `_.property` iteratee shorthand. - * _.every(users, 'active'); - * // => false */ - function every(collection, predicate, guard) { - var func = isArray(collection) ? arrayEvery : baseEvery; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; - } - return func(collection, getIteratee(predicate, 3)); + function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; } /** - * Iterates over elements of `collection`, returning an array of all elements - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * **Note:** Unlike `_.remove`, this method returns a new array. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.reject - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false } - * ]; - * - * _.filter(users, function(o) { return !o.active; }); - * // => objects for ['fred'] - * - * // The `_.matches` iteratee shorthand. - * _.filter(users, { 'age': 36, 'active': true }); - * // => objects for ['barney'] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.filter(users, ['active', false]); - * // => objects for ['fred'] - * - * // The `_.property` iteratee shorthand. - * _.filter(users, 'active'); - * // => objects for ['barney'] + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. * - * // Combining several predicates using `_.overEvery` or `_.overSome`. - * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); - * // => objects for ['fred', 'barney'] + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. */ - function filter(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, getIteratee(predicate, 3)); + function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); } /** - * Iterates over elements of `collection`, returning the first element - * `predicate` returns truthy for. The predicate is invoked with three - * arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=0] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': true }, - * { 'user': 'fred', 'age': 40, 'active': false }, - * { 'user': 'pebbles', 'age': 1, 'active': true } - * ]; - * - * _.find(users, function(o) { return o.age < 40; }); - * // => object for 'barney' - * - * // The `_.matches` iteratee shorthand. - * _.find(users, { 'age': 1, 'active': true }); - * // => object for 'pebbles' - * - * // The `_.matchesProperty` iteratee shorthand. - * _.find(users, ['active', false]); - * // => object for 'fred' + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). * - * // The `_.property` iteratee shorthand. - * _.find(users, 'active'); - * // => object for 'barney' + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. */ - var find = createFind(findIndex); + function baseSortedIndexBy(array, value, iteratee, retHighest) { + var low = 0, + high = array == null ? 0 : array.length; + if (high === 0) { + return 0; + } + + value = iteratee(value); + var valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin(high, MAX_ARRAY_INDEX); + } /** - * This method is like `_.find` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param {number} [fromIndex=collection.length-1] The index to search from. - * @returns {*} Returns the matched element, else `undefined`. - * @example + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. * - * _.findLast([1, 2, 3, 4], function(n) { - * return n % 2 == 1; - * }); - * // => 3 + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. */ - var findLast = createFind(findLastIndex); + function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; + } /** - * Creates a flattened array of values by running each element in `collection` - * thru `iteratee` and flattening the mapped results. The iteratee is invoked - * with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [n, n]; - * } + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. * - * _.flatMap([1, 2], duplicate); - * // => [1, 1, 2, 2] + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. */ - function flatMap(collection, iteratee) { - return baseFlatten(map(collection, iteratee), 1); + function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN; + } + return +value; } /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. * - * _.flatMapDeep([1, 2], duplicate); - * // => [1, 1, 2, 2] + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. */ - function flatMapDeep(collection, iteratee) { - return baseFlatten(map(collection, iteratee), INFINITY); + function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** - * This method is like `_.flatMap` except that it recursively flattens the - * mapped results up to `depth` times. - * - * @static - * @memberOf _ - * @since 4.7.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {number} [depth=1] The maximum recursion depth. - * @returns {Array} Returns the new flattened array. - * @example - * - * function duplicate(n) { - * return [[[n, n]]]; - * } + * The base implementation of `_.uniqBy` without support for iteratee shorthands. * - * _.flatMapDepth([1, 2], duplicate, 2); - * // => [[1, 1], [2, 2]] + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. */ - function flatMapDepth(collection, iteratee, depth) { - depth = depth === undefined ? 1 : toInteger(depth); - return baseFlatten(map(collection, iteratee), depth); + function baseUniq(array, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + length = array.length, + isCommon = true, + result = [], + seen = result; + + if (comparator) { + isCommon = false; + includes = arrayIncludesWith; + } + else if (length >= LARGE_ARRAY_SIZE) { + var set = iteratee ? null : createSet(array); + if (set) { + return setToArray(set); + } + isCommon = false; + includes = cacheHas; + seen = new SetCache; + } + else { + seen = iteratee ? [] : result; + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var seenIndex = seen.length; + while (seenIndex--) { + if (seen[seenIndex] === computed) { + continue outer; + } + } + if (iteratee) { + seen.push(computed); + } + result.push(value); + } + else if (!includes(seen, computed, comparator)) { + if (seen !== result) { + seen.push(computed); + } + result.push(value); + } + } + return result; } /** - * Iterates over elements of `collection` and invokes `iteratee` for each element. - * The iteratee is invoked with three arguments: (value, index|key, collection). - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * **Note:** As with other "Collections" methods, objects with a "length" - * property are iterated like arrays. To avoid this behavior use `_.forIn` - * or `_.forOwn` for object iteration. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @alias each - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEachRight - * @example - * - * _.forEach([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `1` then `2`. + * The base implementation of `_.unset`. * - * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The property path to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. */ - function forEach(collection, iteratee) { - var func = isArray(collection) ? arrayEach : baseEach; - return func(collection, getIteratee(iteratee, 3)); + function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; } /** - * This method is like `_.forEach` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @alias eachRight - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array|Object} Returns `collection`. - * @see _.forEach - * @example + * The base implementation of `_.update`. * - * _.forEachRight([1, 2], function(value) { - * console.log(value); - * }); - * // => Logs `2` then `1`. + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to update. + * @param {Function} updater The function to produce the updated value. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. */ - function forEachRight(collection, iteratee) { - var func = isArray(collection) ? arrayEachRight : baseEachRight; - return func(collection, getIteratee(iteratee, 3)); + function baseUpdate(object, path, updater, customizer) { + return baseSet(object, path, updater(baseGet(object, path)), customizer); } /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The order of grouped values - * is determined by the order they occur in `collection`. The corresponding - * value of each key is an array of elements responsible for generating the - * key. The iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. * - * _.groupBy([6.1, 4.2, 6.3], Math.floor); - * // => { '4': [4.2], '6': [6.1, 6.3] } + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ + function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); + } + + /** + * The base implementation of `wrapperValue` which returns the result of + * performing a sequence of actions on the unwrapped `value`, where each + * successive action is supplied the return value of the previous. * - * // The `_.property` iteratee shorthand. - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } + * @private + * @param {*} value The unwrapped value. + * @param {Array} actions Actions to perform to resolve the unwrapped value. + * @returns {*} Returns the resolved value. */ - var groupBy = createAggregator(function(result, value, key) { - if (hasOwnProperty.call(result, key)) { - result[key].push(value); - } else { - baseAssignValue(result, key, [value]); + function baseWrapperValue(value, actions) { + var result = value; + if (result instanceof LazyWrapper) { + result = result.value(); } - }); + return arrayReduce(actions, function(result, action) { + return action.func.apply(action.thisArg, arrayPush([result], action.args)); + }, result); + } /** - * Checks if `value` is in `collection`. If `collection` is a string, it's - * checked for a substring of `value`, otherwise - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * is used for equality comparisons. If `fromIndex` is negative, it's used as - * the offset from the end of `collection`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {boolean} Returns `true` if `value` is found, else `false`. - * @example - * - * _.includes([1, 2, 3], 1); - * // => true - * - * _.includes([1, 2, 3], 1, 2); - * // => false - * - * _.includes({ 'a': 1, 'b': 2 }, 1); - * // => true + * The base implementation of methods like `_.xor`, without support for + * iteratee shorthands, that accepts an array of arrays to inspect. * - * _.includes('abcd', 'bc'); - * // => true + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of values. */ - function includes(collection, value, fromIndex, guard) { - collection = isArrayLike(collection) ? collection : values(collection); - fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + function baseXor(arrays, iteratee, comparator) { + var length = arrays.length; + if (length < 2) { + return length ? baseUniq(arrays[0]) : []; + } + var index = -1, + result = Array(length); - var length = collection.length; - if (fromIndex < 0) { - fromIndex = nativeMax(length + fromIndex, 0); + while (++index < length) { + var array = arrays[index], + othIndex = -1; + + while (++othIndex < length) { + if (othIndex != index) { + result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator); + } + } } - return isString(collection) - ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) - : (!!length && baseIndexOf(collection, value, fromIndex) > -1); + return baseUniq(baseFlatten(result, 1), iteratee, comparator); } /** - * Invokes the method at `path` of each element in `collection`, returning - * an array of the results of each invoked method. Any additional arguments - * are provided to each invoked method. If `path` is a function, it's invoked - * for, and `this` bound to, each element in `collection`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array|Function|string} path The path of the method to invoke or - * the function invoked per iteration. - * @param {...*} [args] The arguments to invoke each method with. - * @returns {Array} Returns the array of results. - * @example - * - * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); - * // => [[1, 5, 7], [1, 2, 3]] + * This base implementation of `_.zipObject` which assigns values using `assignFunc`. * - * _.invokeMap([123, 456], String.prototype.split, ''); - * // => [['1', '2', '3'], ['4', '5', '6']] + * @private + * @param {Array} props The property identifiers. + * @param {Array} values The property values. + * @param {Function} assignFunc The function to assign values. + * @returns {Object} Returns the new object. */ - var invokeMap = baseRest(function(collection, path, args) { + function baseZipObject(props, values, assignFunc) { var index = -1, - isFunc = typeof path == 'function', - result = isArrayLike(collection) ? Array(collection.length) : []; + length = props.length, + valsLength = values.length, + result = {}; - baseEach(collection, function(value) { - result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); - }); + while (++index < length) { + var value = index < valsLength ? values[index] : undefined; + assignFunc(result, props[index], value); + } return result; - }); + } /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` thru `iteratee`. The corresponding value of - * each key is the last element responsible for generating the key. The - * iteratee is invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The iteratee to transform keys. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * var array = [ - * { 'dir': 'left', 'code': 97 }, - * { 'dir': 'right', 'code': 100 } - * ]; - * - * _.keyBy(array, function(o) { - * return String.fromCharCode(o.code); - * }); - * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * Casts `value` to an empty array if it's not an array like object. * - * _.keyBy(array, 'dir'); - * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. */ - var keyBy = createAggregator(function(result, value, key) { - baseAssignValue(result, key, value); - }); + function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; + } /** - * Creates an array of values by running each element in `collection` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. - * - * The guarded methods are: - * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, - * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, - * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, - * `template`, `trim`, `trimEnd`, `trimStart`, and `words` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - * @example - * - * function square(n) { - * return n * n; - * } - * - * _.map([4, 8], square); - * // => [16, 64] - * - * _.map({ 'a': 4, 'b': 8 }, square); - * // => [16, 64] (iteration order is not guaranteed) - * - * var users = [ - * { 'user': 'barney' }, - * { 'user': 'fred' } - * ]; + * Casts `value` to `identity` if it's not a function. * - * // The `_.property` iteratee shorthand. - * _.map(users, 'user'); - * // => ['barney', 'fred'] + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. */ - function map(collection, iteratee) { - var func = isArray(collection) ? arrayMap : baseMap; - return func(collection, getIteratee(iteratee, 3)); + function castFunction(value) { + return typeof value == 'function' ? value : identity; } /** - * This method is like `_.sortBy` except that it allows specifying the sort - * orders of the iteratees to sort by. If `orders` is unspecified, all values - * are sorted in ascending order. Otherwise, specify an order of "desc" for - * descending or "asc" for ascending sort order of corresponding values. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] - * The iteratees to sort by. - * @param {string[]} [orders] The sort orders of `iteratees`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 34 }, - * { 'user': 'fred', 'age': 40 }, - * { 'user': 'barney', 'age': 36 } - * ]; + * Casts `value` to a path array if it's not one. * - * // Sort by `user` in ascending order and by `age` in descending order. - * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. */ - function orderBy(collection, iteratees, orders, guard) { - if (collection == null) { - return []; - } - if (!isArray(iteratees)) { - iteratees = iteratees == null ? [] : [iteratees]; - } - orders = guard ? undefined : orders; - if (!isArray(orders)) { - orders = orders == null ? [] : [orders]; + function castPath(value, object) { + if (isArray(value)) { + return value; } - return baseOrderBy(collection, iteratees, orders); + return isKey(value, object) ? [value] : stringToPath(toString(value)); } /** - * Creates an array of elements split into two groups, the first of which - * contains elements `predicate` returns truthy for, the second of which - * contains elements `predicate` returns falsey for. The predicate is - * invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the array of grouped elements. - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true }, - * { 'user': 'pebbles', 'age': 1, 'active': false } - * ]; - * - * _.partition(users, function(o) { return o.active; }); - * // => objects for [['fred'], ['barney', 'pebbles']] - * - * // The `_.matches` iteratee shorthand. - * _.partition(users, { 'age': 1, 'active': false }); - * // => objects for [['pebbles'], ['barney', 'fred']] - * - * // The `_.matchesProperty` iteratee shorthand. - * _.partition(users, ['active', false]); - * // => objects for [['barney', 'pebbles'], ['fred']] + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. * - * // The `_.property` iteratee shorthand. - * _.partition(users, 'active'); - * // => objects for [['fred'], ['barney', 'pebbles']] + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. */ - var partition = createAggregator(function(result, value, key) { - result[key ? 0 : 1].push(value); - }, function() { return [[], []]; }); + var castRest = baseRest; /** - * Reduces `collection` to a value which is the accumulated result of running - * each element in `collection` thru `iteratee`, where each successive - * invocation is supplied the return value of the previous. If `accumulator` - * is not given, the first element of `collection` is used as the initial - * value. The iteratee is invoked with four arguments: - * (accumulator, value, index|key, collection). - * - * Many lodash methods are guarded to work as iteratees for methods like - * `_.reduce`, `_.reduceRight`, and `_.transform`. - * - * The guarded methods are: - * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, - * and `sortBy` - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduceRight - * @example - * - * _.reduce([1, 2], function(sum, n) { - * return sum + n; - * }, 0); - * // => 3 + * Casts `array` to a slice if it's needed. * - * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * return result; - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. */ - function reduce(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduce : baseReduce, - initAccum = arguments.length < 3; - - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach); + function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); } /** - * This method is like `_.reduce` except that it iterates over elements of - * `collection` from right to left. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The initial value. - * @returns {*} Returns the accumulated value. - * @see _.reduce - * @example + * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout). * - * var array = [[0, 1], [2, 3], [4, 5]]; + * @private + * @param {number|Object} id The timer id or timeout object of the timer to clear. + */ + var clearTimeout = ctxClearTimeout || function(id) { + return root.clearTimeout(id); + }; + + /** + * Creates a clone of `buffer`. * - * _.reduceRight(array, function(flattened, other) { - * return flattened.concat(other); - * }, []); - * // => [4, 5, 2, 3, 0, 1] + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. */ - function reduceRight(collection, iteratee, accumulator) { - var func = isArray(collection) ? arrayReduceRight : baseReduce, - initAccum = arguments.length < 3; + function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); - return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight); + buffer.copy(result); + return result; } /** - * The opposite of `_.filter`; this method returns the elements of `collection` - * that `predicate` does **not** return truthy for. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {Array} Returns the new filtered array. - * @see _.filter - * @example - * - * var users = [ - * { 'user': 'barney', 'age': 36, 'active': false }, - * { 'user': 'fred', 'age': 40, 'active': true } - * ]; + * Creates a clone of `arrayBuffer`. * - * _.reject(users, function(o) { return !o.active; }); - * // => objects for ['fred'] + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ + function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; + } + + /** + * Creates a clone of `dataView`. * - * // The `_.matches` iteratee shorthand. - * _.reject(users, { 'age': 40, 'active': true }); - * // => objects for ['barney'] + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ + function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); + } + + /** + * Creates a clone of `regexp`. * - * // The `_.matchesProperty` iteratee shorthand. - * _.reject(users, ['active', false]); - * // => objects for ['fred'] + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ + function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; + } + + /** + * Creates a clone of the `symbol` object. * - * // The `_.property` iteratee shorthand. - * _.reject(users, 'active'); - * // => objects for ['barney'] + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. */ - function reject(collection, predicate) { - var func = isArray(collection) ? arrayFilter : baseFilter; - return func(collection, negate(getIteratee(predicate, 3))); + function cloneSymbol(symbol) { + return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {}; } /** - * Gets a random element from `collection`. + * Creates a clone of `typedArray`. * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @returns {*} Returns the random element. - * @example + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ + function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); + } + + /** + * Compares values to sort them in ascending order. * - * _.sample([1, 2, 3, 4]); - * // => 2 + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. */ - function sample(collection) { - var func = isArray(collection) ? arraySample : baseSample; - return func(collection); + function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; } /** - * Gets `n` random elements at unique keys from `collection` up to the - * size of `collection`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Collection - * @param {Array|Object} collection The collection to sample. - * @param {number} [n=1] The number of elements to sample. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Array} Returns the random elements. - * @example + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. * - * _.sampleSize([1, 2, 3], 2); - * // => [3, 1] + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. * - * _.sampleSize([1, 2, 3], 4); - * // => [2, 3, 1] + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. */ - function sampleSize(collection, n, guard) { - if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); + function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } } - var func = isArray(collection) ? arraySampleSize : baseSampleSize; - return func(collection, n); + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; } /** - * Creates an array of shuffled values, using a version of the - * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to shuffle. - * @returns {Array} Returns the new shuffled array. - * @example + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. * - * _.shuffle([1, 2, 3, 4]); - * // => [4, 1, 3, 2] + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. */ - function shuffle(collection) { - var func = isArray(collection) ? arrayShuffle : baseShuffle; - return func(collection); + function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; } /** - * Gets the size of `collection` by returning its length for array-like - * values or the number of own enumerable string keyed properties for objects. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object|string} collection The collection to inspect. - * @returns {number} Returns the collection size. - * @example - * - * _.size([1, 2, 3]); - * // => 3 - * - * _.size({ 'a': 1, 'b': 2 }); - * // => 2 + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. * - * _.size('pebbles'); - * // => 7 + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. */ - function size(collection) { - if (collection == null) { - return 0; + function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; } - if (isArrayLike(collection)) { - return isString(collection) ? stringSize(collection) : collection.length; + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; } - var tag = getTag(collection); - if (tag == mapTag || tag == setTag) { - return collection.size; + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } } - return baseKeys(collection).length; + return result; } /** - * Checks if `predicate` returns truthy for **any** element of `collection`. - * Iteration is stopped once `predicate` returns truthy. The predicate is - * invoked with three arguments: (value, index|key, collection). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {boolean} Returns `true` if any element passes the predicate check, - * else `false`. - * @example - * - * _.some([null, 0, 'yes', false], Boolean); - * // => true - * - * var users = [ - * { 'user': 'barney', 'active': true }, - * { 'user': 'fred', 'active': false } - * ]; - * - * // The `_.matches` iteratee shorthand. - * _.some(users, { 'user': 'barney', 'active': false }); - * // => false - * - * // The `_.matchesProperty` iteratee shorthand. - * _.some(users, ['active', false]); - * // => true + * Copies the values of `source` to `array`. * - * // The `_.property` iteratee shorthand. - * _.some(users, 'active'); - * // => true + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. */ - function some(collection, predicate, guard) { - var func = isArray(collection) ? arraySome : baseSome; - if (guard && isIterateeCall(collection, predicate, guard)) { - predicate = undefined; + function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; } - return func(collection, getIteratee(predicate, 3)); + return array; } /** - * Creates an array of elements, sorted in ascending order by the results of - * running each element in a collection thru each iteratee. This method - * performs a stable sort, that is, it preserves the original sort order of - * equal elements. The iteratees are invoked with one argument: (value). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Collection - * @param {Array|Object} collection The collection to iterate over. - * @param {...(Function|Function[])} [iteratees=[_.identity]] - * The iteratees to sort by. - * @returns {Array} Returns the new sorted array. - * @example - * - * var users = [ - * { 'user': 'fred', 'age': 48 }, - * { 'user': 'barney', 'age': 36 }, - * { 'user': 'fred', 'age': 30 }, - * { 'user': 'barney', 'age': 34 } - * ]; - * - * _.sortBy(users, [function(o) { return o.user; }]); - * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] + * Copies properties of `source` to `object`. * - * _.sortBy(users, ['user', 'age']); - * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. */ - var sortBy = baseRest(function(collection, iteratees) { - if (collection == null) { - return []; - } - var length = iteratees.length; - if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { - iteratees = []; - } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { - iteratees = [iteratees[0]]; - } - return baseOrderBy(collection, baseFlatten(iteratees, 1), []); - }); + function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); - /*------------------------------------------------------------------------*/ + var index = -1, + length = props.length; - /** - * Gets the timestamp of the number of milliseconds that have elapsed since - * the Unix epoch (1 January 1970 00:00:00 UTC). - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Date - * @returns {number} Returns the timestamp. - * @example - * - * _.defer(function(stamp) { - * console.log(_.now() - stamp); - * }, _.now()); - * // => Logs the number of milliseconds it took for the deferred invocation. - */ - var now = ctxNow || function() { - return root.Date.now(); - }; + while (++index < length) { + var key = props[index]; - /*------------------------------------------------------------------------*/ + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; + } /** - * The opposite of `_.before`; this method creates a function that invokes - * `func` once it's called `n` or more times. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {number} n The number of calls before `func` is invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var saves = ['profile', 'settings']; - * - * var done = _.after(saves.length, function() { - * console.log('done saving!'); - * }); + * Copies own symbols of `source` to `object`. * - * _.forEach(saves, function(type) { - * asyncSave({ 'type': type, 'complete': done }); - * }); - * // => Logs 'done saving!' after the two async saves have completed. + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. */ - function after(n, func) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n < 1) { - return func.apply(this, arguments); - } - }; + function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); } /** - * Creates a function that invokes `func`, with up to `n` arguments, - * ignoring any additional arguments. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @param {number} [n=func.length] The arity cap. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new capped function. - * @example + * Copies own and inherited symbols of `source` to `object`. * - * _.map(['6', '8', '10'], _.ary(parseInt, 1)); - * // => [6, 8, 10] + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. */ - function ary(func, n, guard) { - n = guard ? undefined : n; - n = (func && n == null) ? func.length : n; - return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n); + function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); } /** - * Creates a function that invokes `func`, with the `this` binding and arguments - * of the created function, while it's called less than `n` times. Subsequent - * calls to the created function return the result of the last `func` invocation. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {number} n The number of calls at which `func` is no longer invoked. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example + * Creates a function like `_.groupBy`. * - * jQuery(element).on('click', _.before(5, addContactToList)); - * // => Allows adding up to 4 contacts to the list. + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. */ - function before(n, func) { - var result; - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - n = toInteger(n); - return function() { - if (--n > 0) { - result = func.apply(this, arguments); - } - if (n <= 1) { - func = undefined; - } - return result; + function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; + + return func(collection, setter, getIteratee(iteratee, 2), accumulator); }; } /** - * Creates a function that invokes `func` with the `this` binding of `thisArg` - * and `partials` prepended to the arguments it receives. - * - * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for partially applied arguments. - * - * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" - * property of bound functions. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to bind. - * @param {*} thisArg The `this` binding of `func`. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * function greet(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * - * var object = { 'user': 'fred' }; - * - * var bound = _.bind(greet, object, 'hi'); - * bound('!'); - * // => 'hi fred!' + * Creates a function like `_.assign`. * - * // Bound with placeholders. - * var bound = _.bind(greet, object, _, '!'); - * bound('hi'); - * // => 'hi fred!' + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. */ - var bind = baseRest(function(func, thisArg, partials) { - var bitmask = WRAP_BIND_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bind)); - bitmask |= WRAP_PARTIAL_FLAG; - } - return createWrap(func, bitmask, thisArg, partials, holders); - }); + function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; - /** - * Creates a function that invokes the method at `object[key]` with `partials` - * prepended to the arguments it receives. - * - * This method differs from `_.bind` by allowing bound functions to reference - * methods that may be redefined or don't yet exist. See - * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) - * for more details. - * - * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * @static - * @memberOf _ - * @since 0.10.0 - * @category Function - * @param {Object} object The object to invoke the method on. - * @param {string} key The key of the method. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * var object = { - * 'user': 'fred', - * 'greet': function(greeting, punctuation) { - * return greeting + ' ' + this.user + punctuation; - * } - * }; - * - * var bound = _.bindKey(object, 'greet', 'hi'); - * bound('!'); - * // => 'hi fred!' + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); + } + + /** + * Creates a `baseEach` or `baseEachRight` function. * - * object.greet = function(greeting, punctuation) { - * return greeting + 'ya ' + this.user + punctuation; - * }; + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; + } + + /** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. * - * bound('!'); - * // => 'hiya fred!' + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ + function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; + } + + /** + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. * - * // Bound with placeholders. - * var bound = _.bindKey(object, 'greet', _, '!'); - * bound('hi'); - * // => 'hiya fred!' + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. */ - var bindKey = baseRest(function(object, key, partials) { - var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG; - if (partials.length) { - var holders = replaceHolders(partials, getHolder(bindKey)); - bitmask |= WRAP_PARTIAL_FLAG; + function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); } - return createWrap(key, bitmask, object, partials, holders); - }); + return wrapper; + } /** - * Creates a function that accepts arguments of `func` and either invokes - * `func` returning its result, if at least `arity` number of arguments have - * been provided, or returns a function that accepts the remaining `func` - * arguments, and so on. The arity of `func` may be specified if `func.length` - * is not sufficient. - * - * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, - * may be used as a placeholder for provided arguments. - * - * **Note:** This method doesn't set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curry(abc); - * - * curried(1)(2)(3); - * // => [1, 2, 3] - * - * curried(1, 2)(3); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] + * Creates a function like `_.lowerFirst`. * - * // Curried with placeholders. - * curried(1)(_, 3)(2); - * // => [1, 2, 3] + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. */ - function curry(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curry.placeholder; - return result; + function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; } /** - * This method is like `_.curry` except that arguments are applied to `func` - * in the manner of `_.partialRight` instead of `_.partial`. - * - * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for provided arguments. - * - * **Note:** This method doesn't set the "length" property of curried functions. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the new curried function. - * @example - * - * var abc = function(a, b, c) { - * return [a, b, c]; - * }; - * - * var curried = _.curryRight(abc); - * - * curried(3)(2)(1); - * // => [1, 2, 3] - * - * curried(2, 3)(1); - * // => [1, 2, 3] - * - * curried(1, 2, 3); - * // => [1, 2, 3] + * Creates a function like `_.camelCase`. * - * // Curried with placeholders. - * curried(3)(1, _)(2); - * // => [1, 2, 3] + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. */ - function curryRight(func, arity, guard) { - arity = guard ? undefined : arity; - var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); - result.placeholder = curryRight.placeholder; - return result; + function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; } /** - * Creates a debounced function that delays invoking `func` until after `wait` - * milliseconds have elapsed since the last time the debounced function was - * invoked. The debounced function comes with a `cancel` method to cancel - * delayed `func` invocations and a `flush` method to immediately invoke them. - * Provide `options` to indicate whether `func` should be invoked on the - * leading and/or trailing edge of the `wait` timeout. The `func` is invoked - * with the last arguments provided to the debounced function. Subsequent - * calls to the debounced function return the result of the last `func` - * invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the debounced function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.debounce` and `_.throttle`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to debounce. - * @param {number} [wait=0] The number of milliseconds to delay. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=false] - * Specify invoking on the leading edge of the timeout. - * @param {number} [options.maxWait] - * The maximum time `func` is allowed to be delayed before it's invoked. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new debounced function. - * @example - * - * // Avoid costly calculations while the window size is in flux. - * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); - * - * // Invoke `sendMail` when clicked, debouncing subsequent calls. - * jQuery(element).on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * })); - * - * // Ensure `batchLog` is invoked once after 1 second of debounced calls. - * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); - * var source = new EventSource('/stream'); - * jQuery(source).on('message', debounced); + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. * - * // Cancel the trailing debounced invocation. - * jQuery(window).on('popstate', debounced.cancel); + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. */ - function debounce(func, wait, options) { - var lastArgs, - lastThis, - maxWait, - result, - timerId, - lastCallTime, - lastInvokeTime = 0, - leading = false, - maxing = false, - trailing = true; - - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - wait = toNumber(wait) || 0; - if (isObject(options)) { - leading = !!options.leading; - maxing = 'maxWait' in options; - maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait; - trailing = 'trailing' in options ? !!options.trailing : trailing; - } + function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); - function invokeFunc(time) { - var args = lastArgs, - thisArg = lastThis; + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; + } - lastArgs = lastThis = undefined; - lastInvokeTime = time; - result = func.apply(thisArg, args); - return result; - } + /** + * Creates a function that wraps `func` to enable currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); - function leadingEdge(time) { - // Reset any `maxWait` timer. - lastInvokeTime = time; - // Start the timer for the trailing edge. - timerId = setTimeout(timerExpired, wait); - // Invoke the leading edge. - return leading ? invokeFunc(time) : result; - } + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); - function remainingWait(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime, - timeWaiting = wait - timeSinceLastCall; + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); - return maxing - ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke) - : timeWaiting; + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); } + return wrapper; + } - function shouldInvoke(time) { - var timeSinceLastCall = time - lastCallTime, - timeSinceLastInvoke = time - lastInvokeTime; + /** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ + function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = getIteratee(predicate, 3); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; + } - // Either this is the first call, activity has stopped and we're at the - // trailing edge, the system time has gone backwards and we're treating - // it as the trailing edge, or we've hit the `maxWait` limit. - return (lastCallTime === undefined || (timeSinceLastCall >= wait) || - (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); - } + /** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ + function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; - function timerExpired() { - var time = now(); - if (shouldInvoke(time)) { - return trailingEdge(time); + if (fromRight) { + funcs.reverse(); } - // Restart the timer. - timerId = setTimeout(timerExpired, remainingWait(time)); - } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; - function trailingEdge(time) { - timerId = undefined; + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; - // Only invoke if we have `lastArgs` which means `func` has been - // debounced at least once. - if (trailing && lastArgs) { - return invokeFunc(time); + if (data && isLaziable(data[0]) && + data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } } - lastArgs = lastThis = undefined; - return result; - } + return function() { + var args = arguments, + value = args[0]; - function cancel() { - if (timerId !== undefined) { - clearTimeout(timerId); - } - lastInvokeTime = 0; - lastArgs = lastCallTime = lastThis = timerId = undefined; - } + if (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; - function flush() { - return timerId === undefined ? result : trailingEdge(now()); - } + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); + } - function debounced() { - var time = now(), - isInvoking = shouldInvoke(time); + /** + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & WRAP_ARY_FLAG, + isBind = bitmask & WRAP_BIND_FLAG, + isBindKey = bitmask & WRAP_BIND_KEY_FLAG, + isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG), + isFlip = bitmask & WRAP_FLIP_FLAG, + Ctor = isBindKey ? undefined : createCtor(func); - lastArgs = arguments; - lastThis = this; - lastCallTime = time; + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; + + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; - if (isInvoking) { - if (timerId === undefined) { - return leadingEdge(lastCallTime); - } - if (maxing) { - // Handle invocations in a tight loop. - clearTimeout(timerId); - timerId = setTimeout(timerExpired, wait); - return invokeFunc(lastCallTime); - } + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); } - if (timerId === undefined) { - timerId = setTimeout(timerExpired, wait); + if (isAry && ary < length) { + args.length = ary; } - return result; + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); } - debounced.cancel = cancel; - debounced.flush = flush; - return debounced; + return wrapper; } /** - * Defers invoking the `func` until the current call stack has cleared. Any - * additional arguments are provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to defer. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example - * - * _.defer(function(text) { - * console.log(text); - * }, 'deferred'); - * // => Logs 'deferred' after one millisecond. - */ - var defer = baseRest(function(func, args) { - return baseDelay(func, 1, args); - }); - - /** - * Invokes `func` after `wait` milliseconds. Any additional arguments are - * provided to `func` when it's invoked. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay invocation. - * @param {...*} [args] The arguments to invoke `func` with. - * @returns {number} Returns the timer id. - * @example - * - * _.delay(function(text) { - * console.log(text); - * }, 1000, 'later'); - * // => Logs 'later' after one second. - */ - var delay = baseRest(function(func, wait, args) { - return baseDelay(func, toNumber(wait) || 0, args); - }); - - /** - * Creates a function that invokes `func` with arguments reversed. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to flip arguments for. - * @returns {Function} Returns the new flipped function. - * @example - * - * var flipped = _.flip(function() { - * return _.toArray(arguments); - * }); + * Creates a function like `_.invertBy`. * - * flipped('a', 'b', 'c', 'd'); - * // => ['d', 'c', 'b', 'a'] + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. */ - function flip(func) { - return createWrap(func, WRAP_FLIP_FLAG); + function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; } /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided, it determines the cache key for storing the result based on the - * arguments provided to the memoized function. By default, the first argument - * provided to the memoized function is used as the map cache key. The `func` - * is invoked with the `this` binding of the memoized function. - * - * **Note:** The cache is exposed as the `cache` property on the memoized - * function. Its creation may be customized by replacing the `_.memoize.Cache` - * constructor with one whose instances implement the - * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) - * method interface of `clear`, `delete`, `get`, `has`, and `set`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] The function to resolve the cache key. - * @returns {Function} Returns the new memoized function. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * var other = { 'c': 3, 'd': 4 }; - * - * var values = _.memoize(_.values); - * values(object); - * // => [1, 2] - * - * values(other); - * // => [3, 4] - * - * object.a = 2; - * values(object); - * // => [1, 2] - * - * // Modify the result cache. - * values.cache.set(object, ['a', 'b']); - * values(object); - * // => ['a', 'b'] + * Creates a function that performs a mathematical operation on two values. * - * // Replace `_.memoize.Cache`. - * _.memoize.Cache = WeakMap; + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. */ - function memoize(func, resolver) { - if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { - throw new TypeError(FUNC_ERROR_TEXT); - } - var memoized = function() { - var args = arguments, - key = resolver ? resolver.apply(this, args) : args[0], - cache = memoized.cache; - - if (cache.has(key)) { - return cache.get(key); + function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); } - var result = func.apply(this, args); - memoized.cache = cache.set(key, result) || cache; return result; }; - memoized.cache = new (memoize.Cache || MapCache); - return memoized; } - // Expose `MapCache`. - memoize.Cache = MapCache; - /** - * Creates a function that negates the result of the predicate `func`. The - * `func` predicate is invoked with the `this` binding and arguments of the - * created function. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} predicate The predicate to negate. - * @returns {Function} Returns the new negated function. - * @example - * - * function isEven(n) { - * return n % 2 == 0; - * } + * Creates a function like `_.over`. * - * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); - * // => [1, 3, 5] + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. */ - function negate(predicate) { - if (typeof predicate != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - return function() { - var args = arguments; - switch (args.length) { - case 0: return !predicate.call(this); - case 1: return !predicate.call(this, args[0]); - case 2: return !predicate.call(this, args[0], args[1]); - case 3: return !predicate.call(this, args[0], args[1], args[2]); - } - return !predicate.apply(this, args); - }; + function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(getIteratee())); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); } /** - * Creates a function that is restricted to invoking `func` once. Repeat calls - * to the function return the value of the first invocation. The `func` is - * invoked with the `this` binding and arguments of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // => `createApplication` is invoked once + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. */ - function once(func) { - return before(2, func); + function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); } /** - * Creates a function that invokes `func` with its arguments transformed. + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. * - * @static - * @since 4.0.0 - * @memberOf _ - * @category Function + * @private * @param {Function} func The function to wrap. - * @param {...(Function|Function[])} [transforms=[_.identity]] - * The argument transforms. - * @returns {Function} Returns the new function. - * @example - * - * function doubled(n) { - * return n * 2; - * } - * - * function square(n) { - * return n * n; - * } - * - * var func = _.overArgs(function(x, y) { - * return [x, y]; - * }, [square, doubled]); - * - * func(9, 3); - * // => [81, 6] - * - * func(10, 5); - * // => [100, 10] + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. */ - var overArgs = castRest(function(func, transforms) { - transforms = (transforms.length == 1 && isArray(transforms[0])) - ? arrayMap(transforms[0], baseUnary(getIteratee())) - : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee())); + function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG, + Ctor = createCtor(func); - var funcsLength = transforms.length; - return baseRest(function(args) { - var index = -1, - length = nativeMin(args.length, funcsLength); + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; - while (++index < length) { - args[index] = transforms[index].call(this, args[index]); + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; } - return apply(func, this, args); - }); - }); - - /** - * Creates a function that invokes `func` with `partials` prepended to the - * arguments it receives. This method is like `_.bind` except it does **not** - * alter the `this` binding. - * - * The `_.partial.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @since 0.2.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var sayHelloTo = _.partial(greet, 'hello'); - * sayHelloTo('fred'); - * // => 'hello fred' - * - * // Partially applied with placeholders. - * var greetFred = _.partial(greet, _, 'fred'); - * greetFred('hi'); - * // => 'hi fred' - */ - var partial = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partial)); - return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); - }); + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; + } /** - * This method is like `_.partial` except that partially applied arguments - * are appended to the arguments it receives. - * - * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic - * builds, may be used as a placeholder for partially applied arguments. - * - * **Note:** This method doesn't set the "length" property of partially - * applied functions. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Function - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [partials] The arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * function greet(greeting, name) { - * return greeting + ' ' + name; - * } - * - * var greetFred = _.partialRight(greet, 'fred'); - * greetFred('hi'); - * // => 'hi fred' + * Creates a `_.range` or `_.rangeRight` function. * - * // Partially applied with placeholders. - * var sayHelloTo = _.partialRight(greet, 'hello', _); - * sayHelloTo('fred'); - * // => 'hello fred' + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. */ - var partialRight = baseRest(function(func, partials) { - var holders = replaceHolders(partials, getHolder(partialRight)); - return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); - }); + function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; + } /** - * Creates a function that invokes `func` with arguments arranged according - * to the specified `indexes` where the argument value at the first index is - * provided as the first argument, the argument value at the second index is - * provided as the second argument, and so on. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Function - * @param {Function} func The function to rearrange arguments for. - * @param {...(number|number[])} indexes The arranged argument indexes. - * @returns {Function} Returns the new function. - * @example - * - * var rearged = _.rearg(function(a, b, c) { - * return [a, b, c]; - * }, [2, 0, 1]); + * Creates a function that performs a relational operation on two values. * - * rearged('b', 'c', 'a') - * // => ['a', 'b', 'c'] + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. */ - var rearg = flatRest(function(func, indexes) { - return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); - }); + function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; + } /** - * Creates a function that invokes `func` with the `this` binding of the - * created function and arguments from `start` and beyond provided as - * an array. - * - * **Note:** This method is based on the - * [rest parameter](https://mdn.io/rest_parameters). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to apply a rest parameter to. - * @param {number} [start=func.length-1] The start position of the rest parameter. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.rest(function(what, names) { - * return what + ' ' + _.initial(names).join(', ') + - * (_.size(names) > 1 ? ', & ' : '') + _.last(names); - * }); + * Creates a function that wraps `func` to continue currying. * - * say('hello', 'fred', 'barney', 'pebbles'); - * // => 'hello fred, barney, & pebbles' + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. */ - function rest(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); + function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG); + + if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) { + bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG); } - start = start === undefined ? start : toInteger(start); - return baseRest(func, start); + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; + + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); } /** - * Creates a function that invokes `func` with the `this` binding of the - * create function and an array of arguments much like - * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). - * - * **Note:** This method is based on the - * [spread operator](https://mdn.io/spread_operator). - * - * @static - * @memberOf _ - * @since 3.2.0 - * @category Function - * @param {Function} func The function to spread arguments over. - * @param {number} [start=0] The start position of the spread. - * @returns {Function} Returns the new function. - * @example - * - * var say = _.spread(function(who, what) { - * return who + ' says ' + what; - * }); - * - * say(['fred', 'hello']); - * // => 'fred says hello' - * - * var numbers = Promise.all([ - * Promise.resolve(40), - * Promise.resolve(36) - * ]); + * Creates a function like `_.round`. * - * numbers.then(_.spread(function(x, y) { - * return x + y; - * })); - * // => a Promise of 76 + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. */ - function spread(func, start) { - if (typeof func != 'function') { - throw new TypeError(FUNC_ERROR_TEXT); - } - start = start == null ? 0 : nativeMax(toInteger(start), 0); - return baseRest(function(args) { - var array = args[start], - otherArgs = castSlice(args, 0, start); + function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin(toInteger(precision), 292); + if (precision && nativeIsFinite(number)) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); - if (array) { - arrayPush(otherArgs, array); + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); } - return apply(func, this, otherArgs); - }); + return func(number); + }; } /** - * Creates a throttled function that only invokes `func` at most once per - * every `wait` milliseconds. The throttled function comes with a `cancel` - * method to cancel delayed `func` invocations and a `flush` method to - * immediately invoke them. Provide `options` to indicate whether `func` - * should be invoked on the leading and/or trailing edge of the `wait` - * timeout. The `func` is invoked with the last arguments provided to the - * throttled function. Subsequent calls to the throttled function return the - * result of the last `func` invocation. - * - * **Note:** If `leading` and `trailing` options are `true`, `func` is - * invoked on the trailing edge of the timeout only if the throttled function - * is invoked more than once during the `wait` timeout. - * - * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred - * until to the next tick, similar to `setTimeout` with a timeout of `0`. - * - * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) - * for details over the differences between `_.throttle` and `_.debounce`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {Function} func The function to throttle. - * @param {number} [wait=0] The number of milliseconds to throttle invocations to. - * @param {Object} [options={}] The options object. - * @param {boolean} [options.leading=true] - * Specify invoking on the leading edge of the timeout. - * @param {boolean} [options.trailing=true] - * Specify invoking on the trailing edge of the timeout. - * @returns {Function} Returns the new throttled function. - * @example - * - * // Avoid excessively updating the position while scrolling. - * jQuery(window).on('scroll', _.throttle(updatePosition, 100)); + * Creates a set object of `values`. * - * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes. - * var throttled = _.throttle(renewToken, 300000, { 'trailing': false }); - * jQuery(element).on('click', throttled); + * @private + * @param {Array} values The values to add to the set. + * @returns {Object} Returns the new set. + */ + var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) { + return new Set(values); + }; + + /** + * Creates a `_.toPairs` or `_.toPairsIn` function. * - * // Cancel the trailing throttled invocation. - * jQuery(window).on('popstate', throttled.cancel); + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. */ - function throttle(func, wait, options) { - var leading = true, - trailing = true; + function createToPairs(keysFunc) { + return function(object) { + var tag = getTag(object); + if (tag == mapTag) { + return mapToArray(object); + } + if (tag == setTag) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; + } - if (typeof func != 'function') { + /** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ + function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG; + if (!isBindKey && typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } - if (isObject(options)) { - leading = 'leading' in options ? !!options.leading : leading; - trailing = 'trailing' in options ? !!options.trailing : trailing; + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG); + partials = holders = undefined; } - return debounce(func, wait, { - 'leading': leading, - 'maxWait': wait, - 'trailing': trailing - }); + ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined + ? (isBindKey ? 0 : func.length) + : nativeMax(newData[9] - length, 0); + + if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) { + bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); } /** - * Creates a function that accepts up to one argument, ignoring any - * additional arguments. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Function - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - * @example + * Used by `_.defaults` to customize its `_.assignIn` use to assign properties + * of source objects to the destination object for all destination properties + * that resolve to `undefined`. * - * _.map(['6', '8', '10'], _.unary(parseInt)); - * // => [6, 8, 10] + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. */ - function unary(func) { - return ary(func, 1); + function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) { + return srcValue; + } + return objValue; } /** - * Creates a function that provides `value` to `wrapper` as its first - * argument. Any additional arguments provided to the function are appended - * to those provided to the `wrapper`. The wrapper is invoked with the `this` - * binding of the created function. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Function - * @param {*} value The value to wrap. - * @param {Function} [wrapper=identity] The wrapper function. - * @returns {Function} Returns the new function. - * @example - * - * var p = _.wrap(_.escape, function(func, text) { - * return '

' + func(text) + '

'; - * }); + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. * - * p('fred, barney, & pebbles'); - * // => '

fred, barney, & pebbles

' + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. */ - function wrap(value, wrapper) { - return partial(castFunction(wrapper), value); + function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); + stack['delete'](srcValue); + } + return objValue; } - /*------------------------------------------------------------------------*/ - /** - * Casts `value` as an array if it's not one. + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. * - * @static - * @memberOf _ - * @since 4.4.0 - * @category Lang + * @private * @param {*} value The value to inspect. - * @returns {Array} Returns the cast array. - * @example - * - * _.castArray(1); - * // => [1] - * - * _.castArray({ 'a': 1 }); - * // => [{ 'a': 1 }] - * - * _.castArray('abc'); - * // => ['abc'] - * - * _.castArray(null); - * // => [null] - * - * _.castArray(undefined); - * // => [undefined] - * - * _.castArray(); - * // => [] + * @param {string} key The key of the property to inspect. + * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. + */ + function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; + } + + /** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. * - * var array = [1, 2, 3]; - * console.log(_.castArray(array) === array); - * // => true + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. */ - function castArray() { - if (!arguments.length) { - return []; + function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; } - var value = arguments[0]; - return isArray(value) ? value : [value]; + // Check that cyclic values are equal. + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; } /** - * Creates a shallow clone of `value`. - * - * **Note:** This method is loosely based on the - * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) - * and supports cloning arrays, array buffers, booleans, date objects, maps, - * numbers, `Object` objects, regexes, sets, strings, symbols, and typed - * arrays. The own enumerable properties of `arguments` objects are cloned - * as plain objects. An empty object is returned for uncloneable values such - * as error objects, functions, DOM nodes, and WeakMaps. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to clone. - * @returns {*} Returns the cloned value. - * @see _.cloneDeep - * @example + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. * - * var shallow = _.clone(objects); - * console.log(shallow[0] === objects[0]); - * // => true + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ - function clone(value) { - return baseClone(value, CLONE_SYMBOLS_FLAG); + function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag: + case dateTag: + case numberTag: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag: + case stringTag: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag: + var convert = mapToArray; + + case setTag: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; } /** - * This method is like `_.clone` except that it accepts `customizer` which - * is invoked to produce the cloned value. If `customizer` returns `undefined`, - * cloning is handled by the method instead. The `customizer` is invoked with - * up to four arguments; (value [, index|key, object, stack]). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the cloned value. - * @see _.cloneDeepWith - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(false); - * } - * } - * - * var el = _.cloneWith(document.body, customizer); + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 0 + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. */ - function cloneWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_SYMBOLS_FLAG, customizer); - } + function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; - /** - * This method is like `_.clone` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 1.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @returns {*} Returns the deep cloned value. - * @see _.clone - * @example - * - * var objects = [{ 'a': 1 }, { 'b': 2 }]; - * - * var deep = _.cloneDeep(objects); - * console.log(deep[0] === objects[0]); - * // => false - */ - function cloneDeep(value) { - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG); + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) { + return false; + } + } + // Check that cyclic values are equal. + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; } /** - * This method is like `_.cloneWith` except that it recursively clones `value`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to recursively clone. - * @param {Function} [customizer] The function to customize cloning. - * @returns {*} Returns the deep cloned value. - * @see _.cloneWith - * @example - * - * function customizer(value) { - * if (_.isElement(value)) { - * return value.cloneNode(true); - * } - * } - * - * var el = _.cloneDeepWith(document.body, customizer); + * A specialized version of `baseRest` which flattens the rest array. * - * console.log(el === document.body); - * // => false - * console.log(el.nodeName); - * // => 'BODY' - * console.log(el.childNodes.length); - * // => 20 + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. */ - function cloneDeepWith(value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer); + function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); } /** - * Checks if `object` conforms to `source` by invoking the predicate - * properties of `source` with the corresponding property values of `object`. - * - * **Note:** This method is equivalent to `_.conforms` when `source` is - * partially applied. - * - * @static - * @memberOf _ - * @since 4.14.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property predicates to conform to. - * @returns {boolean} Returns `true` if `object` conforms, else `false`. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); - * // => true + * Creates an array of own enumerable property names and symbols of `object`. * - * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); - * // => false + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. */ - function conformsTo(object, source) { - return source == null || baseConformsTo(object, source, keys(source)); + function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); } /** - * Performs a - * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) - * comparison between two values to determine if they are equivalent. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.eq(object, object); - * // => true - * - * _.eq(object, other); - * // => false - * - * _.eq('a', 'a'); - * // => true - * - * _.eq('a', Object('a')); - * // => false + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. * - * _.eq(NaN, NaN); - * // => true + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. */ - function eq(value, other) { - return value === other || (value !== value && other !== other); + function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); } /** - * Checks if `value` is greater than `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than `other`, - * else `false`. - * @see _.lt - * @example - * - * _.gt(3, 1); - * // => true - * - * _.gt(3, 3); - * // => false + * Gets metadata for `func`. * - * _.gt(1, 3); - * // => false + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. */ - var gt = createRelationalOperation(baseGt); + var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); + }; /** - * Checks if `value` is greater than or equal to `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is greater than or equal to - * `other`, else `false`. - * @see _.lte - * @example - * - * _.gte(3, 1); - * // => true - * - * _.gte(3, 3); - * // => true + * Gets the name of `func`. * - * _.gte(1, 3); - * // => false + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. */ - var gte = createRelationalOperation(function(value, other) { - return value >= other; - }); + function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; + } /** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true + * Gets the argument placeholder value for `func`. * - * _.isArguments([1, 2, 3]); - * // => false + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. */ - var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); - }; + function getHolder(func) { + var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func; + return object.placeholder; + } /** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false + * Gets the appropriate "iteratee" function. If `_.iteratee` is customized, + * this function returns the custom method, otherwise it returns `baseIteratee`. + * If arguments are provided, the chosen function is invoked with them and + * its result is returned. * - * _.isArray(_.noop); - * // => false + * @private + * @param {*} [value] The value to convert to an iteratee. + * @param {number} [arity] The arity of the created iteratee. + * @returns {Function} Returns the chosen function or its result. */ - var isArray = Array.isArray; + function getIteratee() { + var result = lodash.iteratee || iteratee; + result = result === iteratee ? baseIteratee : result; + return arguments.length ? result(arguments[0], arguments[1]) : result; + } /** - * Checks if `value` is classified as an `ArrayBuffer` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. - * @example - * - * _.isArrayBuffer(new ArrayBuffer(2)); - * // => true + * Gets the data for `map`. * - * _.isArrayBuffer(new Array(2)); - * // => false + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. */ - var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; + } /** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true + * Gets the property names, values, and compare flags of `object`. * - * _.isArrayLike(_.noop); - * // => false + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. */ - function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); + function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; } /** - * This method is like `_.isArrayLike` except that it also checks if `value` - * is an object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array-like object, - * else `false`. - * @example - * - * _.isArrayLikeObject([1, 2, 3]); - * // => true - * - * _.isArrayLikeObject(document.body.children); - * // => true - * - * _.isArrayLikeObject('abc'); - * // => false + * Gets the native function at `key` of `object`. * - * _.isArrayLikeObject(_.noop); - * // => false + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. */ - function isArrayLikeObject(value) { - return isObjectLike(value) && isArrayLike(value); + function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; } /** - * Checks if `value` is classified as a boolean primitive or object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. - * @example - * - * _.isBoolean(false); - * // => true + * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. * - * _.isBoolean(null); - * // => false + * @private + * @param {*} value The value to query. + * @returns {string} Returns the raw `toStringTag`. */ - function isBoolean(value) { - return value === true || value === false || - (isObjectLike(value) && baseGetTag(value) == boolTag); + function getRawTag(value) { + var isOwn = hasOwnProperty.call(value, symToStringTag), + tag = value[symToStringTag]; + + try { + value[symToStringTag] = undefined; + var unmasked = true; + } catch (e) {} + + var result = nativeObjectToString.call(value); + if (unmasked) { + if (isOwn) { + value[symToStringTag] = tag; + } else { + delete value[symToStringTag]; + } + } + return result; } /** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true + * Creates an array of the own enumerable symbols of `object`. * - * _.isBuffer(new Uint8Array(2)); - * // => false + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. */ - var isBuffer = nativeIsBuffer || stubFalse; + var getSymbols = !nativeGetSymbols ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); + }; /** - * Checks if `value` is classified as a `Date` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a date object, else `false`. - * @example - * - * _.isDate(new Date); - * // => true + * Creates an array of the own and inherited enumerable symbols of `object`. * - * _.isDate('Mon April 23 2012'); - * // => false + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. */ - var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; + }; /** - * Checks if `value` is likely a DOM element. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. - * @example - * - * _.isElement(document.body); - * // => true + * Gets the `toStringTag` of `value`. * - * _.isElement(''); - * // => false + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. */ - function isElement(value) { - return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); + var getTag = baseGetTag; + + // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. + if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) || + (Map && getTag(new Map) != mapTag) || + (Promise && getTag(Promise.resolve()) != promiseTag) || + (Set && getTag(new Set) != setTag) || + (WeakMap && getTag(new WeakMap) != weakMapTag)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag; + case mapCtorString: return mapTag; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag; + case weakMapCtorString: return weakMapTag; + } + } + return result; + }; } /** - * Checks if `value` is an empty object, collection, map, or set. - * - * Objects are considered empty if they have no own enumerable string keyed - * properties. - * - * Array-like values such as `arguments` objects, arrays, buffers, strings, or - * jQuery-like collections are considered empty if they have a `length` of `0`. - * Similarly, maps and sets are considered empty if they have a `size` of `0`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is empty, else `false`. - * @example - * - * _.isEmpty(null); - * // => true - * - * _.isEmpty(true); - * // => true - * - * _.isEmpty(1); - * // => true - * - * _.isEmpty([1, 2, 3]); - * // => false + * Gets the view, applying any `transforms` to the `start` and `end` positions. * - * _.isEmpty({ 'a': 1 }); - * // => false + * @private + * @param {number} start The start of the view. + * @param {number} end The end of the view. + * @param {Array} transforms The transformations to apply to the view. + * @returns {Object} Returns an object containing the `start` and `end` + * positions of the view. */ - function isEmpty(value) { - if (value == null) { - return true; - } - if (isArrayLike(value) && - (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || - isBuffer(value) || isTypedArray(value) || isArguments(value))) { - return !value.length; - } - var tag = getTag(value); - if (tag == mapTag || tag == setTag) { - return !value.size; - } - if (isPrototype(value)) { - return !baseKeys(value).length; - } - for (var key in value) { - if (hasOwnProperty.call(value, key)) { - return false; + function getView(start, end, transforms) { + var index = -1, + length = transforms.length; + + while (++index < length) { + var data = transforms[index], + size = data.size; + + switch (data.type) { + case 'drop': start += size; break; + case 'dropRight': end -= size; break; + case 'take': end = nativeMin(end, start + size); break; + case 'takeRight': start = nativeMax(start, end - size); break; } } - return true; + return { 'start': start, 'end': end }; } /** - * Performs a deep comparison between two values to determine if they are - * equivalent. - * - * **Note:** This method supports comparing arrays, array buffers, booleans, - * date objects, error objects, maps, numbers, `Object` objects, regexes, - * sets, strings, symbols, and typed arrays. `Object` objects are compared - * by their own, not inherited, enumerable properties. Functions and DOM - * nodes are compared by strict equality, i.e. `===`. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'a': 1 }; - * var other = { 'a': 1 }; - * - * _.isEqual(object, other); - * // => true + * Extracts wrapper details from the `source` body comment. * - * object === other; - * // => false + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. */ - function isEqual(value, other) { - return baseIsEqual(value, other); + function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; } /** - * This method is like `_.isEqual` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with up to - * six arguments: (objValue, othValue [, index|key, object, other, stack]). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, othValue) { - * if (isGreeting(objValue) && isGreeting(othValue)) { - * return true; - * } - * } - * - * var array = ['hello', 'goodbye']; - * var other = ['hi', 'goodbye']; + * Checks if `path` exists on `object`. * - * _.isEqualWith(array, other, customizer); - * // => true + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. */ - function isEqualWith(value, other, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - var result = customizer ? customizer(value, other) : undefined; - return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; + function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); } /** - * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, - * `SyntaxError`, `TypeError`, or `URIError` object. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an error object, else `false`. - * @example - * - * _.isError(new Error); - * // => true + * Initializes an array clone. * - * _.isError(Error); - * // => false + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. */ - function isError(value) { - if (!isObjectLike(value)) { - return false; + function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { + result.index = array.index; + result.input = array.input; } - var tag = baseGetTag(value); - return tag == errorTag || tag == domExcTag || - (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); + return result; } /** - * Checks if `value` is a finite primitive number. - * - * **Note:** This method is based on - * [`Number.isFinite`](https://mdn.io/Number/isFinite). - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. - * @example - * - * _.isFinite(3); - * // => true - * - * _.isFinite(Number.MIN_VALUE); - * // => true - * - * _.isFinite(Infinity); - * // => false + * Initializes an object clone. * - * _.isFinite('3'); - * // => false + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. */ - function isFinite(value) { - return typeof value == 'number' && nativeIsFinite(value); + function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; } /** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example + * Initializes an object clone based on its `toStringTag`. * - * _.isFunction(_); - * // => true + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. * - * _.isFunction(/abc/); - * // => false + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. */ - function isFunction(value) { - if (!isObject(value)) { - return false; + function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag: + return cloneArrayBuffer(object); + + case boolTag: + case dateTag: + return new Ctor(+object); + + case dataViewTag: + return cloneDataView(object, isDeep); + + case float32Tag: case float64Tag: + case int8Tag: case int16Tag: case int32Tag: + case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: + return cloneTypedArray(object, isDeep); + + case mapTag: + return new Ctor; + + case numberTag: + case stringTag: + return new Ctor(object); + + case regexpTag: + return cloneRegExp(object); + + case setTag: + return new Ctor; + + case symbolTag: + return cloneSymbol(object); } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; } /** - * Checks if `value` is an integer. - * - * **Note:** This method is based on - * [`Number.isInteger`](https://mdn.io/Number/isInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an integer, else `false`. - * @example - * - * _.isInteger(3); - * // => true - * - * _.isInteger(Number.MIN_VALUE); - * // => false - * - * _.isInteger(Infinity); - * // => false + * Inserts wrapper `details` in a comment at the top of the `source` body. * - * _.isInteger('3'); - * // => false + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. */ - function isInteger(value) { - return typeof value == 'number' && value == toInteger(value); + function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); } /** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * Checks if `value` is a flattenable `arguments` object or array. * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang + * @private * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. */ - function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; + function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); } /** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * Checks if `value` is a valid array-like index. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang + * @private * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. */ - function isObject(value) { + function isIndex(value, length) { var type = typeof value; - return value != null && (type == 'object' || type == 'function'); + length = length == null ? MAX_SAFE_INTEGER : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); } /** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true + * Checks if the given arguments are from an iteratee call. * - * _.isObjectLike(_.noop); - * // => false + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ + function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; + } + + /** + * Checks if `value` is a property name and not a property path. * - * _.isObjectLike(null); - * // => false + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. */ - function isObjectLike(value) { - return value != null && typeof value == 'object'; + function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); } /** - * Checks if `value` is classified as a `Map` object. + * Checks if `value` is suitable for use as unique object key. * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang + * @private * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a map, else `false`. - * @example - * - * _.isMap(new Map); - * // => true - * - * _.isMap(new WeakMap); - * // => false + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. */ - var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); + } /** - * Performs a partial deep comparison between `object` and `source` to - * determine if `object` contains equivalent property values. - * - * **Note:** This method is equivalent to `_.matches` when `source` is - * partially applied. - * - * Partial comparisons will match empty array and empty object `source` - * values against any array or object value, respectively. See `_.isEqual` - * for a list of supported value comparisons. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - * @example - * - * var object = { 'a': 1, 'b': 2 }; - * - * _.isMatch(object, { 'b': 2 }); - * // => true + * Checks if `func` has a lazy counterpart. * - * _.isMatch(object, { 'b': 1 }); - * // => false + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. */ - function isMatch(object, source) { - return object === source || baseIsMatch(object, source, getMatchData(source)); + function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; } /** - * This method is like `_.isMatch` except that it accepts `customizer` which - * is invoked to compare values. If `customizer` returns `undefined`, comparisons - * are handled by the method instead. The `customizer` is invoked with five - * arguments: (objValue, srcValue, index|key, object, source). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {Object} object The object to inspect. - * @param {Object} source The object of property values to match. - * @param {Function} [customizer] The function to customize comparisons. - * @returns {boolean} Returns `true` if `object` is a match, else `false`. - * @example - * - * function isGreeting(value) { - * return /^h(?:i|ello)$/.test(value); - * } - * - * function customizer(objValue, srcValue) { - * if (isGreeting(objValue) && isGreeting(srcValue)) { - * return true; - * } - * } - * - * var object = { 'greeting': 'hello' }; - * var source = { 'greeting': 'hi' }; + * Checks if `func` has its source masked. * - * _.isMatchWith(object, source, customizer); - * // => true + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. */ - function isMatchWith(object, source, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return baseIsMatch(object, source, getMatchData(source), customizer); + function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); } /** - * Checks if `value` is `NaN`. - * - * **Note:** This method is based on - * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as - * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for - * `undefined` and other non-number values. + * Checks if `func` is capable of being masked. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang + * @private * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. */ - function isNaN(value) { - // An `NaN` primitive is the only value that is not equal to itself. - // Perform the `toStringTag` check first to avoid errors with some - // ActiveX objects in IE. - return isNumber(value) && value != +value; - } + var isMaskable = coreJsData ? isFunction : stubFalse; /** - * Checks if `value` is a pristine native function. - * - * **Note:** This method can't reliably detect native functions in the presence - * of the core-js package because core-js circumvents this kind of detection. - * Despite multiple requests, the core-js maintainer has made it clear: any - * attempt to fix the detection will be obstructed. As a result, we're left - * with little choice but to throw an error. Unfortunately, this also affects - * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), - * which rely on core-js. + * Checks if `value` is likely a prototype object. * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang + * @private * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a native function, - * else `false`. - * @example - * - * _.isNative(Array.prototype.push); - * // => true - * - * _.isNative(_); - * // => false + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. */ - function isNative(value) { - if (isMaskable(value)) { - throw new Error(CORE_ERROR_TEXT); - } - return baseIsNative(value); + function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto; + + return value === proto; } /** - * Checks if `value` is `null`. + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang + * @private * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `null`, else `false`. - * @example - * - * _.isNull(null); - * // => true - * - * _.isNull(void 0); - * // => false + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. */ - function isNull(value) { - return value === null; + function isStrictComparable(value) { + return value === value && !isObject(value); } /** - * Checks if `value` is `null` or `undefined`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is nullish, else `false`. - * @example - * - * _.isNil(null); - * // => true - * - * _.isNil(void 0); - * // => true + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. * - * _.isNil(NaN); - * // => false + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. */ - function isNil(value) { - return value == null; + function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; } /** - * Checks if `value` is classified as a `Number` primitive or object. - * - * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are - * classified as numbers, use the `_.isFinite` method. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a number, else `false`. - * @example - * - * _.isNumber(3); - * // => true - * - * _.isNumber(Number.MIN_VALUE); - * // => true - * - * _.isNumber(Infinity); - * // => true + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. * - * _.isNumber('3'); - * // => false + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. */ - function isNumber(value) { - return typeof value == 'number' || - (isObjectLike(value) && baseGetTag(value) == numberTag); + function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; } /** - * Checks if `value` is a plain object, that is, an object created by the - * `Object` constructor or one with a `[[Prototype]]` of `null`. - * - * @static - * @memberOf _ - * @since 0.8.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Foo() { - * this.a = 1; - * } - * - * _.isPlainObject(new Foo); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false + * Merges the function metadata of `source` into `data`. * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. * - * _.isPlainObject(Object.create(null)); - * // => true + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. */ - function isPlainObject(value) { - if (!isObjectLike(value) || baseGetTag(value) != objectTag) { - return false; + function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG); + + var isCombo = + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) || + ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) || + ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; } - var proto = getPrototype(value); - if (proto === null) { - return true; + // Use source `thisArg` if available. + if (srcBitmask & WRAP_BIND_FLAG) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG; } - var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor; - return typeof Ctor == 'function' && Ctor instanceof Ctor && - funcToString.call(Ctor) == objectCtorString; + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & WRAP_ARY_FLAG) { + data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; } /** - * Checks if `value` is classified as a `RegExp` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. - * @example - * - * _.isRegExp(/abc/); - * // => true + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. * - * _.isRegExp('/abc/'); - * // => false + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. */ - var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; + } /** - * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 - * double precision number which isn't the result of a rounded unsafe integer. - * - * **Note:** This method is based on - * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. - * @example - * - * _.isSafeInteger(3); - * // => true - * - * _.isSafeInteger(Number.MIN_VALUE); - * // => false - * - * _.isSafeInteger(Infinity); - * // => false + * Converts `value` to a string using `Object.prototype.toString`. * - * _.isSafeInteger('3'); - * // => false + * @private + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. */ - function isSafeInteger(value) { - return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER; + function objectToString(value) { + return nativeObjectToString.call(value); } /** - * Checks if `value` is classified as a `Set` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a set, else `false`. - * @example - * - * _.isSet(new Set); - * // => true + * A specialized version of `baseRest` which transforms the rest array. * - * _.isSet(new WeakSet); - * // => false + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. */ - var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + function overRest(func, start, transform) { + start = nativeMax(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax(args.length - start, 0), + array = Array(length); - /** - * Checks if `value` is classified as a `String` primitive or object. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a string, else `false`. - * @example - * - * _.isString('abc'); - * // => true - * - * _.isString(1); - * // => false - */ - function isString(value) { - return typeof value == 'string' || - (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; } /** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true + * Gets the parent value at `path` of `object`. * - * _.isSymbol('abc'); - * // => false + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. */ - function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); + function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); } /** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. * - * _.isTypedArray([]); - * // => false + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. */ - var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin(indexes.length, arrLength), + oldArray = copyArray(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; + } /** - * Checks if `value` is `undefined`. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. - * @example - * - * _.isUndefined(void 0); - * // => true + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". * - * _.isUndefined(null); - * // => false + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. */ - function isUndefined(value) { - return value === undefined; + function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; } /** - * Checks if `value` is classified as a `WeakMap` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. - * @example + * Sets metadata for `func`. * - * _.isWeakMap(new WeakMap); - * // => true + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. * - * _.isWeakMap(new Map); - * // => false + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. */ - function isWeakMap(value) { - return isObjectLike(value) && getTag(value) == weakMapTag; - } + var setData = shortOut(baseSetData); /** - * Checks if `value` is classified as a `WeakSet` object. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. - * @example - * - * _.isWeakSet(new WeakSet); - * // => true + * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout). * - * _.isWeakSet(new Set); - * // => false + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @returns {number|Object} Returns the timer id or timeout object. */ - function isWeakSet(value) { - return isObjectLike(value) && baseGetTag(value) == weakSetTag; - } + var setTimeout = ctxSetTimeout || function(func, wait) { + return root.setTimeout(func, wait); + }; /** - * Checks if `value` is less than `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than `other`, - * else `false`. - * @see _.gt - * @example - * - * _.lt(1, 3); - * // => true - * - * _.lt(3, 3); - * // => false + * Sets the `toString` method of `func` to return `string`. * - * _.lt(3, 1); - * // => false + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. */ - var lt = createRelationalOperation(baseLt); + var setToString = shortOut(baseSetToString); /** - * Checks if `value` is less than or equal to `other`. - * - * @static - * @memberOf _ - * @since 3.9.0 - * @category Lang - * @param {*} value The value to compare. - * @param {*} other The other value to compare. - * @returns {boolean} Returns `true` if `value` is less than or equal to - * `other`, else `false`. - * @see _.gte - * @example - * - * _.lte(1, 3); - * // => true - * - * _.lte(3, 3); - * // => true + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. * - * _.lte(3, 1); - * // => false + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. */ - var lte = createRelationalOperation(function(value, other) { - return value <= other; - }); + function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); + } /** - * Converts `value` to an array. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Lang - * @param {*} value The value to convert. - * @returns {Array} Returns the converted array. - * @example - * - * _.toArray({ 'a': 1, 'b': 2 }); - * // => [1, 2] - * - * _.toArray('abc'); - * // => ['a', 'b', 'c'] - * - * _.toArray(1); - * // => [] + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. * - * _.toArray(null); - * // => [] + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. */ - function toArray(value) { - if (!value) { - return []; - } - if (isArrayLike(value)) { - return isString(value) ? stringToArray(value) : copyArray(value); - } - if (symIterator && value[symIterator]) { - return iteratorToArray(value[symIterator]()); - } - var tag = getTag(value), - func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values); + function shortOut(func) { + var count = 0, + lastCalled = 0; - return func(value); + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; } /** - * Converts `value` to a finite number. - * - * @static - * @memberOf _ - * @since 4.12.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted number. - * @example - * - * _.toFinite(3.2); - * // => 3.2 - * - * _.toFinite(Number.MIN_VALUE); - * // => 5e-324 - * - * _.toFinite(Infinity); - * // => 1.7976931348623157e+308 + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. * - * _.toFinite('3.2'); - * // => 3.2 + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. */ - function toFinite(value) { - if (!value) { - return value === 0 ? value : 0; - } - value = toNumber(value); - if (value === INFINITY || value === -INFINITY) { - var sign = (value < 0 ? -1 : 1); - return sign * MAX_INTEGER; + function shuffleSelf(array, size) { + var index = -1, + length = array.length, + lastIndex = length - 1; + + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; } - return value === value ? value : 0; + array.length = size; + return array; } /** - * Converts `value` to an integer. - * - * **Note:** This method is loosely based on - * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toInteger(3.2); - * // => 3 - * - * _.toInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toInteger(Infinity); - * // => 1.7976931348623157e+308 + * Converts `string` to a property path array. * - * _.toInteger('3.2'); - * // => 3 + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. */ - function toInteger(value) { - var result = toFinite(value), - remainder = result % 1; + var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; + }); - return result === result ? (remainder ? result - remainder : result) : 0; + /** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ + function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; } /** - * Converts `value` to an integer suitable for use as the length of an - * array-like object. - * - * **Note:** This method is based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. - * @example - * - * _.toLength(3.2); - * // => 3 - * - * _.toLength(Number.MIN_VALUE); - * // => 0 - * - * _.toLength(Infinity); - * // => 4294967295 + * Converts `func` to its source code. * - * _.toLength('3.2'); - * // => 3 + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. */ - function toLength(value) { - return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0; + function toSource(func) { + if (func != null) { + try { + return funcToString.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; } /** - * Converts `value` to a number. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to process. - * @returns {number} Returns the number. - * @example - * - * _.toNumber(3.2); - * // => 3.2 - * - * _.toNumber(Number.MIN_VALUE); - * // => 5e-324 + * Updates wrapper `details` based on `bitmask` flags. * - * _.toNumber(Infinity); - * // => Infinity + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ + function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); + } + + /** + * Creates a clone of `wrapper`. * - * _.toNumber('3.2'); - * // => 3.2 + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. */ - function toNumber(value) { - if (typeof value == 'number') { - return value; - } - if (isSymbol(value)) { - return NAN; - } - if (isObject(value)) { - var other = typeof value.valueOf == 'function' ? value.valueOf() : value; - value = isObject(other) ? (other + '') : other; - } - if (typeof value != 'string') { - return value === 0 ? value : +value; + function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); } - value = baseTrim(value); - var isBinary = reIsBinary.test(value); - return (isBinary || reIsOctal.test(value)) - ? freeParseInt(value.slice(2), isBinary ? 2 : 8) - : (reIsBadHex.test(value) ? NAN : +value); + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; } + /*------------------------------------------------------------------------*/ + /** - * Converts `value` to a plain object flattening inherited enumerable string - * keyed properties of `value` to own properties of the plain object. + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. * * @static * @memberOf _ * @since 3.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {Object} Returns the converted plain object. + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. * @example * - * function Foo() { - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.assign({ 'a': 1 }, new Foo); - * // => { 'a': 1, 'b': 2 } + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] * - * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); - * // => { 'a': 1, 'b': 2, 'c': 3 } + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] */ - function toPlainObject(value) { - return copyObject(value, keysIn(value)); + function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax(toInteger(size), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; } /** - * Converts `value` to a safe integer. A safe integer can be compared and - * represented correctly. + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. * * @static * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {number} Returns the converted integer. + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. * @example * - * _.toSafeInteger(3.2); - * // => 3 - * - * _.toSafeInteger(Number.MIN_VALUE); - * // => 0 - * - * _.toSafeInteger(Infinity); - * // => 9007199254740991 - * - * _.toSafeInteger('3.2'); - * // => 3 + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] */ - function toSafeInteger(value) { - return value - ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER) - : (value === 0 ? value : 0); + function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; } /** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. + * Creates a new array concatenating `array` with any additional arrays + * and/or values. * * @static * @memberOf _ * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. * @example * - * _.toString(null); - * // => '' + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); * - * _.toString(-0); - * // => '-0' + * console.log(other); + * // => [1, 2, 3, [4]] * - * _.toString([1, 2, 3]); - * // => '1,2,3' + * console.log(array); + * // => [1] */ - function toString(value) { - return value == null ? '' : baseToString(value); - } + function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; - /*------------------------------------------------------------------------*/ + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); + } /** - * Assigns own enumerable string keyed properties of source objects to the - * destination object. Source objects are applied from left to right. - * Subsequent sources overwrite property assignments of previous sources. + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. * - * **Note:** This method mutates `object` and is loosely based on - * [`Object.assign`](https://mdn.io/Object/assign). + * **Note:** Unlike `_.pullAll`, this method returns a new array. * * @static * @memberOf _ - * @since 0.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assignIn + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor * @example * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; - * - * _.assign({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'c': 3 } + * _.difference([2, 1], [2, 3]); + * // => [1] */ - var assign = createAssigner(function(object, source) { - if (isPrototype(source) || isArrayLike(source)) { - copyObject(source, keys(source), object); - return; - } - for (var key in source) { - if (hasOwnProperty.call(source, key)) { - assignValue(object, key, source[key]); - } - } + var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; }); /** - * This method is like `_.assign` except that it iterates over own and - * inherited source properties. + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). * - * **Note:** This method mutates `object`. + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 - * @alias extend - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.assign + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. * @example * - * function Foo() { - * this.a = 1; - * } - * - * function Bar() { - * this.c = 3; - * } - * - * Foo.prototype.b = 2; - * Bar.prototype.d = 4; + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] * - * _.assignIn({ 'a': 0 }, new Foo, new Bar); - * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] */ - var assignIn = createAssigner(function(object, source) { - copyObject(source, keysIn(source), object); + var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)) + : []; }); /** - * This method is like `_.assignIn` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). * - * **Note:** This method mutates `object`. + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. * * @static * @memberOf _ * @since 4.0.0 - * @alias extendWith - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignWith + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. * @example * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } - * - * var defaults = _.partialRight(_.assignInWith, customizer); + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] */ - var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keysIn(source), object, customizer); + var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; }); /** - * This method is like `_.assign` except that it accepts `customizer` - * which is invoked to produce the assigned values. If `customizer` returns - * `undefined`, assignment is handled by the method instead. The `customizer` - * is invoked with five arguments: (objValue, srcValue, key, object, source). - * - * **Note:** This method mutates `object`. + * Creates a slice of `array` with `n` elements dropped from the beginning. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. - * @see _.assignInWith + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. * @example * - * function customizer(objValue, srcValue) { - * return _.isUndefined(objValue) ? srcValue : objValue; - * } + * _.drop([1, 2, 3]); + * // => [2, 3] * - * var defaults = _.partialRight(_.assignWith, customizer); + * _.drop([1, 2, 3], 2); + * // => [3] * - * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] */ - var assignWith = createAssigner(function(object, source, srcIndex, customizer) { - copyObject(source, keys(source), object, customizer); - }); + function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); + } /** - * Creates an array of values corresponding to `paths` of `object`. + * Creates a slice of `array` with `n` elements dropped from the end. * * @static * @memberOf _ - * @since 1.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Array} Returns the picked values. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. * @example * - * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * _.dropRight([1, 2, 3]); + * // => [1, 2] * - * _.at(object, ['a[0].b.c', 'a[1]']); - * // => [3, 4] + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] */ - var at = flatRest(baseAt); + function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); + } /** - * Creates an object that inherits from the `prototype` object. If a - * `properties` object is given, its own enumerable string keyed properties - * are assigned to the created object. + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). * * @static * @memberOf _ - * @since 2.3.0 - * @category Object - * @param {Object} prototype The object to inherit from. - * @param {Object} [properties] The properties to assign to the object. - * @returns {Object} Returns the new object. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. * @example * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; * - * function Circle() { - * Shape.call(this); - * } + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] * - * Circle.prototype = _.create(Shape.prototype, { - * 'constructor': Circle - * }); + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] * - * var circle = new Circle; - * circle instanceof Circle; - * // => true + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] * - * circle instanceof Shape; - * // => true + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] */ - function create(prototype, properties) { - var result = baseCreate(prototype); - return properties == null ? result : baseAssign(result, properties); + function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true, true) + : []; } /** - * Assigns own and inherited enumerable string keyed properties of source - * objects to the destination object for all destination properties that - * resolve to `undefined`. Source objects are applied from left to right. - * Once a property is set, additional values of the same property are ignored. - * - * **Note:** This method mutates `object`. + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaultsDeep + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. * @example * - * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); - * // => { 'a': 1, 'b': 2 } - */ - var defaults = baseRest(function(object, sources) { - object = Object(object); - - var index = -1; - var length = sources.length; - var guard = length > 2 ? sources[2] : undefined; - - if (guard && isIterateeCall(sources[0], sources[1], guard)) { - length = 1; - } - - while (++index < length) { - var source = sources[index]; - var props = keysIn(source); - var propsIndex = -1; - var propsLength = props.length; - - while (++propsIndex < propsLength) { - var key = props[propsIndex]; - var value = object[key]; - - if (value === undefined || - (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) { - object[key] = source[key]; - } - } - } - - return object; - }); - - /** - * This method is like `_.defaults` except that it recursively assigns - * default properties. + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; * - * **Note:** This method mutates `object`. + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] * - * @static - * @memberOf _ - * @since 3.10.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. - * @see _.defaults - * @example + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] * - * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); - * // => { 'a': { 'b': 2, 'c': 3 } } + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] */ - var defaultsDeep = baseRest(function(args) { - args.push(undefined, customDefaultsMerge); - return apply(mergeWith, undefined, args); - }); + function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), true) + : []; + } /** - * This method is like `_.find` except that it returns the key of the first - * element `predicate` returns truthy for instead of the element itself. + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. * * @static * @memberOf _ - * @since 1.1.0 - * @category Object - * @param {Object} object The object to inspect. - * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. * @example * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; - * - * _.findKey(users, function(o) { return o.age < 40; }); - * // => 'barney' (iteration order is not guaranteed) + * var array = [1, 2, 3]; * - * // The `_.matches` iteratee shorthand. - * _.findKey(users, { 'age': 1, 'active': true }); - * // => 'pebbles' + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] * - * // The `_.matchesProperty` iteratee shorthand. - * _.findKey(users, ['active', false]); - * // => 'fred' + * _.fill(Array(3), 2); + * // => [2, 2, 2] * - * // The `_.property` iteratee shorthand. - * _.findKey(users, 'active'); - * // => 'barney' + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] */ - function findKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwn); + function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); } /** - * This method is like `_.findKey` except that it iterates over elements of - * a collection in the opposite order. + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. * * @static * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to inspect. + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. * @param {Function} [predicate=_.identity] The function invoked per iteration. - * @returns {string|undefined} Returns the key of the matched element, - * else `undefined`. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. * @example * - * var users = { - * 'barney': { 'age': 36, 'active': true }, - * 'fred': { 'age': 40, 'active': false }, - * 'pebbles': { 'age': 1, 'active': true } - * }; + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; * - * _.findLastKey(users, function(o) { return o.age < 40; }); - * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 * * // The `_.matches` iteratee shorthand. - * _.findLastKey(users, { 'age': 36, 'active': true }); - * // => 'barney' + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 * * // The `_.matchesProperty` iteratee shorthand. - * _.findLastKey(users, ['active', false]); - * // => 'fred' + * _.findIndex(users, ['active', false]); + * // => 0 * * // The `_.property` iteratee shorthand. - * _.findLastKey(users, 'active'); - * // => 'pebbles' + * _.findIndex(users, 'active'); + * // => 2 */ - function findLastKey(object, predicate) { - return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight); + function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseFindIndex(array, getIteratee(predicate, 3), index); } /** - * Iterates over own and inherited enumerable string keyed properties of an - * object and invokes `iteratee` for each property. The iteratee is invoked - * with three arguments: (value, key, object). Iteratee functions may exit - * iteration early by explicitly returning `false`. + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. * * @static * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forInRight + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forIn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). - */ - function forIn(object, iteratee) { - return object == null - ? object - : baseFor(object, getIteratee(iteratee, 3), keysIn); - } - - /** - * This method is like `_.forIn` except that it iterates over properties of - * `object` in the opposite order. + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; * - * @static - * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forIn - * @example + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 * - * Foo.prototype.c = 3; + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 * - * _.forInRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 */ - function forInRight(object, iteratee) { - return object == null - ? object - : baseForRight(object, getIteratee(iteratee, 3), keysIn); + function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax(length + index, 0) + : nativeMin(index, length - 1); + } + return baseFindIndex(array, getIteratee(predicate, 3), index, true); } /** - * Iterates over own enumerable string keyed properties of an object and - * invokes `iteratee` for each property. The iteratee is invoked with three - * arguments: (value, key, object). Iteratee functions may exit iteration - * early by explicitly returning `false`. + * Flattens `array` a single level deep. * * @static * @memberOf _ - * @since 0.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwnRight + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forOwn(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'a' then 'b' (iteration order is not guaranteed). + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] */ - function forOwn(object, iteratee) { - return object && baseForOwn(object, getIteratee(iteratee, 3)); + function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; } /** - * This method is like `_.forOwn` except that it iterates over properties of - * `object` in the opposite order. + * Recursively flattens `array`. * * @static * @memberOf _ - * @since 2.0.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns `object`. - * @see _.forOwn + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.forOwnRight(new Foo, function(value, key) { - * console.log(key); - * }); - * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] */ - function forOwnRight(object, iteratee) { - return object && baseForOwnRight(object, getIteratee(iteratee, 3)); + function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY) : []; } /** - * Creates an array of function property names from own enumerable properties - * of `object`. + * Recursively flatten `array` up to `depth` times. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functionsIn + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. * @example * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } + * var array = [1, [2, [3, [4]], 5]]; * - * Foo.prototype.c = _.constant('c'); + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] * - * _.functions(new Foo); - * // => ['a', 'b'] + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] */ - function functions(object) { - return object == null ? [] : baseFunctions(object, keys(object)); + function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); } /** - * Creates an array of function property names from own and inherited - * enumerable properties of `object`. + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. * * @static * @memberOf _ * @since 4.0.0 - * @category Object - * @param {Object} object The object to inspect. - * @returns {Array} Returns the function names. - * @see _.functions + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. * @example * - * function Foo() { - * this.a = _.constant('a'); - * this.b = _.constant('b'); - * } - * - * Foo.prototype.c = _.constant('c'); - * - * _.functionsIn(new Foo); - * // => ['a', 'b', 'c'] + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } */ - function functionsIn(object) { - return object == null ? [] : baseFunctions(object, keysIn(object)); + function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; } /** - * Gets the value at `path` of `object`. If the resolved value is - * `undefined`, the `defaultValue` is returned in its place. + * Gets the first element of `array`. * * @static * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to get. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. * @example * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.get(object, 'a[0].b.c'); - * // => 3 - * - * _.get(object, ['a', '0', 'b', 'c']); - * // => 3 + * _.head([1, 2, 3]); + * // => 1 * - * _.get(object, 'a.b.c', 'default'); - * // => 'default' + * _.head([]); + * // => undefined */ - function get(object, path, defaultValue) { - var result = object == null ? undefined : baseGet(object, path); - return result === undefined ? defaultValue : result; + function head(array) { + return (array && array.length) ? array[0] : undefined; } /** - * Checks if `path` is a direct property of `object`. + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. * @example * - * var object = { 'a': { 'b': 2 } }; - * var other = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.has(object, 'a'); - * // => true - * - * _.has(object, 'a.b'); - * // => true - * - * _.has(object, ['a', 'b']); - * // => true + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 * - * _.has(other, 'a'); - * // => false + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 */ - function has(object, path) { - return object != null && hasPath(object, path, baseHas); + function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax(length + index, 0); + } + return baseIndexOf(array, value, index); } /** - * Checks if `path` is a direct or inherited property of `object`. + * Gets all but the last element of `array`. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path to check. - * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. * @example * - * var object = _.create({ 'a': _.create({ 'b': 2 }) }); - * - * _.hasIn(object, 'a'); - * // => true - * - * _.hasIn(object, 'a.b'); - * // => true - * - * _.hasIn(object, ['a', 'b']); - * // => true - * - * _.hasIn(object, 'b'); - * // => false + * _.initial([1, 2, 3]); + * // => [1, 2] */ - function hasIn(object, path) { - return object != null && hasPath(object, path, baseHasIn); + function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; } /** - * Creates an object composed of the inverted keys and values of `object`. - * If `object` contains duplicate values, subsequent values overwrite - * property assignments of previous values. + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. * * @static * @memberOf _ - * @since 0.7.0 - * @category Object - * @param {Object} object The object to invert. - * @returns {Object} Returns the new inverted object. + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. * @example * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; - * - * _.invert(object); - * // => { '1': 'c', '2': 'b' } + * _.intersection([2, 1], [2, 3]); + * // => [2] */ - var invert = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } - - result[value] = key; - }, constant(identity)); + var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; + }); /** - * This method is like `_.invert` except that the inverted object is generated - * from the results of running each element of `object` thru `iteratee`. The - * corresponding inverted value of each inverted key is an array of keys - * responsible for generating the inverted value. The iteratee is invoked - * with one argument: (value). + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). * * @static * @memberOf _ - * @since 4.1.0 - * @category Object - * @param {Object} object The object to invert. + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. * @param {Function} [iteratee=_.identity] The iteratee invoked per element. - * @returns {Object} Returns the new inverted object. + * @returns {Array} Returns the new array of intersecting values. * @example * - * var object = { 'a': 1, 'b': 2, 'c': 1 }; - * - * _.invertBy(object); - * // => { '1': ['a', 'c'], '2': ['b'] } + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] * - * _.invertBy(object, function(value) { - * return 'group' + value; - * }); - * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] */ - var invertBy = createInverter(function(result, value, key) { - if (value != null && - typeof value.toString != 'function') { - value = nativeObjectToString.call(value); - } + var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); - if (hasOwnProperty.call(result, value)) { - result[value].push(key); + if (iteratee === last(mapped)) { + iteratee = undefined; } else { - result[value] = [key]; + mapped.pop(); } - }, getIteratee); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, getIteratee(iteratee, 2)) + : []; + }); /** - * Invokes the method at `path` of `object`. + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the method to invoke. - * @param {...*} [args] The arguments to invoke the method with. - * @returns {*} Returns the result of the invoked method. - * @example - * - * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; - * - * _.invoke(object, 'a[0].b.c.slice', 1, 3); - * // => [2, 3] - */ - var invoke = baseRest(baseInvoke); - - /** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * _.keys('hi'); - * // => ['0', '1'] + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] */ - function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); - } + var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; + }); /** - * Creates an array of the own and inherited enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. + * Converts all elements in `array` into a string separated by `separator`. * * @static * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keysIn(new Foo); - * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' */ - function keysIn(object) { - return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); + function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); } /** - * The opposite of `_.mapValues`; this method creates an object with the - * same values as `object` and keys generated by running each own enumerable - * string keyed property of `object` thru `iteratee`. The iteratee is invoked - * with three arguments: (value, key, object). + * Gets the last element of `array`. * * @static * @memberOf _ - * @since 3.8.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapValues + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. * @example * - * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { - * return key + value; - * }); - * // => { 'a1': 1, 'b2': 2 } + * _.last([1, 2, 3]); + * // => 3 */ - function mapKeys(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, iteratee(value, key, object), value); - }); - return result; + function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; } /** - * Creates an object with the same keys as `object` and values generated - * by running each own enumerable string keyed property of `object` thru - * `iteratee`. The iteratee is invoked with three arguments: - * (value, key, object). + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. * * @static * @memberOf _ - * @since 2.4.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @returns {Object} Returns the new mapped object. - * @see _.mapKeys + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. * @example * - * var users = { - * 'fred': { 'user': 'fred', 'age': 40 }, - * 'pebbles': { 'user': 'pebbles', 'age': 1 } - * }; - * - * _.mapValues(users, function(o) { return o.age; }); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 * - * // The `_.property` iteratee shorthand. - * _.mapValues(users, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 */ - function mapValues(object, iteratee) { - var result = {}; - iteratee = getIteratee(iteratee, 3); - - baseForOwn(object, function(value, key, object) { - baseAssignValue(result, key, iteratee(value, key, object)); - }); - return result; + function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); } /** - * This method is like `_.assign` except that it recursively merges own and - * inherited enumerable string keyed properties of source objects into the - * destination object. Source properties that resolve to `undefined` are - * skipped if a destination value exists. Array and plain object properties - * are merged recursively. Other objects and value types are overridden by - * assignment. Source objects are applied from left to right. Subsequent - * sources overwrite property assignments of previous sources. - * - * **Note:** This method mutates `object`. + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. * * @static * @memberOf _ - * @since 0.5.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} [sources] The source objects. - * @returns {Object} Returns `object`. + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. * @example * - * var object = { - * 'a': [{ 'b': 2 }, { 'd': 4 }] - * }; + * var array = ['a', 'b', 'c', 'd']; * - * var other = { - * 'a': [{ 'c': 3 }, { 'e': 5 }] - * }; + * _.nth(array, 1); + * // => 'b' * - * _.merge(object, other); - * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + * _.nth(array, -2); + * // => 'c'; */ - var merge = createAssigner(function(object, source, srcIndex) { - baseMerge(object, source, srcIndex); - }); + function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; + } /** - * This method is like `_.merge` except that it accepts `customizer` which - * is invoked to produce the merged values of the destination and source - * properties. If `customizer` returns `undefined`, merging is handled by the - * method instead. The `customizer` is invoked with six arguments: - * (objValue, srcValue, key, object, source, stack). + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. * - * **Note:** This method mutates `object`. + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The destination object. - * @param {...Object} sources The source objects. - * @param {Function} customizer The function to customize assigned values. - * @returns {Object} Returns `object`. + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. * @example * - * function customizer(objValue, srcValue) { - * if (_.isArray(objValue)) { - * return objValue.concat(srcValue); - * } - * } - * - * var object = { 'a': [1], 'b': [2] }; - * var other = { 'a': [3], 'b': [4] }; + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * - * _.mergeWith(object, other, customizer); - * // => { 'a': [1, 3], 'b': [2, 4] } + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] */ - var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { - baseMerge(object, source, srcIndex, customizer); - }); + var pull = baseRest(pullAll); /** - * The opposite of `_.pick`; this method creates an object composed of the - * own and inherited enumerable property paths of `object` that are not omitted. + * This method is like `_.pull` except that it accepts an array of values to remove. * - * **Note:** This method is considerably slower than `_.pick`. + * **Note:** Unlike `_.difference`, this method mutates `array`. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to omit. - * @returns {Object} Returns the new object. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. * @example * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; * - * _.omit(object, ['a', 'c']); - * // => { 'b': '2' } + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] */ - var omit = flatRest(function(object, paths) { - var result = {}; - if (object == null) { - return result; - } - var isDeep = false; - paths = arrayMap(paths, function(path) { - path = castPath(path, object); - isDeep || (isDeep = path.length > 1); - return path; - }); - copyObject(object, getAllKeysIn(object), result); - if (isDeep) { - result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); - } - var length = paths.length; - while (length--) { - baseUnset(result, paths[length]); - } - return result; - }); + function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; + } /** - * The opposite of `_.pickBy`; this method creates an object composed of - * the own and inherited enumerable string keyed properties of `object` that - * `predicate` doesn't return truthy for. The predicate is invoked with two - * arguments: (value, key). + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. * * @static * @memberOf _ * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. * @example * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; * - * _.omitBy(object, _.isNumber); - * // => { 'b': '2' } + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] */ - function omitBy(object, predicate) { - return pickBy(object, negate(getIteratee(predicate))); + function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, getIteratee(iteratee, 2)) + : array; } /** - * Creates an object composed of the picked `object` properties. + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The source object. - * @param {...(string|string[])} [paths] The property paths to pick. - * @returns {Object} Returns the new object. + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. * @example * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; * - * _.pick(object, ['a', 'c']); - * // => { 'a': 1, 'c': 3 } + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] */ - var pick = flatRest(function(object, paths) { - return object == null ? {} : basePick(object, paths); - }); + function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; + } /** - * Creates an object composed of the `object` properties `predicate` returns - * truthy for. The predicate is invoked with two arguments: (value, key). + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The source object. - * @param {Function} [predicate=_.identity] The function invoked per property. - * @returns {Object} Returns the new object. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. * @example * - * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); * - * _.pickBy(object, _.isNumber); - * // => { 'a': 1, 'c': 3 } + * console.log(array); + * // => ['a', 'c'] + * + * console.log(pulled); + * // => ['b', 'd'] */ - function pickBy(object, predicate) { - if (object == null) { - return {}; - } - var props = arrayMap(getAllKeysIn(object), function(prop) { - return [prop]; - }); - predicate = getIteratee(predicate); - return basePickBy(object, props, function(value, path) { - return predicate(value, path[0]); - }); - } + var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, + result = baseAt(array, indexes); + + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + + return result; + }); /** - * This method is like `_.get` except that if the resolved value is a - * function it's invoked with the `this` binding of its parent object and - * its result is returned. + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). + * + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @param {Array|string} path The path of the property to resolve. - * @param {*} [defaultValue] The value returned for `undefined` resolved values. - * @returns {*} Returns the resolved value. + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. * @example * - * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; - * - * _.result(object, 'a[0].b.c1'); - * // => 3 - * - * _.result(object, 'a[0].b.c2'); - * // => 4 + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); * - * _.result(object, 'a[0].b.c3', 'default'); - * // => 'default' + * console.log(array); + * // => [1, 3] * - * _.result(object, 'a[0].b.c3', _.constant('default')); - * // => 'default' + * console.log(evens); + * // => [2, 4] */ - function result(object, path, defaultValue) { - path = castPath(path, object); - + function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; + } var index = -1, - length = path.length; + indexes = [], + length = array.length; - // Ensure the loop is entered when path is empty. - if (!length) { - length = 1; - object = undefined; - } + predicate = getIteratee(predicate, 3); while (++index < length) { - var value = object == null ? undefined : object[toKey(path[index])]; - if (value === undefined) { - index = length; - value = defaultValue; + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); } - object = isFunction(value) ? value.call(object) : value; } - return object; + basePullAt(array, indexes); + return result; } /** - * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, - * it's created. Arrays are created for missing index properties while objects - * are created for all other missing properties. Use `_.setWith` to customize - * `path` creation. + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. * - * **Note:** This method mutates `object`. + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). * * @static * @memberOf _ - * @since 3.7.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @returns {Object} Returns `object`. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. * @example * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * var array = [1, 2, 3]; * - * _.set(object, 'a[0].b.c', 4); - * console.log(object.a[0].b.c); - * // => 4 + * _.reverse(array); + * // => [3, 2, 1] * - * _.set(object, ['x', '0', 'y', 'z'], 5); - * console.log(object.x[0].y.z); - * // => 5 + * console.log(array); + * // => [3, 2, 1] */ - function set(object, path, value) { - return object == null ? object : baseSet(object, path, value); + function reverse(array) { + return array == null ? array : nativeReverse.call(array); } /** - * This method is like `_.set` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). + * Creates a slice of `array` from `start` up to, but not including, `end`. * - * **Note:** This method mutates `object`. + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ + function slice(array, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); + } + + /** + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. * * @static * @memberOf _ - * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {*} value The value to set. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. * @example * - * var object = {}; - * - * _.setWith(object, '[0][1]', 'a', Object); - * // => { '0': { '1': 'a' } } + * _.sortedIndex([30, 50], 40); + * // => 1 */ - function setWith(object, path, value, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseSet(object, path, value, customizer); + function sortedIndex(array, value) { + return baseSortedIndex(array, value); } /** - * Creates an array of own enumerable string keyed-value pairs for `object` - * which can be consumed by `_.fromPairs`. If `object` is a map or set, its - * entries are returned. + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 - * @alias entries - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } + * var objects = [{ 'x': 4 }, { 'x': 5 }]; * - * Foo.prototype.c = 3; + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 * - * _.toPairs(new Foo); - * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 */ - var toPairs = createToPairs(keys); + function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2)); + } /** - * Creates an array of own and inherited enumerable string keyed-value pairs - * for `object` which can be consumed by `_.fromPairs`. If `object` is a map - * or set, its entries are returned. + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. * * @static * @memberOf _ * @since 4.0.0 - * @alias entriesIn - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the key-value pairs. + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.toPairsIn(new Foo); - * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 */ - var toPairsIn = createToPairs(keysIn); + function sortedIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; + } /** - * An alternative to `_.reduce`; this method transforms `object` to a new - * `accumulator` object which is the result of running each of its own - * enumerable string keyed properties thru `iteratee`, with each invocation - * potentially mutating the `accumulator` object. If `accumulator` is not - * provided, a new object with the same `[[Prototype]]` will be used. The - * iteratee is invoked with four arguments: (accumulator, value, key, object). - * Iteratee functions may exit iteration early by explicitly returning `false`. + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. * * @static * @memberOf _ - * @since 1.3.0 - * @category Object - * @param {Object} object The object to iterate over. - * @param {Function} [iteratee=_.identity] The function invoked per iteration. - * @param {*} [accumulator] The custom accumulator value. - * @returns {*} Returns the accumulated value. + * @since 3.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. * @example * - * _.transform([2, 3, 4], function(result, n) { - * result.push(n *= n); - * return n % 2 == 0; - * }, []); - * // => [4, 9] - * - * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { - * (result[value] || (result[value] = [])).push(key); - * }, {}); - * // => { '1': ['a', 'c'], '2': ['b'] } + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 */ - function transform(object, iteratee, accumulator) { - var isArr = isArray(object), - isArrLike = isArr || isBuffer(object) || isTypedArray(object); - - iteratee = getIteratee(iteratee, 4); - if (accumulator == null) { - var Ctor = object && object.constructor; - if (isArrLike) { - accumulator = isArr ? new Ctor : []; - } - else if (isObject(object)) { - accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {}; - } - else { - accumulator = {}; - } - } - (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) { - return iteratee(accumulator, value, index, object); - }); - return accumulator; + function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); } /** - * Removes the property at `path` of `object`. - * - * **Note:** This method mutates `object`. + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). * * @static * @memberOf _ * @since 4.0.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to unset. - * @returns {boolean} Returns `true` if the property is deleted, else `false`. + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. * @example * - * var object = { 'a': [{ 'b': { 'c': 7 } }] }; - * _.unset(object, 'a[0].b.c'); - * // => true - * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; + * var objects = [{ 'x': 4 }, { 'x': 5 }]; * - * _.unset(object, ['a', '0', 'b', 'c']); - * // => true + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 * - * console.log(object); - * // => { 'a': [{ 'b': {} }] }; + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 */ - function unset(object, path) { - return object == null ? true : baseUnset(object, path); + function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true); } /** - * This method is like `_.set` except that accepts `updater` to produce the - * value to set. Use `_.updateWith` to customize `path` creation. The `updater` - * is invoked with one argument: (value). - * - * **Note:** This method mutates `object`. + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. * * @static * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @returns {Object} Returns `object`. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. * @example * - * var object = { 'a': [{ 'b': { 'c': 3 } }] }; - * - * _.update(object, 'a[0].b.c', function(n) { return n * n; }); - * console.log(object.a[0].b.c); - * // => 9 - * - * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; }); - * console.log(object.x[0].y.z); - * // => 0 + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 */ - function update(object, path, updater) { - return object == null ? object : baseUpdate(object, path, castFunction(updater)); + function sortedLastIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; } /** - * This method is like `_.update` except that it accepts `customizer` which is - * invoked to produce the objects of `path`. If `customizer` returns `undefined` - * path creation is handled by the method instead. The `customizer` is invoked - * with three arguments: (nsValue, key, nsObject). - * - * **Note:** This method mutates `object`. + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. * * @static * @memberOf _ - * @since 4.6.0 - * @category Object - * @param {Object} object The object to modify. - * @param {Array|string} path The path of the property to set. - * @param {Function} updater The function to produce the updated value. - * @param {Function} [customizer] The function to customize assigned values. - * @returns {Object} Returns `object`. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. * @example * - * var object = {}; - * - * _.updateWith(object, '[0][1]', _.constant('a'), Object); - * // => { '0': { '1': 'a' } } + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] */ - function updateWith(object, path, updater, customizer) { - customizer = typeof customizer == 'function' ? customizer : undefined; - return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer); + function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; } /** - * Creates an array of the own enumerable string keyed property values of `object`. - * - * **Note:** Non-object values are coerced to objects. + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. * * @static - * @since 0.1.0 * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.values(new Foo); - * // => [1, 2] (iteration order is not guaranteed) - * - * _.values('hi'); - * // => ['h', 'i'] + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] */ - function values(object) { - return object == null ? [] : baseValues(object, keys(object)); + function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, getIteratee(iteratee, 2)) + : []; } /** - * Creates an array of the own and inherited enumerable string keyed property - * values of `object`. - * - * **Note:** Non-object values are coerced to objects. + * Gets all but the first element of `array`. * * @static * @memberOf _ - * @since 3.0.0 - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property values. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. * @example * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.valuesIn(new Foo); - * // => [1, 2, 3] (iteration order is not guaranteed) + * _.tail([1, 2, 3]); + * // => [2, 3] */ - function valuesIn(object) { - return object == null ? [] : baseValues(object, keysIn(object)); + function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; } - /*------------------------------------------------------------------------*/ - /** - * Clamps `number` within the inclusive `lower` and `upper` bounds. + * Creates a slice of `array` with `n` elements taken from the beginning. * * @static * @memberOf _ - * @since 4.0.0 - * @category Number - * @param {number} number The number to clamp. - * @param {number} [lower] The lower bound. - * @param {number} upper The upper bound. - * @returns {number} Returns the clamped number. + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. * @example * - * _.clamp(-10, -5, 5); - * // => -5 + * _.take([1, 2, 3]); + * // => [1] * - * _.clamp(10, -5, 5); - * // => 5 + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] */ - function clamp(number, lower, upper) { - if (upper === undefined) { - upper = lower; - lower = undefined; - } - if (upper !== undefined) { - upper = toNumber(upper); - upper = upper === upper ? upper : 0; - } - if (lower !== undefined) { - lower = toNumber(lower); - lower = lower === lower ? lower : 0; + function take(array, n, guard) { + if (!(array && array.length)) { + return []; } - return baseClamp(toNumber(number), lower, upper); + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); } /** - * Checks if `n` is between `start` and up to, but not including, `end`. If - * `end` is not specified, it's set to `start` with `start` then set to `0`. - * If `start` is greater than `end` the params are swapped to support - * negative ranges. + * Creates a slice of `array` with `n` elements taken from the end. * * @static * @memberOf _ - * @since 3.3.0 - * @category Number - * @param {number} number The number to check. - * @param {number} [start=0] The start of the range. - * @param {number} end The end of the range. - * @returns {boolean} Returns `true` if `number` is in the range, else `false`. - * @see _.range, _.rangeRight + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. * @example * - * _.inRange(3, 2, 4); - * // => true - * - * _.inRange(4, 8); - * // => true - * - * _.inRange(4, 2); - * // => false - * - * _.inRange(2, 2); - * // => false + * _.takeRight([1, 2, 3]); + * // => [3] * - * _.inRange(1.2, 2); - * // => true + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] * - * _.inRange(5.2, 4); - * // => false + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] * - * _.inRange(-3, -2, -6); - * // => true + * _.takeRight([1, 2, 3], 0); + * // => [] */ - function inRange(number, start, end) { - start = toFinite(start); - if (end === undefined) { - end = start; - start = 0; - } else { - end = toFinite(end); + function takeRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; } - number = toNumber(number); - return baseInRange(number, start, end); + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); } /** - * Produces a random number between the inclusive `lower` and `upper` bounds. - * If only one argument is provided a number between `0` and the given number - * is returned. If `floating` is `true`, or either `lower` or `upper` are - * floats, a floating-point number is returned instead of an integer. - * - * **Note:** JavaScript follows the IEEE-754 standard for resolving - * floating-point values which can produce unexpected results. + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). * * @static * @memberOf _ - * @since 0.7.0 - * @category Number - * @param {number} [lower=0] The lower bound. - * @param {number} [upper=1] The upper bound. - * @param {boolean} [floating] Specify returning a floating-point number. - * @returns {number} Returns the random number. + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. * @example * - * _.random(0, 5); - * // => an integer between 0 and 5 - * - * _.random(5); - * // => also an integer between 0 and 5 + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; * - * _.random(5, true); - * // => a floating-point number between 0 and 5 + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] * - * _.random(1.2, 5.2); - * // => a floating-point number between 1.2 and 5.2 - */ - function random(lower, upper, floating) { - if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { - upper = floating = undefined; - } - if (floating === undefined) { - if (typeof upper == 'boolean') { - floating = upper; - upper = undefined; - } - else if (typeof lower == 'boolean') { - floating = lower; - lower = undefined; - } - } - if (lower === undefined && upper === undefined) { - lower = 0; - upper = 1; - } - else { - lower = toFinite(lower); - if (upper === undefined) { - upper = lower; - lower = 0; - } else { - upper = toFinite(upper); - } - } - if (lower > upper) { - var temp = lower; - lower = upper; - upper = temp; - } - if (floating || lower % 1 || upper % 1) { - var rand = nativeRandom(); - return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); - } - return baseRandom(lower, upper); + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] + */ + function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3), false, true) + : []; } - /*------------------------------------------------------------------------*/ - /** - * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). * * @static * @memberOf _ * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the camel cased string. + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. * @example * - * _.camelCase('Foo Bar'); - * // => 'fooBar' + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; * - * _.camelCase('--foo-bar--'); - * // => 'fooBar' + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] * - * _.camelCase('__FOO_BAR__'); - * // => 'fooBar' + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] */ - var camelCase = createCompounder(function(result, word, index) { - word = word.toLowerCase(); - return result + (index ? capitalize(word) : word); - }); + function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, getIteratee(predicate, 3)) + : []; + } /** - * Converts the first character of `string` to upper case and the remaining - * to lower case. + * Creates an array of unique values, in order, from all given arrays using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to capitalize. - * @returns {string} Returns the capitalized string. + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of combined values. * @example * - * _.capitalize('FRED'); - * // => 'Fred' + * _.union([2], [1, 2]); + * // => [2, 1] */ - function capitalize(string) { - return upperFirst(toString(string).toLowerCase()); - } + var union = baseRest(function(arrays) { + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true)); + }); /** - * Deburrs `string` by converting - * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) - * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) - * letters to basic Latin letters and removing - * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * This method is like `_.union` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which uniqueness is computed. Result values are chosen from the first + * array in which the value occurs. The iteratee is invoked with one argument: + * (value). * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to deburr. - * @returns {string} Returns the deburred string. + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of combined values. * @example * - * _.deburr('déjà vu'); - * // => 'deja vu' + * _.unionBy([2.1], [1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] */ - function deburr(string) { - string = toString(string); - return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); - } + var unionBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2)); + }); /** - * Checks if `string` ends with the given target string. + * This method is like `_.union` except that it accepts `comparator` which + * is invoked to compare elements of `arrays`. Result values are chosen from + * the first array in which the value occurs. The comparator is invoked + * with two arguments: (arrVal, othVal). * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=string.length] The position to search up to. - * @returns {boolean} Returns `true` if `string` ends with `target`, - * else `false`. + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of combined values. * @example * - * _.endsWith('abc', 'c'); - * // => true - * - * _.endsWith('abc', 'b'); - * // => false + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * _.endsWith('abc', 'b', 2); - * // => true + * _.unionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ - function endsWith(string, target, position) { - string = toString(string); - target = baseToString(target); - - var length = string.length; - position = position === undefined - ? length - : baseClamp(toInteger(position), 0, length); - - var end = position; - position -= target.length; - return position >= 0 && string.slice(position, end) == target; - } + var unionWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator); + }); /** - * Converts the characters "&", "<", ">", '"', and "'" in `string` to their - * corresponding HTML entities. - * - * **Note:** No other characters are escaped. To escape additional - * characters use a third-party library like [_he_](https://mths.be/he). - * - * Though the ">" character is escaped for symmetry, characters like - * ">" and "/" don't need escaping in HTML and have no special meaning - * unless they're part of a tag or unquoted attribute value. See - * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) - * (under "semi-related fun fact") for more details. - * - * When working with HTML you should always - * [quote attribute values](http://wonko.com/post/html-escaping) to reduce - * XSS vectors. + * Creates a duplicate-free version of an array, using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons, in which only the first occurrence of each element + * is kept. The order of result values is determined by the order they occur + * in the array. * * @static - * @since 0.1.0 * @memberOf _ - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. * @example * - * _.escape('fred, barney, & pebbles'); - * // => 'fred, barney, & pebbles' + * _.uniq([2, 1, 2]); + * // => [2, 1] */ - function escape(string) { - string = toString(string); - return (string && reHasUnescapedHtml.test(string)) - ? string.replace(reUnescapedHtml, escapeHtmlChar) - : string; + function uniq(array) { + return (array && array.length) ? baseUniq(array) : []; } /** - * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", - * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * This method is like `_.uniq` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * uniqueness is computed. The order of result values is determined by the + * order they occur in the array. The iteratee is invoked with one argument: + * (value). * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to escape. - * @returns {string} Returns the escaped string. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. * @example * - * _.escapeRegExp('[lodash](https://lodash.com/)'); - * // => '\[lodash\]\(https://lodash\.com/\)' + * _.uniqBy([2.1, 1.2, 2.3], Math.floor); + * // => [2.1, 1.2] + * + * // The `_.property` iteratee shorthand. + * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }, { 'x': 2 }] */ - function escapeRegExp(string) { - string = toString(string); - return (string && reHasRegExpChar.test(string)) - ? string.replace(reRegExpChar, '\\$&') - : string; + function uniqBy(array, iteratee) { + return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : []; } /** - * Converts `string` to - * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * This method is like `_.uniq` except that it accepts `comparator` which + * is invoked to compare elements of `array`. The order of result values is + * determined by the order they occur in the array.The comparator is invoked + * with two arguments: (arrVal, othVal). * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the kebab cased string. + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new duplicate free array. * @example * - * _.kebabCase('Foo Bar'); - * // => 'foo-bar' - * - * _.kebabCase('fooBar'); - * // => 'foo-bar' + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * _.kebabCase('__FOO_BAR__'); - * // => 'foo-bar' + * _.uniqWith(objects, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }] */ - var kebabCase = createCompounder(function(result, word, index) { - return result + (index ? '-' : '') + word.toLowerCase(); - }); + function uniqWith(array, comparator) { + comparator = typeof comparator == 'function' ? comparator : undefined; + return (array && array.length) ? baseUniq(array, undefined, comparator) : []; + } /** - * Converts `string`, as space separated words, to lower case. + * This method is like `_.zip` except that it accepts an array of grouped + * elements and creates an array regrouping the elements to their pre-zip + * configuration. * * @static * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the lower cased string. + * @since 1.2.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @returns {Array} Returns the new array of regrouped elements. * @example * - * _.lowerCase('--Foo-Bar--'); - * // => 'foo bar' - * - * _.lowerCase('fooBar'); - * // => 'foo bar' + * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] * - * _.lowerCase('__FOO_BAR__'); - * // => 'foo bar' + * _.unzip(zipped); + * // => [['a', 'b'], [1, 2], [true, false]] */ - var lowerCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + word.toLowerCase(); - }); + function unzip(array) { + if (!(array && array.length)) { + return []; + } + var length = 0; + array = arrayFilter(array, function(group) { + if (isArrayLikeObject(group)) { + length = nativeMax(group.length, length); + return true; + } + }); + return baseTimes(length, function(index) { + return arrayMap(array, baseProperty(index)); + }); + } /** - * Converts the first character of `string` to lower case. + * This method is like `_.unzip` except that it accepts `iteratee` to specify + * how regrouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). * * @static * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the converted string. + * @since 3.8.0 + * @category Array + * @param {Array} array The array of grouped elements to process. + * @param {Function} [iteratee=_.identity] The function to combine + * regrouped values. + * @returns {Array} Returns the new array of regrouped elements. * @example * - * _.lowerFirst('Fred'); - * // => 'fred' + * var zipped = _.zip([1, 2], [10, 20], [100, 200]); + * // => [[1, 10, 100], [2, 20, 200]] * - * _.lowerFirst('FRED'); - * // => 'fRED' + * _.unzipWith(zipped, _.add); + * // => [3, 30, 300] */ - var lowerFirst = createCaseFirst('toLowerCase'); + function unzipWith(array, iteratee) { + if (!(array && array.length)) { + return []; + } + var result = unzip(array); + if (iteratee == null) { + return result; + } + return arrayMap(result, function(group) { + return apply(iteratee, undefined, group); + }); + } /** - * Pads `string` on the left and right sides if it's shorter than `length`. - * Padding characters are truncated if they can't be evenly divided by `length`. + * Creates an array excluding all given values using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.pull`, this method returns a new array. * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...*} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.xor * @example * - * _.pad('abc', 8); - * // => ' abc ' + * _.without([2, 1, 2, 3], 1, 2); + * // => [3] + */ + var without = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, values) + : []; + }); + + /** + * Creates an array of unique values that is the + * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference) + * of the given arrays. The order of result values is determined by the order + * they occur in the arrays. * - * _.pad('abc', 8, '_-'); - * // => '_-abc_-_' + * @static + * @memberOf _ + * @since 2.4.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of filtered values. + * @see _.difference, _.without + * @example * - * _.pad('abc', 3); - * // => 'abc' + * _.xor([2, 1], [2, 3]); + * // => [1, 3] */ - function pad(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - if (!length || strLength >= length) { - return string; - } - var mid = (length - strLength) / 2; - return ( - createPadding(nativeFloor(mid), chars) + - string + - createPadding(nativeCeil(mid), chars) - ); - } + var xor = baseRest(function(arrays) { + return baseXor(arrayFilter(arrays, isArrayLikeObject)); + }); /** - * Pads `string` on the right side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. + * This method is like `_.xor` except that it accepts `iteratee` which is + * invoked for each element of each `arrays` to generate the criterion by + * which by which they're compared. The order of result values is determined + * by the order they occur in the arrays. The iteratee is invoked with one + * argument: (value). * * @static * @memberOf _ * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. * @example * - * _.padEnd('abc', 6); - * // => 'abc ' - * - * _.padEnd('abc', 6, '_-'); - * // => 'abc_-_' + * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2, 3.4] * - * _.padEnd('abc', 3); - * // => 'abc' + * // The `_.property` iteratee shorthand. + * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] */ - function padEnd(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (string + createPadding(length - strLength, chars)) - : string; - } + var xorBy = baseRest(function(arrays) { + var iteratee = last(arrays); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2)); + }); /** - * Pads `string` on the left side if it's shorter than `length`. Padding - * characters are truncated if they exceed `length`. + * This method is like `_.xor` except that it accepts `comparator` which is + * invoked to compare elements of `arrays`. The order of result values is + * determined by the order they occur in the arrays. The comparator is invoked + * with two arguments: (arrVal, othVal). * * @static * @memberOf _ * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to pad. - * @param {number} [length=0] The padding length. - * @param {string} [chars=' '] The string used as padding. - * @returns {string} Returns the padded string. + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. * @example * - * _.padStart('abc', 6); - * // => ' abc' - * - * _.padStart('abc', 6, '_-'); - * // => '_-_abc' + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; * - * _.padStart('abc', 3); - * // => 'abc' + * _.xorWith(objects, others, _.isEqual); + * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }] */ - function padStart(string, length, chars) { - string = toString(string); - length = toInteger(length); - - var strLength = length ? stringSize(string) : 0; - return (length && strLength < length) - ? (createPadding(length - strLength, chars) + string) - : string; - } + var xorWith = baseRest(function(arrays) { + var comparator = last(arrays); + comparator = typeof comparator == 'function' ? comparator : undefined; + return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator); + }); /** - * Converts `string` to an integer of the specified radix. If `radix` is - * `undefined` or `0`, a `radix` of `10` is used unless `value` is a - * hexadecimal, in which case a `radix` of `16` is used. - * - * **Note:** This method aligns with the - * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * Creates an array of grouped elements, the first of which contains the + * first elements of the given arrays, the second of which contains the + * second elements of the given arrays, and so on. * * @static * @memberOf _ - * @since 1.1.0 - * @category String - * @param {string} string The string to convert. - * @param {number} [radix=10] The radix to interpret `value` by. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {number} Returns the converted integer. + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @returns {Array} Returns the new array of grouped elements. * @example * - * _.parseInt('08'); - * // => 8 - * - * _.map(['6', '08', '10'], _.parseInt); - * // => [6, 8, 10] + * _.zip(['a', 'b'], [1, 2], [true, false]); + * // => [['a', 1, true], ['b', 2, false]] */ - function parseInt(string, radix, guard) { - if (guard || radix == null) { - radix = 0; - } else if (radix) { - radix = +radix; - } - return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0); - } + var zip = baseRest(unzip); /** - * Repeats the given string `n` times. + * This method is like `_.fromPairs` except that it accepts two arrays, + * one of property identifiers and one of corresponding values. * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to repeat. - * @param {number} [n=1] The number of times to repeat the string. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the repeated string. + * @since 0.4.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. * @example * - * _.repeat('*', 3); - * // => '***' - * - * _.repeat('abc', 2); - * // => 'abcabc' - * - * _.repeat('abc', 0); - * // => '' + * _.zipObject(['a', 'b'], [1, 2]); + * // => { 'a': 1, 'b': 2 } */ - function repeat(string, n, guard) { - if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { - n = 1; - } else { - n = toInteger(n); - } - return baseRepeat(toString(string), n); + function zipObject(props, values) { + return baseZipObject(props || [], values || [], assignValue); } /** - * Replaces matches for `pattern` in `string` with `replacement`. - * - * **Note:** This method is based on - * [`String#replace`](https://mdn.io/String/replace). + * This method is like `_.zipObject` except that it supports property paths. * * @static * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to modify. - * @param {RegExp|string} pattern The pattern to replace. - * @param {Function|string} replacement The match replacement. - * @returns {string} Returns the modified string. + * @since 4.1.0 + * @category Array + * @param {Array} [props=[]] The property identifiers. + * @param {Array} [values=[]] The property values. + * @returns {Object} Returns the new object. * @example * - * _.replace('Hi Fred', 'Fred', 'Barney'); - * // => 'Hi Barney' + * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]); + * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } } */ - function replace() { - var args = arguments, - string = toString(args[0]); - - return args.length < 3 ? string : string.replace(args[1], args[2]); + function zipObjectDeep(props, values) { + return baseZipObject(props || [], values || [], baseSet); } /** - * Converts `string` to - * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * This method is like `_.zip` except that it accepts `iteratee` to specify + * how grouped values should be combined. The iteratee is invoked with the + * elements of each group: (...group). * * @static * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the snake cased string. + * @since 3.8.0 + * @category Array + * @param {...Array} [arrays] The arrays to process. + * @param {Function} [iteratee=_.identity] The function to combine + * grouped values. + * @returns {Array} Returns the new array of grouped elements. * @example * - * _.snakeCase('Foo Bar'); - * // => 'foo_bar' - * - * _.snakeCase('fooBar'); - * // => 'foo_bar' - * - * _.snakeCase('--FOO-BAR--'); - * // => 'foo_bar' + * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) { + * return a + b + c; + * }); + * // => [111, 222] */ - var snakeCase = createCompounder(function(result, word, index) { - return result + (index ? '_' : '') + word.toLowerCase(); + var zipWith = baseRest(function(arrays) { + var length = arrays.length, + iteratee = length > 1 ? arrays[length - 1] : undefined; + + iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined; + return unzipWith(arrays, iteratee); }); + /*------------------------------------------------------------------------*/ + /** - * Splits `string` by `separator`. - * - * **Note:** This method is based on - * [`String#split`](https://mdn.io/String/split). + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. * * @static * @memberOf _ - * @since 4.0.0 - * @category String - * @param {string} [string=''] The string to split. - * @param {RegExp|string} separator The separator pattern to split by. - * @param {number} [limit] The length to truncate results to. - * @returns {Array} Returns the string segments. + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * _.split('a-b-c', '-', 2); - * // => ['a', 'b'] + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' */ - function split(string, separator, limit) { - if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { - separator = limit = undefined; - } - limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0; - if (!limit) { - return []; - } - string = toString(string); - if (string && ( - typeof separator == 'string' || - (separator != null && !isRegExp(separator)) - )) { - separator = baseToString(separator); - if (!separator && hasUnicode(string)) { - return castSlice(stringToArray(string), 0, limit); - } - } - return string.split(separator, limit); + function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; } /** - * Converts `string` to - * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. * * @static * @memberOf _ - * @since 3.1.0 - * @category String - * @param {string} [string=''] The string to convert. - * @returns {string} Returns the start cased string. + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. * @example * - * _.startCase('--foo-bar--'); - * // => 'Foo Bar' - * - * _.startCase('fooBar'); - * // => 'Foo Bar' - * - * _.startCase('__FOO_BAR__'); - * // => 'FOO BAR' + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] */ - var startCase = createCompounder(function(result, word, index) { - return result + (index ? ' ' : '') + upperFirst(word); - }); + function tap(value, interceptor) { + interceptor(value); + return value; + } /** - * Checks if `string` starts with the given target string. + * This method is like `_.tap` except that it returns the result of `interceptor`. + * The purpose of this method is to "pass thru" values replacing intermediate + * results in a method chain sequence. * * @static * @memberOf _ * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to inspect. - * @param {string} [target] The string to search for. - * @param {number} [position=0] The position to search from. - * @returns {boolean} Returns `true` if `string` starts with `target`, - * else `false`. + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns the result of `interceptor`. * @example * - * _.startsWith('abc', 'a'); - * // => true - * - * _.startsWith('abc', 'b'); - * // => false - * - * _.startsWith('abc', 'b', 1); - * // => true + * _(' abc ') + * .chain() + * .trim() + * .thru(function(value) { + * return [value]; + * }) + * .value(); + * // => ['abc'] */ - function startsWith(string, target, position) { - string = toString(string); - position = position == null - ? 0 - : baseClamp(toInteger(position), 0, string.length); - - target = baseToString(target); - return string.slice(position, position + target.length) == target; + function thru(value, interceptor) { + return interceptor(value); } /** - * Creates a compiled template function that can interpolate data properties - * in "interpolate" delimiters, HTML-escape interpolated data properties in - * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data - * properties may be accessed as free variables in the template. If a setting - * object is given, it takes precedence over `_.templateSettings` values. - * - * **Note:** In the development build `_.template` utilizes - * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) - * for easier debugging. - * - * For more information on precompiling templates see - * [lodash's custom builds documentation](https://lodash.com/custom-builds). - * - * For more information on Chrome extension sandboxes see - * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * This method is the wrapper version of `_.at`. * - * @static - * @since 0.1.0 + * @name at * @memberOf _ - * @category String - * @param {string} [string=''] The template string. - * @param {Object} [options={}] The options object. - * @param {RegExp} [options.escape=_.templateSettings.escape] - * The HTML "escape" delimiter. - * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] - * The "evaluate" delimiter. - * @param {Object} [options.imports=_.templateSettings.imports] - * An object to import into the template as free variables. - * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] - * The "interpolate" delimiter. - * @param {string} [options.sourceURL='lodash.templateSources[n]'] - * The sourceURL of the compiled template. - * @param {string} [options.variable='obj'] - * The data object variable name. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {Function} Returns the compiled template function. + * @since 1.0.0 + * @category Seq + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new `lodash` wrapper instance. * @example * - * // Use the "interpolate" delimiter to create a compiled template. - * var compiled = _.template('hello <%= user %>!'); - * compiled({ 'user': 'fred' }); - * // => 'hello fred!' - * - * // Use the HTML "escape" delimiter to escape data property values. - * var compiled = _.template('<%- value %>'); - * compiled({ 'value': '